file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
pragma solidity ^0.5.2;
interface Token {
function transfer(address to, uint256 value) external returns (bool);
function balanceOf(address who) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
}
contract onlyOwner {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
modifier isOwner {
require(msg.sender == owner);
_;
}
}
contract SwapDistributor is onlyOwner{
Token token;
address distTokens;
constructor() public{
address _contract = 0xBA3a79D758f19eFe588247388754b8e4d6EddA81;
distTokens = _contract;
token = Token(_contract);
}
function setTokenContract(address _contract) isOwner public{
distTokens = _contract;
token = Token(_contract);
}
function getTokenContract() public view returns(address){
return distTokens;
}
/**
* @dev Values must be in the minimal unit (in wei in case of 18 decimals)
*
* **/
function sendAmount(address[] memory _users, uint256[] memory _values) isOwner public returns(bool){
require(_users.length == _values.length, "Lenght of users and values must be equal");
uint256 total_balance = 0;
for(uint i=0; i< _values.length; i++){
total_balance = total_balance + _values[i];
}
require(token.balanceOf(address(this)) >= total_balance, "Distributor balance needs to be higher than total distributed values");
for(uint i=0; i< _users.length; i++){
token.transfer(_users[i], _values[i]);
}
return true;
}
/**
* @dev Values must be in the minimal unit (in wei in case of 18 decimals). Set the allowance to the contract be
* able to do the transfer
*
* **/
function sendAmountAllowance(address[] memory _users, uint256[] memory _values) public returns(bool){
require(_users.length == _values.length, "Lenght of users and values must be equal");
require(msg.sender != address(0));
uint256 total_balance = 0;
for(uint i=0; i< _values.length; i++){
total_balance = total_balance + _values[i];
}
require(token.balanceOf(msg.sender) >= total_balance, "Sender balance needs to be higher than total distributed values");
require(token.allowance(msg.sender, address(this)) >= total_balance, "Allowance balance to the distributor needs to be higher than total distributed values");
for(uint i=0; i< _users.length; i++){
token.transferFrom(msg.sender, _users[i], _values[i]);
}
return true;
}
/**
* @dev Use this if your token is different from the one supported natively in this contract, set the allowance for the token
* contract you use here
*
* **/
function sendAllowanceFromToken(address[] memory _users, uint256[] memory _values, address _contract) public returns(bool){
Token _token = Token(_contract);
require(_users.length == _values.length, "Lenght of users and values must be equal");
require(msg.sender != address(0));
uint256 total_balance = 0;
for(uint i=0; i< _values.length; i++){
total_balance = total_balance + _values[i];
}
require(_token.balanceOf(msg.sender) >= total_balance, "Sender balance needs to be higher than total distributed values");
require(_token.allowance(msg.sender, address(this)) >= total_balance, "Allowance balance to the distributor needs to be higher than total distributed values");
for(uint i=0; i< _users.length; i++){
_token.transferFrom(msg.sender, _users[i], _values[i]);
}
return true;
}
function returnAmount() isOwner public returns(bool){
token.transfer(owner, token.balanceOf(address(this)));
}
}
|
Values must be in the minimal unit (in wei in case of 18 decimals). Set the allowance to the contract be able to do the transfer /
|
function sendAmountAllowance(address[] memory _users, uint256[] memory _values) public returns(bool){
require(_users.length == _values.length, "Lenght of users and values must be equal");
require(msg.sender != address(0));
uint256 total_balance = 0;
for(uint i=0; i< _values.length; i++){
total_balance = total_balance + _values[i];
}
require(token.balanceOf(msg.sender) >= total_balance, "Sender balance needs to be higher than total distributed values");
require(token.allowance(msg.sender, address(this)) >= total_balance, "Allowance balance to the distributor needs to be higher than total distributed values");
for(uint i=0; i< _users.length; i++){
token.transferFrom(msg.sender, _users[i], _values[i]);
}
return true;
}
| 12,611,323
|
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.6.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.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.2;
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-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: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.2;
/**
* @title ERC20Detailed 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 ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.5.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 not 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 Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, with should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.5.2;
/**
* @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: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.2;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://eips.ethereum.org/EIPS/eip-20
* Originally based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*
* This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for
* all accounts just by listening to said events. Note that this isn't required by the specification, and other
* compliant implementations may not do it.
*/
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(_msgSender(), to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(_msgSender(), spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, _msgSender(), _allowances[from][_msgSender()].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowances[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowances[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount));
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.2;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract ERC20Burnable is Initializable, Context, ERC20 {
/**
* @dev Burns a specific amount of tokens.
* @param amount The amount of token to be burned.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The account whose tokens will be burned.
* @param value uint256 The amount of token to be burned.
*/
function burnFrom(address from, uint256 value) public {
_burnFrom(from, value);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.5.2;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* 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;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.2;
/**
* @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'
require((value == 0) || (token.allowance(address(this), spender) == 0));
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);
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 equal true).
* @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.
require(address(token).isContract());
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success);
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)));
}
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol
pragma solidity ^0.5.2;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.2;
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.2;
contract PauserRole is Initializable, Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
function initialize(address sender) public initializer {
if (!isPauser(sender)) {
_addPauser(sender);
}
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.2;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Initializable, Context, PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
function initialize(address sender) public initializer {
PauserRole.initialize(sender);
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol
pragma solidity ^0.5.2;
/**
* @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 is Initializable, Context {
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.
*/
function initialize(address sender) public initializer {
_owner = 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 _msgSender() == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/math/Math.sol
pragma solidity ^0.5.2;
/**
* @title Math
* @dev Assorted math operations
*/
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 Calculates the average of two numbers. Since these are integers,
* averages of an even and odd number cannot be represented, and will be
* rounded down.
*/
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/contracts-ethereum-package/contracts/access/roles/WhitelistAdminRole.sol
pragma solidity ^0.5.2;
/**
* @title WhitelistAdminRole
* @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
*/
contract WhitelistAdminRole is Initializable, Context {
using Roles for Roles.Role;
event WhitelistAdminAdded(address indexed account);
event WhitelistAdminRemoved(address indexed account);
Roles.Role private _whitelistAdmins;
function initialize(address sender) public initializer {
if (!isWhitelistAdmin(sender)) {
_addWhitelistAdmin(sender);
}
}
modifier onlyWhitelistAdmin() {
require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
_;
}
function isWhitelistAdmin(address account) public view returns (bool) {
return _whitelistAdmins.has(account);
}
function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
_addWhitelistAdmin(account);
}
function renounceWhitelistAdmin() public {
_removeWhitelistAdmin(_msgSender());
}
function _addWhitelistAdmin(address account) internal {
_whitelistAdmins.add(account);
emit WhitelistAdminAdded(account);
}
function _removeWhitelistAdmin(address account) internal {
_whitelistAdmins.remove(account);
emit WhitelistAdminRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/WhitelistedRole.sol
pragma solidity ^0.5.2;
/**
* @title WhitelistedRole
* @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
* crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
* it), and not Whitelisteds themselves.
*/
contract WhitelistedRole is Initializable, Context, WhitelistAdminRole {
using Roles for Roles.Role;
event WhitelistedAdded(address indexed account);
event WhitelistedRemoved(address indexed account);
Roles.Role private _whitelisteds;
modifier onlyWhitelisted() {
require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role");
_;
}
function initialize(address sender) public initializer {
WhitelistAdminRole.initialize(sender);
}
function isWhitelisted(address account) public view returns (bool) {
return _whitelisteds.has(account);
}
function addWhitelisted(address account) public onlyWhitelistAdmin {
_addWhitelisted(account);
}
function removeWhitelisted(address account) public onlyWhitelistAdmin {
_removeWhitelisted(account);
}
function renounceWhitelisted() public {
_removeWhitelisted(_msgSender());
}
function _addWhitelisted(address account) internal {
_whitelisteds.add(account);
emit WhitelistedAdded(account);
}
function _removeWhitelisted(address account) internal {
_whitelisteds.remove(account);
emit WhitelistedRemoved(account);
}
uint256[50] private ______gap;
}
// File: contracts/InvictusWhitelist.sol
pragma solidity ^0.5.6;
/**
* Manages whitelisted addresses.
*
*/
contract InvictusWhitelist is Initializable, Ownable, WhitelistedRole {
function initialize() public initializer {
Ownable.initialize(msg.sender);
WhitelistedRole.initialize(msg.sender);
}
/// @dev override to support legacy name
function verifyParticipant(address participant) public onlyWhitelistAdmin {
if (!isWhitelisted(participant)) {
addWhitelisted(participant);
}
}
/// Allow the owner to remove a whitelistAdmin
function removeWhitelistAdmin(address account) public onlyOwner {
require(account != msg.sender, "Use renounceWhitelistAdmin");
_removeWhitelistAdmin(account);
}
}
// File: contracts/IMLToken.sol
pragma solidity ^0.5.6;
/**
* Contract for Invictus Margin Lending (IML) fund.
*
*/
contract IMLToken is Initializable, ERC20Detailed, ERC20Burnable, Ownable, Pausable, MinterRole {
using SafeERC20 for ERC20;
using SafeMath for uint256;
// Maps participant addresses to the withdrawal request
mapping (address => uint256) public pendingWithdrawals;
address[] public withdrawals;
uint256 private minTokenRedemption;
uint256 private maxWithdrawalsPerTx;
Price public price;
address public whitelistContract;
address public stableContract;
struct Price {
uint256 numerator;
uint256 denominator;
}
event PriceUpdate(uint256 numerator, uint256 denominator);
event AddLiquidity(address indexed account, address indexed stableAddress, uint256 value);
event RemoveLiquidity(address indexed account, uint256 value);
event WithdrawRequest(address indexed participant, uint256 amountTokens);
event Withdraw(address indexed participant, uint256 amountTokens, uint256 etherAmount);
event WithdrawInvalidAddress(address indexed participant, uint256 amountTokens);
event WithdrawFailed(address indexed participant, uint256 amountTokens);
event TokensClaimed(address indexed token, uint256 balance);
/**
* Sets the maximum number of withdrawals in a single transaction.
* @dev Allows us to configure batch sizes and avoid running out of gas.
*/
function setMaxWithdrawalsPerTx(uint256 newMaxWithdrawalsPerTx) external onlyOwner {
require(newMaxWithdrawalsPerTx > 0, "Must be greater than 0");
maxWithdrawalsPerTx = newMaxWithdrawalsPerTx;
}
/// Sets the minimum number of tokens to redeem.
function setMinimumTokenRedemption(uint256 newMinTokenRedemption) external onlyOwner {
require(newMinTokenRedemption > 0, "Minimum must be greater than 0");
minTokenRedemption = newMinTokenRedemption;
}
/// Updates the price numerator.
function updatePrice(uint256 newNumerator) external onlyMinter {
require(newNumerator > 0, "Must be positive value");
price.numerator = newNumerator;
processWithdrawals();
emit PriceUpdate(price.numerator, price.denominator);
}
/// Updates the price denominator.
function updatePriceDenominator(uint256 newDenominator) external onlyMinter {
require(newDenominator > 0, "Must be positive value");
price.denominator = newDenominator;
}
/**
* Whitelisted token holders can request token redemption, and withdraw stable coins.
* @param amountTokensToWithdraw The number of tokens to withdraw.
* @dev withdrawn tokens are burnt.
*/
function requestWithdrawal(uint256 amountTokensToWithdraw) external whenNotPaused
onlyWhitelisted {
address participant = msg.sender;
require(balanceOf(participant) >= amountTokensToWithdraw,
"Cannot withdraw more than balance held");
require(amountTokensToWithdraw >= minTokenRedemption, "Too few tokens");
burn(amountTokensToWithdraw);
uint256 pendingAmount = pendingWithdrawals[participant];
if (pendingAmount == 0) {
withdrawals.push(participant);
}
pendingWithdrawals[participant] = pendingAmount.add(amountTokensToWithdraw);
emit WithdrawRequest(participant, amountTokensToWithdraw);
}
/// Allows owner to claim any ERC20 tokens.
function claimTokens(ERC20 token) external onlyOwner {
require(address(token) != address(0), "Invalid address");
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(owner(), token.balanceOf(address(this)));
emit TokensClaimed(address(token), balance);
}
/**
* @dev Allows the owner to burn a specific amount of tokens on a participant's behalf.
* @param value The amount of tokens to be burned.
*/
function burnForParticipant(address account, uint256 value) external onlyOwner {
_burn(account, value);
}
/**
* @dev Function allowing the owner to change the stable contract when paused.
* @param stableContractInput The new stable contract address.
*/
function changeStableContract(address stableContractInput) external onlyOwner whenPaused {
require(stableContractInput != address(0), "Invalid stable coin address");
stableContract = stableContractInput;
}
/// Adds liquidity to the contract, allowing anyone to explicitly deposit stable coin.
function addLiquidity(uint256 amount) external {
ERC20 erc20 = ERC20(stableContract);
erc20.safeTransferFrom(msg.sender, address(this), amount);
emit AddLiquidity(msg.sender, stableContract, amount);
}
/// Removes liquidity, allowing owner to transfer stable coin to the fund wallet.
function removeLiquidity(uint256 amount) external onlyOwner {
ERC20(stableContract).safeTransfer(msg.sender, amount);
emit RemoveLiquidity(msg.sender, amount);
}
/// Allow the owner to remove a minter
function removeMinter(address account) external onlyOwner {
require(account != msg.sender, "Use renounceMinter");
_removeMinter(account);
}
/// Allow the owner to remove a pauser
function removePauser(address account) external onlyOwner {
require(account != msg.sender, "Use renouncePauser");
_removePauser(account);
}
/// returns the number of withdrawals pending.
function numberWithdrawalsPending() external view returns (uint256) {
return withdrawals.length;
}
/**
* Initialize the contract.
*/
function initialize(uint256 priceNumeratorInput, address whitelistContractInput, address stableContractInput) public initializer {
ERC20Detailed.initialize("Invictus Margin Lending", "IML", 18);
Pausable.initialize(msg.sender);
Ownable.initialize(msg.sender);
MinterRole.initialize(msg.sender);
price = Price(priceNumeratorInput, 1000);
require(priceNumeratorInput > 0, "Invalid price numerator");
require(whitelistContractInput != address(0), "Invalid whitelist address");
require(stableContractInput != address(0), "Invalid stable coin address");
whitelistContract = whitelistContractInput;
stableContract = stableContractInput;
minTokenRedemption = 1 ether;
maxWithdrawalsPerTx = 50;
}
/**
* @dev Function to mint tokens when not paused.
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter whenNotPaused returns (bool) {
_mint(to, value);
return true;
}
/// Internal function to process withdrawals.
function processWithdrawals() internal {
uint256 numberOfWithdrawals = Math.min(withdrawals.length, maxWithdrawalsPerTx);
uint256 startingIndex = withdrawals.length;
uint256 endingIndex = withdrawals.length.sub(numberOfWithdrawals);
for (uint256 i = startingIndex; i > endingIndex; i--) {
handleWithdrawal(i - 1);
}
}
function handleWithdrawal(uint256 index) internal {
address participant = withdrawals[index];
uint256 tokens = pendingWithdrawals[participant];
uint256 withdrawValue = tokens.mul(price.denominator) / price.numerator;
pendingWithdrawals[participant] = 0;
withdrawals.pop();
if (ERC20(stableContract).balanceOf(address(this)) < withdrawValue) {
mint(participant, tokens);
emit WithdrawFailed(participant, tokens);
return;
}
ERC20(stableContract).safeTransfer(participant, withdrawValue);
emit Withdraw(participant, tokens, withdrawValue);
}
modifier onlyWhitelisted() {
require(InvictusWhitelist(whitelistContract).isWhitelisted(msg.sender), "Must be whitelisted");
_;
}
}
|
Internal function to process withdrawals.
|
function processWithdrawals() internal {
uint256 numberOfWithdrawals = Math.min(withdrawals.length, maxWithdrawalsPerTx);
uint256 startingIndex = withdrawals.length;
uint256 endingIndex = withdrawals.length.sub(numberOfWithdrawals);
for (uint256 i = startingIndex; i > endingIndex; i--) {
handleWithdrawal(i - 1);
}
}
| 6,063,618
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6;
/**
* @dev Foo dev
* @notice Foo userdoc
*/
contract Foo {
/**
* @dev Foo.bar devdoc
* @notice Foo.bar userdoc
*/
function bar() external view returns (uint256) {
return 0;
}
/**
* @dev Foo.foo devdoc
* @notice Foo.foo userdoc
*/
function foo() external view returns (uint256) {
return 0;
}
}
|
Foo.foo devdoc Foo.foo userdoc/
|
function foo() external view returns (uint256) {
return 0;
}
| 1,838,571
|
pragma solidity ^0.4.24;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title EternalStorage
* @dev An ownable contract that can be used as a storage where the variables
* are stored in a set of mappings indexed by hash names.
*/
contract EternalStorage {
struct Storage {
mapping(bytes32 => bool) _bool;
mapping(bytes32 => int256) _int;
mapping(bytes32 => uint256) _uint;
mapping(bytes32 => string) _string;
mapping(bytes32 => address) _address;
mapping(bytes32 => bytes) _bytes;
mapping(bytes32 => bytes32) _bytes32;
}
Storage internal s;
/**
* @dev Get the value stored of a boolean variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getBoolean(bytes32 h) public view returns (bool) {
return s._bool[h];
}
/**
* @dev Get the value stored of a int variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getInt(bytes32 h) public view returns (int) {
return s._int[h];
}
/**
* @dev Get the value stored of a uint variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getUint(bytes32 h) public view returns (uint256) {
return s._uint[h];
}
/**
* @dev Get the value stored of a address variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getAddress(bytes32 h) public view returns (address) {
return s._address[h];
}
/**
* @dev Get the value stored of a string variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getString(bytes32 h) public view returns (string) {
return s._string[h];
}
/**
* @dev Get the value stored of a bytes variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getBytes(bytes32 h) public view returns (bytes) {
return s._bytes[h];
}
/**
* @dev Get the value stored of a bytes variable by the hash name
* @param h The keccak256 hash of the variable name
*/
function getBytes32(bytes32 h) public view returns (bytes32) {
return s._bytes32[h];
}
/**
* @dev Allows the owner to set a value for a boolean variable
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function _setBoolean(bytes32 h, bool v) internal {
s._bool[h] = v;
}
/**
* @dev Allows the owner to set a value for a int variable
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function _setInt(bytes32 h, int256 v) internal {
s._int[h] = v;
}
/**
* @dev Allows the owner to set a value for a boolean variable
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function _setUint(bytes32 h, uint256 v) internal {
s._uint[h] = v;
}
/**
* @dev Allows the owner to set a value for a address variable
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function _setAddress(bytes32 h, address v) internal {
s._address[h] = v;
}
/**
* @dev Allows the owner to set a value for a string variable
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function _setString(bytes32 h, string v) internal {
s._string[h] = v;
}
/**
* @dev Allows the owner to set a value for a bytes variable
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function _setBytes(bytes32 h, bytes v) internal {
s._bytes[h] = v;
}
/**
* @dev Allows the owner to set a value for a bytes32 variable
* @param h The keccak256 hash of the variable name
* @param v The value to be stored
*/
function _setBytes32(bytes32 h, bytes32 v) internal {
s._bytes32[h] = v;
}
}
|
Allows the owner to set a value for a boolean variable h The keccak256 hash of the variable name v The value to be stored/
|
function _setUint(bytes32 h, uint256 v) internal {
s._uint[h] = v;
}
| 6,382,847
|
//Address: 0x84119cb33e8f590d75c2d6ea4e6b0741a7494eda
//Contract name: GigaWattToken
//Balance: 0 Ether
//Verification Date: 8/10/2017
//Transacion Count: 13493
// CODE STARTS HERE
/*
* Giga Watt Token Smart Contract. Copyright © 2016 by ABDK Consulting.
* Author: Mikhail Vladimirov <mikhail.vladimirov@gmail.com>
*/
pragma solidity ^0.4.1;
/**
* ERC-20 standard token interface, as defined
* <a href="http://github.com/ethereum/EIPs/issues/20">here</a>.
*/
contract Token {
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () constant returns (uint256 supply);
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) constant returns (uint256 balance);
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens from the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value) returns (bool success);
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
returns (bool success);
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value) returns (bool success);
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
constant returns (uint256 remaining);
/**
* Logged when tokens were transferred from one owner to another.
*
* @param _from address of the owner, tokens were transferred from
* @param _to address of the owner, tokens were transferred to
* @param _value number of tokens transferred
*/
event Transfer (address indexed _from, address indexed _to, uint256 _value);
/**
* Logged when owner approved his tokens to be transferred by some spender.
*
* @param _owner owner who approved his tokens to be transferred
* @param _spender spender who were allowed to transfer the tokens belonging
* to the owner
* @param _value number of tokens belonging to the owner, approved to be
* transferred by the spender
*/
event Approval (
address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* Provides methods to safely add, subtract and multiply uint256 numbers.
*/
contract SafeMath {
uint256 constant private MAX_UINT256 =
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Add two uint256 values, throw in case of overflow.
*
* @param x first value to add
* @param y second value to add
* @return x + y
*/
function safeAdd (uint256 x, uint256 y)
constant internal
returns (uint256 z) {
if (x > MAX_UINT256 - y) throw;
return x + y;
}
/**
* Subtract one uint256 value from another, throw in case of underflow.
*
* @param x value to subtract from
* @param y value to subtract
* @return x - y
*/
function safeSub (uint256 x, uint256 y)
constant internal
returns (uint256 z) {
if (x < y) throw;
return x - y;
}
/**
* Multiply two uint256 values, throw in case of overflow.
*
* @param x first value to multiply
* @param y second value to multiply
* @return x * y
*/
function safeMul (uint256 x, uint256 y)
constant internal
returns (uint256 z) {
if (y == 0) return 0; // Prevent division by zero at the next line
if (x > MAX_UINT256 / y) throw;
return x * y;
}
}
/**
* Abstract base contract for contracts implementing Token interface.
*/
contract AbstractToken is Token, SafeMath {
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply () constant returns (uint256 supply) {
return tokensCount;
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf (address _owner) constant returns (uint256 balance) {
return accounts [_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens from the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value) returns (bool success) {
return doTransfer (msg.sender, _to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
returns (bool success)
{
if (_value > approved [_from][msg.sender]) return false;
if (doTransfer (_from, _to, _value)) {
approved [_from][msg.sender] =
safeSub (approved[_from][msg.sender], _value);
return true;
} else return false;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
*
* @param _spender address to allow the owner of to transfer tokens from
message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value) returns (bool success) {
approved [msg.sender][_spender] = _value;
Approval (msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance (address _owner, address _spender)
constant returns (uint256 remaining) {
return approved [_owner][_spender];
}
/**
* Create given number of new tokens and give them to given owner.
*
* @param _owner address to given new created tokens to the owner of
* @param _value number of new tokens to create
*/
function createTokens (address _owner, uint256 _value) internal {
if (_value > 0) {
accounts [_owner] = safeAdd (accounts [_owner], _value);
tokensCount = safeAdd (tokensCount, _value);
}
}
/**
* Perform token transfer.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to to the owner of
* @param _value number of tokens to transfer
* @return true if tokens were transferred successfully, false otherwise
*/
function doTransfer (address _from, address _to, uint256 _value)
private returns (bool success) {
if (_value > accounts [_from]) return false;
if (_value > 0 && _from != _to) {
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
Transfer (_from, _to, _value);
}
return true;
}
/**
* Total number of tokens in circulation.
*/
uint256 tokensCount;
/**
* Maps addresses of token owners to states of their accounts.
*/
mapping (address => uint256) accounts;
/**
* Maps addresses of token owners to mappings from addresses of spenders to
* how many tokens belonging to the owner, the spender is currently allowed to
* transfer.
*/
mapping (address => mapping (address => uint256)) approved;
}
/**
* Standard Token smart contract that provides the following features:
* <ol>
* <li>Centralized creation of new tokens</li>
* <li>Freeze/unfreeze token transfers</li>
* <li>Change owner</li>
* </ol>
*/
contract StandardToken is AbstractToken {
/**
* Maximum allowed tokens in circulation (2^64 - 1).
*/
uint256 constant private MAX_TOKENS = 0xFFFFFFFFFFFFFFFF;
/**
* Address of the owner of the contract.
*/
address owner;
/**
* Whether transfers are currently frozen.
*/
bool frozen;
/**
* Instantiate the contract and make the message sender to be the owner.
*/
function StandardToken () {
owner = msg.sender;
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens from the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer (address _to, uint256 _value)
returns (bool success) {
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom (address _from, address _to, uint256 _value)
returns (bool success) {
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
/**
* Create certain number of new tokens and give them to the owner of the
* contract.
*
* @param _value number of new tokens to create
* @return true if tokens were created successfully, false otherwise
*/
function createTokens (uint256 _value)
returns (bool success) {
if (msg.sender != owner) throw;
if (_value > MAX_TOKENS - totalSupply ()) return false;
AbstractToken.createTokens (owner, _value);
return true;
}
/**
* Freeze token transfers.
*/
function freezeTransfers () {
if (msg.sender != owner) throw;
if (!frozen)
{
frozen = true;
Freeze ();
}
}
/**
* Unfreeze token transfers.
*/
function unfreezeTransfers () {
if (msg.sender != owner) throw;
if (frozen) {
frozen = false;
Unfreeze ();
}
}
/**
* Set new owner address.
*
* @param _newOwner new owner address
*/
function setOwner (address _newOwner) {
if (msg.sender != owner) throw;
owner = _newOwner;
}
/**
* Logged when token transfers were freezed.
*/
event Freeze ();
/**
* Logged when token transfers were unfreezed.
*/
event Unfreeze ();
}
/**
* Giga Watt Token Smart Contract.
*/
contract GigaWattToken is StandardToken {
/**
* Constructor just calls constructor of parent contract.
*/
function GigaWattToken () StandardToken () {
// Do nothing
}
}
|
Maximum allowed tokens in circulation (2^64 - 1)./ Address of the owner of the contract./ Whether transfers are currently frozen./ Instantiate the contract and make the message sender to be the owner./
|
function StandardToken () {
owner = msg.sender;
}
| 5,503,199
|
pragma solidity >=0.4.21 <0.6.0;
import "../interfaces/IPToken.sol";
import "./BaseRecipe.sol";
contract BuyPTokenRecipe is BaseRecipe {
constructor(address _token, address _underlying) BaseRecipe(_token, _underlying) public {
}
function tokensReceived(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes calldata _userData,
bytes calldata _operatorData
) external {
_tokensReceived(_to);
token.redeem(address(this), token.balanceOf(address(this)));
uint256 underlyingAmount = underlying.balanceOf(address(this));
address pTokenAddress = abi.decode(_userData, (address));
underlying.approve(pTokenAddress, underlyingAmount);
IPToken pToken = IPToken(pTokenAddress);
// TODO consider getting max price from some oracle
pToken.mintWithToken(_from, address(underlying), underlyingAmount, 0);
}
function() external payable {}
}
|
TODO consider getting max price from some oracle
|
function tokensReceived(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes calldata _userData,
bytes calldata _operatorData
) external {
_tokensReceived(_to);
token.redeem(address(this), token.balanceOf(address(this)));
uint256 underlyingAmount = underlying.balanceOf(address(this));
address pTokenAddress = abi.decode(_userData, (address));
underlying.approve(pTokenAddress, underlyingAmount);
IPToken pToken = IPToken(pTokenAddress);
pToken.mintWithToken(_from, address(underlying), underlyingAmount, 0);
}
| 15,863,774
|
./partial_match/5/0x7aAC0f092F7b961145900839Ed6d54b1980F200c/sources/PostageStamp.sol
|
Create a new batch. At least `_initialBalancePerChunk2^depth` number of tokens need to be preapproved for this contract. _owner The owner of the new batch. _initialBalancePerChunk The initial balance per chunk of the batch. _depth The initial depth of the new batch. _batchId The batchId being copied (from previous version contract data). _immutable Whether the batch is mutable./ bucket depth should be non-zero and smaller than the depth Derive batchId from msg.sender to ensure another party cannot use the same batch id and frontrun us. per chunk balance times the batch size is what we need to transfer in
|
function copyBatch(
address _owner,
uint256 _initialBalancePerChunk,
uint8 _depth,
uint8 _bucketDepth,
bytes32 _batchId,
bool _immutable
) external whenNotPaused {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "only administrator can use copy method");
require(_owner != address(0), "owner cannot be the zero address");
require(_bucketDepth != 0 && _bucketDepth < _depth, "invalid bucket depth");
require(batches[_batchId].owner == address(0), "batch already exists");
uint256 totalAmount = _initialBalancePerChunk * (1 << _depth);
require(ERC20(bzzToken).transferFrom(msg.sender, address(this), totalAmount), "failed transfer");
uint256 normalisedBalance = currentTotalOutPayment() + (_initialBalancePerChunk);
validChunkCount += 1 << _depth;
batches[_batchId] = Batch({
owner: _owner,
depth: _depth,
immutableFlag: _immutable,
normalisedBalance: normalisedBalance
});
require(normalisedBalance > 0, "normalised balance cannot be zero");
emit BatchCreated(_batchId, totalAmount, normalisedBalance, _owner, _depth, _bucketDepth, _immutable);
}
| 16,885,240
|
pragma solidity 0.4.24;
import "openzeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol";
import "openzeppelin-solidity/contracts/crowdsale/validation/WhitelistedCrowdsale.sol";
import "./SolidToken.sol";
import "./Distributable.sol";
import "openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
contract TokenSale is MintedCrowdsale, WhitelistedCrowdsale, Pausable, Distributable {
//Global Variables
mapping(address => uint256) public contributions;
Stages public currentStage;
//CONSTANTS
uint256 constant MINIMUM_CONTRIBUTION = 0.5 ether; //the minimum conbtribution on Wei
uint256 constant MAXIMUM_CONTRIBUTION = 100 ether; //the maximum contribution on Wei
uint256 constant BONUS_PERCENT = 250; // The percentage of bonus in the fisrt stage, in;
uint256 constant TOKENS_ON_SALE_PERCENT = 600; //The percentage of avaiable tokens for sale;
uint256 constant BONUSSALE_MAX_DURATION = 30 days ;
uint256 constant MAINSALE_MAX_DURATION = 60 days;
uint256 constant TOKEN_RELEASE_DELAY = 182 days;
uint256 constant HUNDRED_PERCENT = 1000; //100% considering one extra decimal
//BONUSSALE VARIABLES
uint256 public bonussale_Cap = 14400 ether;
uint256 public bonussale_TokenCap = 1200000 ether;
uint256 public bonussale_StartDate;
uint256 public bonussale_EndDate;
uint256 public bonussale_TokesSold;
uint256 public bonussale_WeiRaised;
//MAINSALE VARIABLES
uint256 public mainSale_Cap = 18000 ether;
uint256 public mainSale_TokenCap = 1200000 ether;
uint256 public mainSale_StartDate;
uint256 public mainSale_EndDate;
uint256 public mainSale_TokesSold;
uint256 public mainSale_WeiRaised;
//TEMPORARY VARIABLES - USED TO AVOID OVERRIDING MORE OPEN ZEPPELING FUNCTIONS
uint256 private changeDue;
bool private capReached;
enum Stages{
SETUP,
READY,
BONUSSALE,
MAINSALE,
FINALIZED
}
/**
MODIFIERS
**/
/**
@dev Garantee that contract has the desired satge
**/
modifier atStage(Stages _currentStage){
require(currentStage == _currentStage);
_;
}
/**
@dev Execute automatically transitions between different Stages
based on time only
**/
modifier timedTransition(){
if(currentStage == Stages.READY && now >= bonussale_StartDate){
currentStage = Stages.BONUSSALE;
}
if(currentStage == Stages.BONUSSALE && now > bonussale_EndDate){
finalizePresale();
}
if(currentStage == Stages.MAINSALE && now > mainSale_EndDate){
finalizeSale();
}
_;
}
/**
CONSTRUCTOR
**/
/**
@param _rate The exchange rate(multiplied by 1000) of tokens to eth(1 token = rate * ETH)
@param _wallet The address that recieves _forwardFunds
@param _token A token contract. Will be overriden later(needed fot OZ constructor)
**/
constructor(uint256 _rate, address _wallet, ERC20 _token) public Crowdsale(_rate,_wallet,_token) {
require(_rate == 15);
currentStage = Stages.SETUP;
}
/**
SETUP RELATED FUNCTIONS
**/
/**
* @dev Sets the initial date and token.
* @param initialDate A timestamp representing the start of the bonussale
@param tokenAddress The address of the deployed SolidToken
*/
function setupSale(uint256 initialDate, address tokenAddress) onlyOwner atStage(Stages.SETUP) public {
bonussale_StartDate = initialDate;
bonussale_EndDate = bonussale_StartDate + BONUSSALE_MAX_DURATION;
token = ERC20(tokenAddress);
require(SolidToken(tokenAddress).totalSupply() == 0, "Tokens have already been distributed");
require(SolidToken(tokenAddress).owner() == address(this), "Token has the wrong ownership");
currentStage = Stages.READY;
}
/**
STAGE RELATED FUNCTIONS
**/
/**
* @dev Returns de ETH cap of the current currentStage
* @return uint256 representing the cap
*/
function getCurrentCap() public view returns(uint256 cap){
cap = bonussale_Cap;
if(currentStage == Stages.MAINSALE){
cap = mainSale_Cap;
}
}
/**
* @dev Returns de ETH cap of the current currentStage
* @return uint256 representing the raised amount in the stage
*/
function getRaisedForCurrentStage() public view returns(uint256 raised){
raised = bonussale_WeiRaised;
if(currentStage == Stages.MAINSALE)
raised = mainSale_WeiRaised;
}
/**
* @dev Returns the sale status.
* @return True if open, false if closed
*/
function saleOpen() public timedTransition whenNotPaused returns(bool open) {
open = ((now >= bonussale_StartDate && now < bonussale_EndDate) ||
(now >= mainSale_StartDate && now < mainSale_EndDate)) &&
(currentStage == Stages.BONUSSALE || currentStage == Stages.MAINSALE);
}
/**
FINALIZATION RELATES FUNCTIONS
**/
/**
* @dev Checks and distribute the remaining tokens. Finish minting afterwards
* @return uint256 representing the cap
*/
function distributeTokens() public onlyOwner atStage(Stages.FINALIZED) {
require(!distributed);
distributed = true;
uint256 totalTokens = (bonussale_TokesSold.add(mainSale_TokesSold)).mul(HUNDRED_PERCENT).div(TOKENS_ON_SALE_PERCENT); //sold token will represent 60% of all tokens
for(uint i = 0; i < partners.length; i++){
uint256 amount = percentages[partners[i]].mul(totalTokens).div(HUNDRED_PERCENT);
_deliverTokens(partners[i], amount);
}
for(uint j = 0; j < partnerFixedAmount.length; i++){
_deliverTokens(partnerFixedAmount[j], fixedAmounts[partnerFixedAmount[j]]);
}
require(SolidToken(token).finishMinting());
}
/**
* @dev Finalizes the bonussale and sets up the break and public sales
*
*/
function finalizePresale() atStage(Stages.BONUSSALE) internal{
bonussale_EndDate = now;
mainSale_StartDate = now;
mainSale_EndDate = mainSale_StartDate + MAINSALE_MAX_DURATION;
mainSale_TokenCap = mainSale_TokenCap.add(bonussale_TokenCap.sub(bonussale_TokesSold));
mainSale_Cap = mainSale_Cap.add(bonussale_Cap.sub(weiRaised.sub(changeDue)));
currentStage = Stages.MAINSALE;
}
/**
* @dev Finalizes the public sale
*
*/
function finalizeSale() atStage(Stages.MAINSALE) internal {
mainSale_EndDate = now;
require(SolidToken(token).setTransferEnablingDate(now + TOKEN_RELEASE_DELAY));
currentStage = Stages.FINALIZED;
}
/**
OPEN ZEPPELIN OVERRIDES
**/
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) isWhitelisted(_beneficiary) internal {
require(_beneficiary == msg.sender);
require(saleOpen(), "Sale is Closed");
// Check for edge cases
uint256 acceptedValue = _weiAmount;
uint256 currentCap = getCurrentCap();
uint256 raised = getRaisedForCurrentStage();
if(contributions[_beneficiary].add(acceptedValue) > MAXIMUM_CONTRIBUTION){
changeDue = (contributions[_beneficiary].add(acceptedValue)).sub(MAXIMUM_CONTRIBUTION);
acceptedValue = acceptedValue.sub(changeDue);
}
if(raised.add(acceptedValue) >= currentCap){
changeDue = changeDue.add(raised.add(acceptedValue).sub(currentCap));
acceptedValue = _weiAmount.sub(changeDue);
capReached = true;
}
require(capReached || contributions[_beneficiary].add(acceptedValue) >= MINIMUM_CONTRIBUTION ,"Contribution below minimum");
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256 amount) {
amount = (_weiAmount.sub(changeDue)).mul(HUNDRED_PERCENT).div(rate); // Multiplication to account for the decimal cases in the rate
if(currentStage == Stages.BONUSSALE){
amount = amount.add(amount.mul(BONUS_PERCENT).div(HUNDRED_PERCENT)); //Add bonus
}
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
if(currentStage == Stages.MAINSALE && capReached) finalizeSale();
if(currentStage == Stages.BONUSSALE && capReached) finalizePresale();
//Cleanup temp
changeDue = 0;
capReached = false;
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
uint256 tokenAmount = _getTokenAmount(_weiAmount);
if(currentStage == Stages.BONUSSALE){
bonussale_TokesSold = bonussale_TokesSold.add(tokenAmount);
bonussale_WeiRaised = bonussale_WeiRaised.add(_weiAmount.sub(changeDue));
} else {
mainSale_TokesSold = mainSale_TokesSold.add(tokenAmount);
mainSale_WeiRaised = mainSale_WeiRaised.add(_weiAmount.sub(changeDue));
}
contributions[_beneficiary] = contributions[_beneficiary].add(_weiAmount).sub(changeDue);
weiRaised = weiRaised.sub(changeDue);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value.sub(changeDue));
msg.sender.transfer(changeDue); //Transfer change to _beneficiary
}
}
|
Finalizes the bonussale and sets up the break and public sales/
|
function finalizePresale() atStage(Stages.BONUSSALE) internal{
bonussale_EndDate = now;
mainSale_StartDate = now;
mainSale_EndDate = mainSale_StartDate + MAINSALE_MAX_DURATION;
mainSale_TokenCap = mainSale_TokenCap.add(bonussale_TokenCap.sub(bonussale_TokesSold));
mainSale_Cap = mainSale_Cap.add(bonussale_Cap.sub(weiRaised.sub(changeDue)));
currentStage = Stages.MAINSALE;
}
| 2,541,224
|
./full_match/80001/0xe5904022b45A537722d689894ba02D541c991C0D/sources/contracts/FractionCalculator.sol
|
Convert decimal string to integer Multiply fraction by variable
|
function calculateFraction(string memory decimalStr, uint256 variable) public pure returns (uint256) {
(uint256 numerator, uint256 denominator) = parseDecimal(decimalStr);
uint256 result = numerator * variable / denominator;
return result;
}
| 9,474,076
|
/**
*Submitted for verification at Etherscan.io on 2018-10-26
*/
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
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);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return 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) {
_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) {
require(spender != address(0));
_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 <= _allowed[from][msg.sender]);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_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 increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_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 decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != 0);
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != 0);
require(value <= _balances[account]);
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
/**
* @title ERC20Detailed 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 ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
uint private _totalSupply;
mapping(address => uint) balances;
constructor(string name, string symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply=10000;
balances[0x9BD20919b2B6a8E071F82BebF4EFe8Cb739f1919] = _totalSupply;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* 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;
function safeTransfer(
IERC20 token,
address to,
uint256 value
)
internal
{
require(token.transfer(to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
)
internal
{
require(token.transferFrom(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'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
)
internal
{
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
contract XL is ERC20, ERC20Detailed {
using SafeERC20 for XL;
constructor()
ERC20()
ERC20Detailed("XL Token", "XL", 6)
public
{
_mint(msg.sender, 999999999 * (uint256(10) ** 6));
}
}
|
return the number of decimals of the token./
|
function decimals() public view returns(uint8) {
return _decimals;
}
| 192,419
|
./full_match/1/0x873847b829a33C87c1fb227367D7b28a7DF979b4/sources/contracts/radiant/staking/ChefIncentivesController.sol
|
Ending reward distribution time./
|
function endRewardTime() public returns (uint256) {
uint256 unclaimedRewards = availableRewards();
uint256 extra = 0;
uint256 length = poolLength();
for (uint256 i; i < length; ) {
PoolInfo storage pool = poolInfo[registeredTokens[i]];
if (pool.lastRewardTime > lastAllPoolUpdate) {
extra +=
((pool.lastRewardTime - lastAllPoolUpdate) * pool.allocPoint * rewardsPerSecond) /
totalAllocPoint;
}
unchecked {
i++;
}
}
endingTime.lastUpdatedTime = block.timestamp;
if (rewardsPerSecond == 0) {
endingTime.estimatedTime = type(uint256).max;
endingTime.estimatedTime = (unclaimedRewards + extra) / rewardsPerSecond + lastAllPoolUpdate;
}
return endingTime.estimatedTime;
}
| 3,223,484
|
./partial_match/1/0x6b3ede185cA3079800390534313a130Ac4975D1e/sources/MarsRulerRegistry.sol
|
// Usage Functions // Validate Ownership Validate Augments Consume $MES Set Gear Config Emit GearChange Event
|
function setGear(uint256 tokenId_, GearConfig memory gearConfig_) external {
require(msg.sender == Martians.ownerOf(tokenId_),
"You are not the owner!");
require(10 == CS.characters(tokenId_).augments_,
"Your Martian is not a Ruler yet!");
bool _success = MES.transferFrom(msg.sender, address(this), GEAR_CHANGE_COST);
require(_success, "$MES deduction failed!");
emit GearChange(msg.sender, tokenId_, gearConfig_);
}
| 4,103,112
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";
import "./KindlyMarketplaceInterface.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@chainlink/contracts/src/v0.8/ChainlinkClient.sol";
/**
* @title MyContract is an example contract which requests data from
* the Chainlink network
* @dev This contract is designed to work on multiple networks, including
* local test networks
*/
contract KindlyNFT is Ownable, ERC721, ERC721URIStorage, ChainlinkClient {
// Chainlink setup
using Chainlink for Chainlink.Request;
// bytes32 public lastURI;
address private oracle;
bytes32 private jobId;
uint256 private fee;
bytes public data;
string public lastURI;
using SafeMath for uint256;
address public kindlyERC20Address;
address public kindlyMarketplaceAddress;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
struct Deeds {
uint256 kindlyTokensOnHold;
uint256 feedChild;
uint256 feedRescuedAnimal;
uint256 plantTree;
uint256 stakedKindly;
uint256 rewardsFromStaking;
uint256 id;
address holder;
}
// events
// event StatsChanged(address _holder, uint256 tokenId);
// Deeds[] public goodDeeds;
mapping(address => Deeds) public mappingAddressDeeds;
// variable bytes returned in a signle oracle response
string public image_url;
/**
* @notice Initialize the link token and target oracle
* @dev The oracle address must be an Operator contract for multiword response
*
*
* Kovan Testnet details:
* Link Token: 0xa36085F69e2889c224210F603D836748e7dC0088
* Oracle: 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8 (Chainlink DevRel)
*
*/
constructor(
) ERC721("KindlyNFT", "KND721") {
setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088);
setChainlinkOracle(0x25C7ac1900de67605c0A1812109E960068B1C3d6);
}
/**
* @notice Request variable bytes from the oracle
*/
function requestBytes(string memory _kindlyTokens, string memory _kindlyStaked)
public
{
bytes32 specId = "b3b68ecd35464833a16613742640ae89";
uint256 payment = 100000000000000000;
Chainlink.Request memory req = buildChainlinkRequest(specId, address(this), this.fulfillBytes.selector);
// req.add("get","http://104.251.214.49:45725/api");
req.add("get", appendStrings("http://104.251.214.49:45725/api?kindlyTokens=", _kindlyTokens, "&kindlyStaked=", _kindlyStaked));
req.add("path", "ipfs_url_bytes");
sendOperatorRequest(req, payment);
}
event RequestFulfilled(
bytes32 indexed requestId,
bytes indexed data
);
/**
* @notice Fulfillment function for variable bytes
* @dev This is called by the oracle. recordChainlinkFulfillment must be used.
*/
function fulfillBytes(
bytes32 requestId,
bytes memory bytesData
)
public
recordChainlinkFulfillment(requestId)
{
emit RequestFulfilled(requestId, bytesData);
data = bytesData;
lastURI = string(data);
}
function appendStrings(string memory a, string memory b, string memory c, string memory d) internal pure returns (string memory) {
return string(abi.encodePacked(a, b, c, d));
}
/**
* Network: Kovan
* Oracle: 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8 (Chainlink Devrel
* Node)
* Job ID: d5270d1c311941d0b08bead21fea7747 // this jobs converts to uint256 --> need bytes32?
* Fee: 0.1 LINK
*/
/**
* Network: Rinkeby (on maintenance mode?)
* Oracle: 0x7AFe1118Ea78C1eae84ca8feE5C65Bc76CcF879e (Chainlink Devrel
* Node)
* Job ID: b0bde308282843d49a3a8d2dd2464af1 // converts into bytes32
* Fee: 0.1 LINK
*/
/**
* @notice Deploy the contract with a specified address for the LINK
* and Oracle contract addresses
* @dev Sets the storage for the specified addresses
*/
// constructor(/*address _link address _newKindlyERC20Address, address _newkindlyMarketplaceAddress*/)
// ERC721("KindlyNFT", "KND721")
// {
// // if (_link == address(0)) {
// // setPublicChainlinkToken();
// // } else {
// // setChainlinkToken(_link);
// // }
// // kindlyERC20Address = _newKindlyERC20Address;
// // kindlyMarketplaceAddress = _newkindlyMarketplaceAddress;
// setPublicChainlinkToken();
// // setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088);
// setChainlinkOracle(0x25C7ac1900de67605c0A1812109E960068B1C3d6);
// // oracle = 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8; // 0x7AFe1118Ea78C1eae84ca8feE5C65Bc76CcF879e; // rinkeby
// // jobId = "7401f318127148a894c00c292e486ffd" ;// "b0bde308282843d49a3a8d2dd2464af1"; // rinkeby
// // fee = 0.1 * 10 ** 18; // (Varies by network and job)
// }
/**
* @notice Request variable bytes from the oracle
*/
// function requestBytes(
// )
// public
// {
// bytes32 specId = "b3b68ecd35464833a16613742640ae89";
// uint256 payment = 100000000000000000;
// Chainlink.Request memory req = buildChainlinkRequest(specId, address(this), this.fulfillBytes.selector);
// req.add("get","http://104.251.214.49:45725/api");
// req.add("path", "newURI");
// sendOperatorRequest(req, payment);
// }
// event RequestFulfilled(
// bytes32 indexed requestId,
// bytes indexed data
// );
/**
* @notice Fulfillment function for variable bytes
* @dev This is called by the oracle. recordChainlinkFulfillment must be used.
*/
// function fulfillBytes(bytes32 requestId, bytes memory bytesData) public recordChainlinkFulfillment(requestId) {
// emit RequestFulfilled(requestId, bytesData);
// data = bytesData;
// lastURI2 = string(data);
// }
function setOracle(address _oracle) public onlyOwner {
oracle = _oracle;
}
function setJobId(string memory _jobId) public onlyOwner {
jobId = stringToBytes32(_jobId);
}
function stringToBytes32(string memory source) internal pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function safeMint(address to) public onlyOwner {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
}
// TODO: add merge function. If an address received another NFT it merges the stats with the old one
// The following functions are overrides required by Solidity.
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId) public view override(ERC721) returns (bool) {
return super.supportsInterface(interfaceId);
}
function updateKindlyOnHold(address previousHolder, address newHolder, uint256 newBalance) public { // TODO: add modifier ownable only kindly erc20 contract
if (previousHolder != address(0)){
mappingAddressDeeds[previousHolder].kindlyTokensOnHold = mappingAddressDeeds[previousHolder].kindlyTokensOnHold.sub(newBalance);
// emit StatsChanged(previousHolder, mappingAddressDeeds[previousHolder].id);
}
if (newHolder != address(0)){
mappingAddressDeeds[newHolder].kindlyTokensOnHold = mappingAddressDeeds[newHolder].kindlyTokensOnHold.add(newBalance);
// emit StatsChanged(previousHolder, mappingAddressDeeds[previousHolder].id);
}
}
function addKindlyChildDoantions(address _holder, uint256 balance) public {
mappingAddressDeeds[_holder].feedChild = mappingAddressDeeds[_holder].feedChild.add(balance);
// emit StatsChanged(_holder, mappingAddressDeeds[_holder].id);
}
function addKindlyAnimalDoantions(address _holder, uint256 balance) public {
mappingAddressDeeds[_holder].feedRescuedAnimal = mappingAddressDeeds[_holder].feedRescuedAnimal.add(balance);
// emit StatsChanged(_holder, mappingAddressDeeds[_holder].id);
}
function addKindlyTreeDoantions(address _holder, uint256 balance) public {
mappingAddressDeeds[_holder].plantTree = mappingAddressDeeds[_holder].plantTree.add(balance);
// emit StatsChanged(_holder, mappingAddressDeeds[_holder].id);
}
function addStakedkindly(address _holder, uint256 balance) public {
// on staking in the marketplace the owner of the nft will receive extra stakedKindly
require(_holder != address(0), "Address should not be 0x");
mappingAddressDeeds[_holder].stakedKindly = mappingAddressDeeds[_holder].stakedKindly.add(balance);
// emit StatsChanged(_holder, mappingAddressDeeds[_holder].id);
// TODO: on stake the kindly on hold changes. Need to update the holders kindly balance
}
function removeStakedkindly(address _holder, uint256 balance) public {
// on removal of staked kindly in the marketplace the owner of the nft will lose the extra stakedKindly
require(_holder != address(0), "Address should not be 0x");
mappingAddressDeeds[_holder].stakedKindly = mappingAddressDeeds[_holder].stakedKindly.sub(balance);
// emit StatsChanged(_holder, mappingAddressDeeds[_holder].id);
// TODO: on stake the kindly on hold changes. Need to update the holders kindly balance
}
function updateRewardsFromStakedKindly(address _holder, uint256 balance) public {
// the owner of the nft will receive point from rewards collected from the staking process
require(_holder != address(0), "Address should not be 0x");
mappingAddressDeeds[_holder].rewardsFromStaking = mappingAddressDeeds[_holder].rewardsFromStaking.add(balance);
// emit StatsChanged(_holder, mappingAddressDeeds[_holder].id);
}
function setKindlyERC20Address(address _newKindlyERC20Address) public onlyOwner {
// TODO: add emit of change
kindlyERC20Address = _newKindlyERC20Address;
}
function setkindlyMarketplaceAddress(address _newkindlyMarketplaceAddress) public onlyOwner {
// TODO: add emit of change
kindlyMarketplaceAddress = _newkindlyMarketplaceAddress;
}
function getKindlyOnWallet(address _holder) public view returns (uint256){
// return kindlyERC20Address.call(bytes4(keccak256("balanceOf(address)")), _holder);
return ERC20(kindlyERC20Address).balanceOf(_holder);
}
function getStakedKindlyOnMarketplace(address _holder) public view returns (uint256){
return KindlyMarketplaceInterface(kindlyMarketplaceAddress).getStakedKindly(_holder);
}
function getRewardsFromStakingOnMarketplace(address _holder) public view returns (uint256) {
return mappingAddressDeeds[_holder].rewardsFromStaking;
}
function getChildDonationsOnMarketplace(address _holder) public view returns (uint256){
return KindlyMarketplaceInterface(kindlyMarketplaceAddress).getChildDonations(_holder);
}
function getAnimalDonationsOnMarketplace(address _holder) public view returns (uint256){
return KindlyMarketplaceInterface(kindlyMarketplaceAddress).getAnimalDonations(_holder);
}
function getTreeDonationsOnMarketplace(address _holder) public view returns (uint256){
return KindlyMarketplaceInterface(kindlyMarketplaceAddress).getTreeDonations(_holder);
}
function getNFTKindlyStats(address _holder) public view returns (uint256, uint256, uint256, uint256, address){
return (mappingAddressDeeds[_holder].kindlyTokensOnHold, mappingAddressDeeds[_holder].stakedKindly, mappingAddressDeeds[_holder].rewardsFromStaking, mappingAddressDeeds[_holder].id, mappingAddressDeeds[_holder].holder);
}
function getNFTDonationStats(address _holder) public view returns (uint256 childsFed, uint256 animalsFed, uint256 treePlanted) {
return (mappingAddressDeeds[_holder].feedChild, mappingAddressDeeds[_holder].feedRescuedAnimal, mappingAddressDeeds[_holder].plantTree);
}
function createNFT() public {
uint256 newId = _tokenIdCounter.current() + 1;
// uint256 kindlyOnWallet = getKindlyOnWallet(msg.sender);
// TODO: read balance of staked kindly in the marketplace as well as donations and set as starting values
mappingAddressDeeds[msg.sender] = Deeds(
getKindlyOnWallet(msg.sender),
getChildDonationsOnMarketplace(msg.sender),
getAnimalDonationsOnMarketplace(msg.sender),
getTreeDonationsOnMarketplace(msg.sender),
getStakedKindlyOnMarketplace(msg.sender), // default value from staked tokens is 0
uint256(0), // default rewards value from staked tokens is 0
newId,
msg.sender
);
safeMint(msg.sender); // TODO: validate if msg.sender is okay in the first parameter of safemint
}
function getTokenURI(uint256 tokenId) public view returns (string memory) {
return tokenURI(tokenId);
}
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
function setTokenURI(uint256 tokenId, string memory _tokenURI) public {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_setTokenURI(tokenId, _tokenURI);
}
/**
* Create a Chainlink request to retrieve API response, find the target
* data.
*/
// function requestNewURI() public returns (bytes32 requestId)
// {
// Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
// // Set the URL to perform the GET request on
// request.add("get", "http://104.251.214.49:45725/api");
// // Set the path to find the desired data in the API response, where the response format is:
// // {"RAW":
// // {"ETH":
// // {"USD":
// // {
// // "VOLUME24HOUR": xxx.xxx,
// // }
// // }
// // }
// // }
// request.add("path", "newURI"); // "RAW.ETH.USD.VOLUME24HOUR"); // TODO: adapt to API call response
// // Multiply the result by 1000000000000000000 to remove decimals
// // int timesAmount = 10**18;
// // request.addInt("times", timesAmount);
// // Sends the request
// return sendChainlinkRequestTo(oracle, request, fee);
// }
/**
* Receive the response in the form of uint256
*/
// function fulfill(bytes32 _requestId, bytes32 _newURI) public recordChainlinkFulfillment(_requestId)
// {
// lastURI = _newURI;
// }
}
|
on removal of staked kindly in the marketplace the owner of the nft will lose the extra stakedKindly emit StatsChanged(_holder, mappingAddressDeeds[_holder].id); TODO: on stake the kindly on hold changes. Need to update the holders kindly balance
|
function removeStakedkindly(address _holder, uint256 balance) public {
require(_holder != address(0), "Address should not be 0x");
mappingAddressDeeds[_holder].stakedKindly = mappingAddressDeeds[_holder].stakedKindly.sub(balance);
}
| 7,216,183
|
./full_match/1/0x2741d68d12b9Ba83c0f8779193EE88b2fA359705/sources/BOUNTY.sol
|
exclude from paying fees or having max transaction amount
|
constructor() ERC20("bounty.tech", "BOUNTY") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 10;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 39;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 10_000_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);
| 9,785,984
|
//SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import './lib/ERC721X.sol';
contract ShinobiBunny is ERC721X, Ownable {
using ECDSA for bytes32;
using Strings for uint256;
event SaleStateUpdate(bool active);
string public baseURI = "ipfs://none";
string public unrevealedURI = 'ipfs://QmQgDNbcGnPNiPdYDiJou9RsawaSSHrm6pQFjHrFkRTFAP/';
bool public publicSaleActive;
bool public whitelistActive;
bool public diamondlistActive;
uint256 public totalSupply;
uint256 public constant MAX_SUPPLY = 7777;
uint256 public constant PREMINT_AMOUNT = 3;
uint256 public RESERVED_AMOUNT = 1500;
uint256 public price = 0.12 ether;
uint256 public purchaseLimit = 1;
uint256 public whitelistPrice = 0.1 ether;
uint256 public whitelistPurchaseLimit = 1;
mapping(address => uint256) public _publicMinted;
mapping(address => uint256) public _whitelistMinted;
mapping(address => bool) public _diamondlistUsed;
address private _signerAddress = 0xc6EC711aDdFb8FFC9f7561f065F698f8606691AA;
uint256 private constant SIGNED_DATA_WHITELIST = 69;
uint256 private constant SIGNED_DATA_DIAMONDLIST = 1337;
bool public revealed = false;
constructor() ERC721X('Shinobi Bunny', 'SNB') {
// premint first 3 tokenIds to the owner
_mintBatch(msg.sender, PREMINT_AMOUNT);
}
// ------------- External -------------
function mint(uint256 amount) external payable whenPublicSaleActive noContract {
require(_publicMinted[msg.sender] + amount <= purchaseLimit, 'EXCEEDS_LIMIT');
require(msg.value == price * amount, 'INCORRECT_VALUE');
_publicMinted[msg.sender] = _publicMinted[msg.sender] + amount;
_mintBatch(msg.sender, amount);
}
function whitelistMint(uint256 amount, bytes memory signature)
external
payable
whenWhitelistActive
onlyWhitelisted(signature)
noContract
{
require(_whitelistMinted[msg.sender] + amount <= whitelistPurchaseLimit, 'EXCEEDS_LIMIT');
require(msg.value == whitelistPrice * amount, 'INCORRECT_VALUE');
_whitelistMinted[msg.sender] = _whitelistMinted[msg.sender] + amount;
_mintBatch(msg.sender, amount);
}
function diamondlistMint(bytes memory signature)
external
payable
whenDiamondlistActive
onlyDiamondlisted(signature)
noContract
{
_mintBatch(msg.sender, 1);
}
function ownMint(uint256 amount) external onlyOwner {
_mintBatch(msg.sender, amount);
}
// ------------- Private -------------
function _mintBatch(address to, uint256 amount) private {
uint256 tokenId = totalSupply;
require(tokenId + amount <= MAX_SUPPLY - RESERVED_AMOUNT, 'MAX_SUPPLY_REACHED');
require(amount > 0, 'MUST_BE_GREATER_0');
for (uint256 i; i < amount; i++) _mint(to, tokenId + i);
totalSupply += amount;
}
function _validSignature(bytes memory signature, bytes32 data) private view returns (bool) {
bytes32 msgHash = keccak256(abi.encode(address(this), data, msg.sender));
return msgHash.toEthSignedMessageHash().recover(signature) == _signerAddress;
}
// ------------- View -------------
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token');
if (!revealed) return unrevealedURI;
return string(abi.encodePacked(baseURI, tokenId.toString(), '.json'));
}
// ------------- Admin -------------
function setReserve(uint256 value) external onlyOwner {
RESERVED_AMOUNT = value;
}
function reveal(bool value) external onlyOwner {
revealed = value;
}
function giveAway(address[] calldata accounts) external onlyOwner {
for (uint256 i; i < accounts.length; i++) _mintBatch(accounts[i], 1);
}
function setPrice(uint256 price_) external onlyOwner {
price = price_;
}
function setWhitelistPrice(uint256 price_) external onlyOwner {
whitelistPrice = price_;
}
function setPurchaseLimit(uint256 limit) external onlyOwner {
purchaseLimit = limit;
}
function setWhitelistPurchaseLimit(uint256 limit) external onlyOwner {
whitelistPurchaseLimit = limit;
}
function setSignerAddress(address address_) external onlyOwner {
_signerAddress = address_;
}
function setWhitelistActive(bool active) external onlyOwner {
whitelistActive = active;
}
function setDiamondlistActive(bool active) external onlyOwner {
diamondlistActive = active;
}
function setPublicSaleActive(bool active) external onlyOwner {
publicSaleActive = active;
emit SaleStateUpdate(active);
}
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
function setUnrevealedURI(string memory _uri) external onlyOwner {
unrevealedURI = _uri;
}
function withdraw() public payable onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
function recoverToken(IERC20 token) external onlyOwner {
uint256 balance = token.balanceOf(address(this));
token.transfer(owner(), balance);
}
// ------------- Modifier -------------
modifier whenDiamondlistActive() {
require(diamondlistActive, 'DIAMONDLIST_NOT_ACTIVE');
_;
}
modifier whenWhitelistActive() {
require(whitelistActive, 'WHITELIST_NOT_ACTIVE');
_;
}
modifier whenPublicSaleActive() {
require(publicSaleActive, 'PUBLIC_SALE_NOT_ACTIVE');
_;
}
modifier noContract() {
require(tx.origin == msg.sender, 'CONTRACT_CALL');
_;
}
modifier onlyDiamondlisted(bytes memory signature) {
require(_validSignature(signature, bytes32(SIGNED_DATA_DIAMONDLIST)), 'NOT_WHITELISTED');
require(!_diamondlistUsed[msg.sender], 'DIAMONDLIST_USED');
_diamondlistUsed[msg.sender] = true;
_;
}
modifier onlyWhitelisted(bytes memory signature) {
require(_validSignature(signature, bytes32(SIGNED_DATA_WHITELIST)), 'NOT_WHITELISTED');
_;
}
// ------------- ERC721 -------------
function tokenIdsOf(address owner) external view returns (uint256[] memory) {
uint256[] memory ids = new uint256[](balanceOf(owner));
uint256 count;
for (uint256 i; i < balanceOf(owner); ++i) ids[count++] = tokenOfOwnerByIndex(owner, i);
return ids;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 `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
// OpenZeppelin Contracts v4.4.0 (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);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @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 {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. 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.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @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) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* 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));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.8.10;
// _____ _____ ____ _ _ ▗█▘ ▟▛
// |_ _|__ | ___| _ | __ )| | ___ ___| | __ ▗▛▘ ▟▛
// | |/ _ \| |_ | | | || _ \| |/ _ \ / __| |/ / ▗▛ ▟▀
// | | (_) | _|| |_| || |_) | | (_) | (__| < ▗▛ ▟▘
// |_|\___/|_| \__,_||____/|_|\___/ \___|_|\_\
// ▄▄▄▄▄▄
// ▟▀▀▀▀ ▝▀▀▀▀▀▀▀▀█▖
// ▗▛ ▟▘▌
// ▄▛ ▗▄▄▄▄▄▄▄▄▄▄▄▄▄▄ ▗▛ ▌
// ▐▛▀▀▀ ▝▀▜ ▌
// ▐ ▗ ▗ ▐ ▌
// ▐ ▐ ▛▀▀▀▀█
// ▗█ ▐ ▗▌ ▟▘
// ▟▀▐ ▐ ▟ ▐▘
// ▟▘ ▐▖ ▛▗▞ ▗▌
// ▟▘ ▙▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▟▀▀▀▀ ▗▛
// ▟▘ ▗▛
// ▟▙▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▛
//
// Lighter modification of ERC721, with some adjustments
// Warning: Does not implement IERC721.
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
/**
* @notice This implementation has some modifications compared to the standard ERC721.
* This should not be used unless the changes are understood.
* @dev Changes made to this contract:
* - `_balances` are not being tracked in order to save on gas.
* - `_owners` is internal, allowing for the super class to implement functions such as `balanceOf` and `tokenIdsOf`.
* - `balanceOf` is removed, meaning this contract doesn't follow the IERC721 standard. This could be implemented by
* an inefficient loop until the maximum index, however this implementation is left to the super contract.
*
* @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}.
*/
abstract contract ERC721X is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
uint256 private totalSupply;
// Mapping from token ID to owner address
mapping(uint256 => address) internal _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;
// Enumerable
// 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 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');
// // uint256 count;
// // for (uint256 i; i < totalSupply; ++i) if (owner == _owners[i]) count++;
// // return count;
// }
// function balanceOf(address owner) public view virtual override returns (uint256) {}
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 = ERC721X.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 = ERC721X.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;
totalSupply++;
emit Transfer(address(0), to, tokenId);
}
// function _mintUnchecked(address to, uint256 tokenId) internal virtual {
// _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 = ERC721X.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(ERC721X.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(ERC721X.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 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;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {
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);
}
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
function tokenByIndex(uint256 index) public view virtual returns (uint256) {
require(index < totalSupply, "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
uint256 lastTokenIndex = 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];
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
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();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (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.0 (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.0 (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.0 (utils/Address.sol)
pragma solidity ^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;
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);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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);
}
|
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./ Clear approvals from the previous owner
|
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721X.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);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
| 13,992,847
|
/**
*Submitted for verification at Etherscan.io on 2020-02-25
*/
pragma solidity ^0.5.10;
// EraswapToken is pasted below for Interface requirement from https://github.com/KMPARDS/EraSwapSmartContracts/blob/master/Eraswap/contracts/EraswapToken/EraswapToken.sol
pragma solidity ^0.5.9;
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);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal 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(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW
emit 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) {
return balances[_owner];
}
}
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
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
);
}
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string memory _name, string memory _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
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, 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(_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); //injected INTEGER OVERFLOW OR UNDERFLOW
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 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,
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); //injected INTEGER OVERFLOW OR UNDERFLOW
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
balances[_to] = balances[_to].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract CappedToken is MintableToken {
uint256 public cap;
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
public
returns (bool)
{
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
contract EraswapERC20 is DetailedERC20, BurnableToken, CappedToken {
string private name = "Eraswap";
string private symbol = "EST";
uint8 private decimals = 18;
uint256 private cap = 9100000000000000000000000000;
/**
* @dev Constructor
*/
constructor() internal DetailedERC20("Eraswap", "EST", 18) CappedToken(cap){
mint(msg.sender, 910000000000000000000000000);
}
}
contract NRTManager is Ownable, EraswapERC20{
using SafeMath for uint256;
uint256 public LastNRTRelease; // variable to store last release date
uint256 public MonthlyNRTAmount; // variable to store Monthly NRT amount to be released
uint256 public AnnualNRTAmount; // variable to store Annual NRT amount to be released
uint256 public MonthCount; // variable to store the count of months from the intial date
uint256 public luckPoolBal; // Luckpool Balance
uint256 public burnTokenBal; // tokens to be burned
// different pool address
address public newTalentsAndPartnerships;
address public platformMaintenance;
address public marketingAndRNR;
address public kmPards;
address public contingencyFunds;
address public researchAndDevelopment;
address public buzzCafe;
address public timeSwappers; // which include powerToken , curators ,timeTraders , daySwappers
address public TimeAlly; //address of TimeAlly Contract
uint256 public newTalentsAndPartnershipsBal; // variable to store last NRT released to the address;
uint256 public platformMaintenanceBal; // variable to store last NRT released to the address;
uint256 public marketingAndRNRBal; // variable to store last NRT released to the address;
uint256 public kmPardsBal; // variable to store last NRT released to the address;
uint256 public contingencyFundsBal; // variable to store last NRT released to the address;
uint256 public researchAndDevelopmentBal; // variable to store last NRT released to the address;
uint256 public buzzCafeNRT; // variable to store last NRT released to the address;
uint256 public TimeAllyNRT; // variable to store last NRT released to the address;
uint256 public timeSwappersNRT; // variable to store last NRT released to the address;
// Event to watch NRT distribution
// @param NRTReleased The amount of NRT released in the month
event NRTDistributed(uint256 NRTReleased);
/**
* Event to watch Transfer of NRT to different Pool
* @param pool - The pool name
* @param sendAddress - The address of pool
* @param value - The value of NRT released
**/
event NRTTransfer(string pool, address sendAddress, uint256 value);
// Event to watch Tokens Burned
// @param amount The amount burned
event TokensBurned(uint256 amount);
/**
* @dev Should burn tokens according to the total circulation
* @return true if success
*/
function burnTokens() internal returns (bool){
if(burnTokenBal == 0){
return true;
}
else{
uint MaxAmount = ((totalSupply()).mul(2)).div(100); // max amount permitted to burn in a month
if(MaxAmount >= burnTokenBal ){
burn(burnTokenBal);
burnTokenBal = 0;
}
else{
burnTokenBal = burnTokenBal.sub(MaxAmount);
burn(MaxAmount);
}
return true;
}
}
/**
* @dev To invoke monthly release
* @return true if success
*/
function MonthlyNRTRelease() external returns (bool) {
require(now.sub(LastNRTRelease)> 2592000);
uint256 NRTBal = MonthlyNRTAmount.add(luckPoolBal); // Total NRT available.
// Calculating NRT to be released to each of the pools
newTalentsAndPartnershipsBal = (NRTBal.mul(5)).div(100);
platformMaintenanceBal = (NRTBal.mul(10)).div(100);
marketingAndRNRBal = (NRTBal.mul(10)).div(100);
kmPardsBal = (NRTBal.mul(10)).div(100);
contingencyFundsBal = (NRTBal.mul(10)).div(100);
researchAndDevelopmentBal = (NRTBal.mul(5)).div(100);
buzzCafeNRT = (NRTBal.mul(25)).div(1000);
TimeAllyNRT = (NRTBal.mul(15)).div(100);
timeSwappersNRT = (NRTBal.mul(325)).div(1000);
// sending tokens to respective wallets and emitting events
mint(newTalentsAndPartnerships,newTalentsAndPartnershipsBal);
emit NRTTransfer("newTalentsAndPartnerships", newTalentsAndPartnerships, newTalentsAndPartnershipsBal);
mint(platformMaintenance,platformMaintenanceBal);
emit NRTTransfer("platformMaintenance", platformMaintenance, platformMaintenanceBal);
mint(marketingAndRNR,marketingAndRNRBal);
emit NRTTransfer("marketingAndRNR", marketingAndRNR, marketingAndRNRBal);
mint(kmPards,kmPardsBal);
emit NRTTransfer("kmPards", kmPards, kmPardsBal);
mint(contingencyFunds,contingencyFundsBal);
emit NRTTransfer("contingencyFunds", contingencyFunds, contingencyFundsBal);
mint(researchAndDevelopment,researchAndDevelopmentBal);
emit NRTTransfer("researchAndDevelopment", researchAndDevelopment, researchAndDevelopmentBal);
mint(buzzCafe,buzzCafeNRT);
emit NRTTransfer("buzzCafe", buzzCafe, buzzCafeNRT);
mint(TimeAlly,TimeAllyNRT);
emit NRTTransfer("stakingContract", TimeAlly, TimeAllyNRT);
mint(timeSwappers,timeSwappersNRT);
emit NRTTransfer("timeSwappers", timeSwappers, timeSwappersNRT);
// Reseting NRT
emit NRTDistributed(NRTBal);
luckPoolBal = 0;
LastNRTRelease = LastNRTRelease.add(30 days); // resetting release date again
burnTokens(); // burning burnTokenBal
emit TokensBurned(burnTokenBal);
if(MonthCount == 11){
MonthCount = 0;
AnnualNRTAmount = (AnnualNRTAmount.mul(9)).div(10);
MonthlyNRTAmount = MonthlyNRTAmount.div(12);
}
else{
MonthCount = MonthCount.add(1);
}
return true;
}
/**
* @dev Constructor
*/
constructor() public{
LastNRTRelease = now;
AnnualNRTAmount = 819000000000000000000000000;
MonthlyNRTAmount = AnnualNRTAmount.div(uint256(12));
MonthCount = 0;
}
}
contract PausableEraswap is NRTManager {
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require((now.sub(LastNRTRelease))< 2592000);
_;
}
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 EraswapToken is PausableEraswap {
/**
* Event to watch the addition of pool address
* @param pool - The pool name
* @param sendAddress - The address of pool
**/
event PoolAddressAdded(string pool, address sendAddress);
// Event to watch LuckPool Updation
// @param luckPoolBal The current luckPoolBal
event LuckPoolUpdated(uint256 luckPoolBal);
// Event to watch BurnTokenBal Updation
// @param burnTokenBal The current burnTokenBal
event BurnTokenBalUpdated(uint256 burnTokenBal);
/**
* @dev Throws if caller is not TimeAlly
*/
modifier OnlyTimeAlly() {
require(msg.sender == TimeAlly);
_;
}
/**
* @dev To update pool addresses
* @param pool - A List of pool addresses
* Updates if pool address is not already set and if given address is not zero
* @return true if success
*/
function UpdateAddresses (address[] memory pool) onlyOwner public returns(bool){
if((pool[0] != address(0)) && (newTalentsAndPartnerships == address(0))){
newTalentsAndPartnerships = pool[0];
emit PoolAddressAdded( "NewTalentsAndPartnerships", newTalentsAndPartnerships);
}
if((pool[1] != address(0)) && (platformMaintenance == address(0))){
platformMaintenance = pool[1];
emit PoolAddressAdded( "PlatformMaintenance", platformMaintenance);
}
if((pool[2] != address(0)) && (marketingAndRNR == address(0))){
marketingAndRNR = pool[2];
emit PoolAddressAdded( "MarketingAndRNR", marketingAndRNR);
}
if((pool[3] != address(0)) && (kmPards == address(0))){
kmPards = pool[3];
emit PoolAddressAdded( "KmPards", kmPards);
}
if((pool[4] != address(0)) && (contingencyFunds == address(0))){
contingencyFunds = pool[4];
emit PoolAddressAdded( "ContingencyFunds", contingencyFunds);
}
if((pool[5] != address(0)) && (researchAndDevelopment == address(0))){
researchAndDevelopment = pool[5];
emit PoolAddressAdded( "ResearchAndDevelopment", researchAndDevelopment);
}
if((pool[6] != address(0)) && (buzzCafe == address(0))){
buzzCafe = pool[6];
emit PoolAddressAdded( "BuzzCafe", buzzCafe);
}
if((pool[7] != address(0)) && (timeSwappers == address(0))){
timeSwappers = pool[7];
emit PoolAddressAdded( "TimeSwapper", timeSwappers);
}
if((pool[8] != address(0)) && (TimeAlly == address(0))){
TimeAlly = pool[8];
emit PoolAddressAdded( "TimeAlly", TimeAlly);
}
return true;
}
/**
* @dev Function to update luckpool balance
* @param amount Amount to be updated
*/
function UpdateLuckpool(uint256 amount) OnlyTimeAlly external returns(bool){
require(allowance(msg.sender, address(this)) >= amount);
require(transferFrom(msg.sender,address(this), amount));
luckPoolBal = luckPoolBal.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit LuckPoolUpdated(luckPoolBal);
return true;
}
/**
* @dev Function to trigger to update for burning of tokens
* @param amount Amount to be updated
*/
function UpdateBurnBal(uint256 amount) OnlyTimeAlly external returns(bool){
require(allowance(msg.sender, address(this)) >= amount);
require(transferFrom(msg.sender,address(this), amount));
burnTokenBal = burnTokenBal.add(amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit BurnTokenBalUpdated(burnTokenBal);
return true;
}
/**
* @dev Function to trigger balance update of a list of users
* @param TokenTransferList - List of user addresses
* @param TokenTransferBalance - Amount of token to be sent
*/
function UpdateBalance(address[100] calldata TokenTransferList, uint256[100] calldata TokenTransferBalance) OnlyTimeAlly external returns(bool){
for (uint256 i = 0; i < TokenTransferList.length; i++) {
require(allowance(msg.sender, address(this)) >= TokenTransferBalance[i]);
require(transferFrom(msg.sender, TokenTransferList[i], TokenTransferBalance[i]));
}
return true;
}
}
/// @title BetDeEx Smart Contract - The Decentralized Prediction Platform of Era Swap Ecosystem
/// @author The EraSwap Team
/// @notice This contract is used by manager to deploy new Bet contracts
/// @dev This contract also acts as treasurer
contract BetDeEx {
using SafeMath for uint256;
address[] public bets; /// @dev Stores addresses of bets
address public superManager; /// @dev Required to be public because ES needs to be sent transaparently.
EraswapToken esTokenContract;
mapping(address => uint256) public betBalanceInExaEs; /// @dev All ES tokens are transfered to main BetDeEx address for common allowance in ERC20 so this mapping stores total ES tokens betted in each bet.
mapping(address => bool) public isBetValid; /// @dev Stores authentic bet contracts (only deployed through this contract)
mapping(address => bool) public isManager; /// @dev Stores addresses who are given manager privileges by superManager
event NewBetContract (
address indexed _deployer,
address _contractAddress,
uint8 indexed _category,
uint8 indexed _subCategory,
string _description
);
event NewBetting (
address indexed _betAddress,
address indexed _bettorAddress,
uint8 indexed _choice,
uint256 _betTokensInExaEs
);
event EndBetContract (
address indexed _ender,
address indexed _contractAddress,
uint8 _result,
uint256 _prizePool,
uint256 _platformFee
);
/// @dev This event is for indexing ES withdrawl transactions to winner bettors from this contract
event TransferES (
address indexed _betContract,
address indexed _to,
uint256 _tokensInExaEs
);
modifier onlySuperManager() {
require(msg.sender == superManager, "only superManager can call");
_;
}
modifier onlyManager() {
require(isManager[msg.sender], "only manager can call");
_;
}
modifier onlyBetContract() {
require(isBetValid[msg.sender], "only bet contract can call");
_;
}
/// @notice Sets up BetDeEx smart contract when deployed
/// @param _esTokenContractAddress is EraSwap contract address
constructor(address _esTokenContractAddress) public {
superManager = msg.sender;
isManager[msg.sender] = true;
esTokenContract = EraswapToken(_esTokenContractAddress);
}
/// @notice This function is used to deploy a new bet
/// @param _description is the question of Bet in plain English, bettors have to understand the bet description and later choose to bet on yes no or draw according to their preference
/// @param _category is the broad category for example Sports. Purpose of this is only to filter bets and show in UI, hence the name of the category is not stored in smart contract and category is repressented by a number (0, 1, 2, 3...)
/// @param _subCategory is a specific category for example Football. Each category will have sub categories represented by a number (0, 1, 2, 3...)
/// @param _minimumBetInExaEs is the least amount of ExaES that can be betted, any bet participant (bettor) will have to bet this amount or higher. Betting higher amount gives more share of winning amount
/// @param _prizePercentPerThousand is a form of representation of platform fee. It is a number less than or equal to 1000. For eg 2% is to be collected as platform fee then this value would be 980. If 0.2% then 998.
/// @param _isDrawPossible is functionality for allowing a draw option
/// @param _pauseTimestamp Bet will be open for betting until this timestamp, after this timestamp, any user will not be able to place bet. and manager can only end bet after this time
/// @return address of newly deployed bet contract. This is for UI of Admin panel.
function createBet(
string memory _description,
uint8 _category,
uint8 _subCategory,
uint256 _minimumBetInExaEs,
uint256 _prizePercentPerThousand,
bool _isDrawPossible,
uint256 _pauseTimestamp
) public onlyManager returns (address) {
Bet _newBet = new Bet(
_description,
_category,
_subCategory,
_minimumBetInExaEs,
_prizePercentPerThousand,
_isDrawPossible,
_pauseTimestamp
);
bets.push(address(_newBet));
isBetValid[address(_newBet)] = true;
emit NewBetContract(
msg.sender,
address(_newBet),
_category,
_subCategory,
_description
);
return address(_newBet);
}
/// @notice this function is used for getting total number of bets
/// @return number of Bet contracts deployed by BetDeEx
function getNumberOfBets() public view returns (uint256) {
return bets.length;
}
/// @notice this is for giving access to multiple accounts to manage BetDeEx
/// @param _manager is address of new manager
function addManager(address _manager) public onlySuperManager {
isManager[_manager] = true;
}
/// @notice this is for revoking access of a manager to manage BetDeEx
/// @param _manager is address of manager who is to be converted into a former manager
function removeManager(address _manager) public onlySuperManager {
isManager[_manager] = false;
}
/// @notice this is an internal functionality that is only for bet contracts to emit a event when a new bet is placed so that front end can get the information by subscribing to contract
function emitNewBettingEvent(address _bettorAddress, uint8 _choice, uint256 _betTokensInExaEs) public onlyBetContract {
emit NewBetting(msg.sender, _bettorAddress, _choice, _betTokensInExaEs);
}
/// @notice this is an internal functionality that is only for bet contracts to emit event when a bet is ended so that front end can get the information by subscribing to contract
function emitEndEvent(address _ender, uint8 _result, uint256 _gasFee) public onlyBetContract {
emit EndBetContract(_ender, msg.sender, _result, betBalanceInExaEs[msg.sender], _gasFee);
}
/// @notice this is an internal functionality that is used to transfer tokens from bettor wallet to BetDeEx contract
function collectBettorTokens(address _from, uint256 _betTokensInExaEs) public onlyBetContract returns (bool) {
require(esTokenContract.transferFrom(_from, address(this), _betTokensInExaEs), "tokens should be collected from user");
betBalanceInExaEs[msg.sender] = betBalanceInExaEs[msg.sender].add(_betTokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
return true;
}
/// @notice this is an internal functionality that is used to transfer prizes to winners
function sendTokensToAddress(address _to, uint256 _tokensInExaEs) public onlyBetContract returns (bool) {
betBalanceInExaEs[msg.sender] = betBalanceInExaEs[msg.sender].sub(_tokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
require(esTokenContract.transfer(_to, _tokensInExaEs), "tokens should be sent");
emit TransferES(msg.sender, _to, _tokensInExaEs);
return true;
}
/// @notice this is an internal functionality that is used to collect platform fee
function collectPlatformFee(uint256 _platformFee) public onlyBetContract returns (bool) {
require(esTokenContract.transfer(superManager, _platformFee), "platform fee should be collected");
return true;
}
}
/// @title Bet Smart Contract
/// @author The EraSwap Team
/// @notice This contract is governs bettors and is deployed by BetDeEx Smart Contract
contract Bet {
using SafeMath for uint256;
BetDeEx betDeEx;
string public description; /// @dev question text of the bet
bool public isDrawPossible; /// @dev if false then user cannot bet on draw choice
uint8 public category; /// @dev sports, movies
uint8 public subCategory; /// @dev cricket, football
uint8 public finalResult; /// @dev given a value when manager ends bet
address public endedBy; /// @dev address of manager who enters the correct choice while ending the bet
uint256 public creationTimestamp; /// @dev set during bet creation
uint256 public pauseTimestamp; /// @dev set as an argument by deployer
uint256 public endTimestamp; /// @dev set when a manager ends bet and prizes are distributed
uint256 public minimumBetInExaEs; /// @dev minimum amount required to enter bet
uint256 public prizePercentPerThousand; /// @dev percentage of bet balance which will be dristributed to winners and rest is platform fee
uint256[3] public totalBetTokensInExaEsByChoice = [0, 0, 0]; /// @dev array of total bet value of no, yes, draw voters
uint256[3] public getNumberOfChoiceBettors = [0, 0, 0]; /// @dev stores number of bettors in a choice
uint256 public totalPrize; /// @dev this is the prize (platform fee is already excluded)
mapping(address => uint256[3]) public bettorBetAmountInExaEsByChoice; /// @dev mapps addresses to array of betAmount by choice
mapping(address => bool) public bettorHasClaimed; /// @dev set to true when bettor claims the prize
modifier onlyManager() {
require(betDeEx.isManager(msg.sender), "only manager can call");
_;
}
/// @notice this sets up Bet contract
/// @param _description is the question of Bet in plain English, bettors have to understand the bet description and later choose to bet on yes no or draw according to their preference
/// @param _category is the broad category for example Sports. Purpose of this is only to filter bets and show in UI, hence the name of the category is not stored in smart contract and category is repressented by a number (0, 1, 2, 3...)
/// @param _subCategory is a specific category for example Football. Each category will have sub categories represented by a number (0, 1, 2, 3...)
/// @param _minimumBetInExaEs is the least amount of ExaES that can be betted, any bet participant (bettor) will have to bet this amount or higher. Betting higher amount gives more share of winning amount
/// @param _prizePercentPerThousand is a form of representation of platform fee. It is a number less than or equal to 1000. For eg 2% is to be collected as platform fee then this value would be 980. If 0.2% then 998.
/// @param _isDrawPossible is functionality for allowing a draw option
/// @param _pauseTimestamp Bet will be open for betting until this timestamp, after this timestamp, any user will not be able to place bet. and manager can only end bet after this time
constructor(string memory _description, uint8 _category, uint8 _subCategory, uint256 _minimumBetInExaEs, uint256 _prizePercentPerThousand, bool _isDrawPossible, uint256 _pauseTimestamp) public {
description = _description;
isDrawPossible = _isDrawPossible;
category = _category;
subCategory = _subCategory;
minimumBetInExaEs = _minimumBetInExaEs;
prizePercentPerThousand = _prizePercentPerThousand;
betDeEx = BetDeEx(msg.sender);
creationTimestamp = now;
pauseTimestamp = _pauseTimestamp;
}
/// @notice this function gives amount of ExaEs that is total betted on this bet
function betBalanceInExaEs() public view returns (uint256) {
return betDeEx.betBalanceInExaEs(address(this));
}
/// @notice this function is used to place a bet on available choice
/// @param _choice should be 0, 1, 2; no => 0, yes => 1, draw => 2
/// @param _betTokensInExaEs is amount of bet
function enterBet(uint8 _choice, uint256 _betTokensInExaEs) public {
require(now < pauseTimestamp, "cannot enter after pause time");
require(_betTokensInExaEs >= minimumBetInExaEs, "betting tokens should be more than minimum");
/// @dev betDeEx contract transfers the tokens to it self
require(betDeEx.collectBettorTokens(msg.sender, _betTokensInExaEs), "betting tokens should be collected");
// @dev _choice can be 0 or 1 and it can be 2 only if isDrawPossible is true
if (_choice > 2 || (_choice == 2 && !isDrawPossible) ) {
require(false, "this choice is not available");
}
getNumberOfChoiceBettors[_choice] = getNumberOfChoiceBettors[_choice].add(1);
totalBetTokensInExaEsByChoice[_choice] = totalBetTokensInExaEsByChoice[_choice].add(_betTokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
bettorBetAmountInExaEsByChoice[msg.sender][_choice] = bettorBetAmountInExaEsByChoice[msg.sender][_choice].add(_betTokensInExaEs); //injected INTEGER OVERFLOW OR UNDERFLOW
betDeEx.emitNewBettingEvent(msg.sender, _choice, _betTokensInExaEs);
}
/// @notice this function is used by manager to load correct answer
/// @param _choice is the correct choice
function endBet(uint8 _choice) public onlyManager {
require(now >= pauseTimestamp, "cannot end bet before pause time");
require(endedBy == address(0), "Bet Already Ended");
// @dev _choice can be 0 or 1 and it can be 2 only if isDrawPossible is true
if(_choice < 2 || (_choice == 2 && isDrawPossible)) {
finalResult = _choice;
} else {
require(false, "this choice is not available");
}
endedBy = msg.sender;
endTimestamp = now;
/// @dev the platform fee is excluded from entire bet balance and this is the amount to be distributed
totalPrize = betBalanceInExaEs().mul(prizePercentPerThousand).div(1000);
/// @dev this is the left platform fee according to the totalPrize variable above
uint256 _platformFee = betBalanceInExaEs().sub(totalPrize);
/// @dev sending plaftrom fee to the super manager
require(betDeEx.collectPlatformFee(_platformFee), "platform fee should be collected");
betDeEx.emitEndEvent(endedBy, _choice, _platformFee);
}
/// @notice this function can be called by anyone to see how much winners are getting
/// @param _bettorAddress is address whose prize we want to see
/// @return winner prize of input address
function seeWinnerPrize(address _bettorAddress) public view returns (uint256) {
require(endTimestamp > 0, "cannot see prize before bet ends");
return bettorBetAmountInExaEsByChoice[_bettorAddress][finalResult].mul(totalPrize).div(totalBetTokensInExaEsByChoice[finalResult]);
}
/// @notice this function will be called after bet ends and winner bettors can withdraw their prize share
function withdrawPrize() public {
require(endTimestamp > 0, "cannot withdraw before end time");
require(!bettorHasClaimed[msg.sender], "cannot claim again");
require(bettorBetAmountInExaEsByChoice[msg.sender][finalResult] > minimumBetInExaEs, "caller should have a betting"); /// @dev to keep out option 0
uint256 _winningAmount = bettorBetAmountInExaEsByChoice[msg.sender][finalResult].mul(totalPrize).div(totalBetTokensInExaEsByChoice[finalResult]);
bettorHasClaimed[msg.sender] = true;
betDeEx.sendTokensToAddress(
msg.sender,
_winningAmount
);
}
}
|
this is an internal functionality that is only for bet contracts to emit a event when a new bet is placed so that front end can get the information by subscribing to contract
|
function emitNewBettingEvent(address _bettorAddress, uint8 _choice, uint256 _betTokensInExaEs) public onlyBetContract {
emit NewBetting(msg.sender, _bettorAddress, _choice, _betTokensInExaEs);
}
| 13,072,601
|
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/AgentMask.sol
|
Approves an external router or agent to act on a user's behalf. router The address of the external agent. nCalls The number of calls the external router is authorized to make. Set to uint32.max for unlimited. callPath The specific proxy sidecar callpath that the router is approved for /
|
function approveAgent (address router, uint32 nCalls, uint16 callPath) internal {
bytes32 key = agentKey(lockHolder_, router, callPath);
UserBalance storage bal = userBals_[key];
bal.agentCallsLeft_ = nCalls;
}
| 4,651,160
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
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/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "hardhat/console.sol";
/**
* @title MimeticPhantomAirDrop
* @notice This is an extremely light-weight forked version of OpenZeppelins
* ERC-721 implementation. Each case of implementation will vary and
* thus not all nuances have been covered in the implementation.
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721]
* Non-Fungible Token Standard, including the Metadata extension and
* combining with the uage of https://nftchance.medium.com/mimetic-metadata-how-to-create-a-truly-non-dilutive-nft-collection-in-2022-746a01f886c5[Mimetic Metadata] and https://0xinuarashi.medium.com/introduction-to-phantom-minting-503a508f9560[Phantom Minting] then finally https://eips.ethereum.org/EIPS/eip-2309[EIP2309]
* authors: nftchance, masonchain, 0xInuarashi
*/
contract ERC721 is
Context
, ERC165
, Ownable
, 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 from token ID to approved address
mapping(uint256 => mapping(address => address)) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
uint256 internal _supply;
IERC721 public parent;
/**
* @dev Initializes the contract by setting a `name` and a `symbol`
* to the token collection.
*/
constructor(
string memory name_
, string memory symbol_
, uint256 supply
, address _parent
) {
_name = name_;
_symbol = symbol_;
_supply = supply;
parent = IERC721(_parent);
}
/**
* @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);
}
function initialize(
uint256 _start
, uint256 _end
)
public
virtual
onlyOwner()
{
for(
uint256 i = _start;
i < _end;
i++
) {
emit Transfer(
address(0x0)
, address(this)
, i
);
}
}
function initializeToOwners(
uint256 _start
, uint256 _end
)
public
virtual
onlyOwner()
{
for(
uint256 i = _start;
i < _end;
i++
) {
emit Transfer(
address(0x0)
, parent.ownerOf(i)
, i
);
}
}
function initializeToCalldata(
uint256 _start
, uint256 _end
, address[] calldata accounts
)
public
virtual
onlyOwner()
{
require(
_end - _start == accounts.length
, "Incorrect amount of accounts provided."
);
uint256 index;
for(
uint256 i = _start;
i < _end;
i++
) {
console.log(i);
emit Transfer(
address(0x0)
, accounts[index++]
, i
);
}
}
/// @dev Implementing EIP-2309: https://eips.ethereum.org/EIPS/eip-2309
event ConsecutiveTransfer(
uint256 indexed fromTokenId
, uint256 toTokenId
, address indexed fromAddress
, address indexed toAddress
);
/**
* @notice This function emits an event that is listened to by NFT
* marketplaces and allows for the entire collection to be
* available and viewed even before ownership of tokens is
* written to as per common ERC implementation.
* @dev True ownership is determined by our parent collection
* interface until a transaction decouples ownership
* of this child token from the parent token.
*/
function initialize2309()
public
virtual
onlyOwner()
{
emit ConsecutiveTransfer(
0
, _supply
, address(0x0)
, address(this)
);
}
function initialize2309ToTarget(
uint256 _start
, uint256 _end
, address _to
)
public
virtual
onlyOwner()
{
emit ConsecutiveTransfer(
_start
, _end
, address(0x0)
, _to
);
}
/**
* @dev This function has been sacrificed with the implementation of
* the supply based for-loop. For large supplies, this handling
* will essentially prevent the usage of balanceOf() on-chain
* as gas consumption will be immense since this repo is
* merely intended for display purposes. (There are better ways
* to do this -- If you write it please make a pull request
* and it will get merged!)
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address _owner)
public
view
virtual
override
returns (
uint256 balance
)
{
require(
_owner != address(0)
, "ERC721: balance query for the zero address"
);
for(
uint256 i = _supply;
i > 0;
i--
) {
balance++;
}
}
/**
* @notice This function determines the active owner of the airdropped
* token. An address is not written to storage until the token has
* been claimed (which is not neccessary). If a token doesn't exist
* the owner of the Parent token it utilized.
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (
address
)
{
require(
tokenId < _supply
, "ERC721: approved query for nonexistent token"
);
// If the address has been written to storage use the stored address
if(_owners[tokenId] != address(0))
return _owners[tokenId];
// Fallback to use owner of the token that it was migrated from
return parent.ownerOf(tokenId);
}
/**
* @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;
}
/**
* @notice This function retrieves the URI of a given token id.
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (
string memory
)
{
require(
tokenId < _supply
, "ERC721: approved 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
)
{
return _tokenApprovals[tokenId][ERC721.ownerOf(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(
tokenId < _supply
, "ERC721: approved 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[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(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
delete _tokenApprovals[tokenId][_owner];
emit Approval(
_owner
, address(0)
, tokenId
);
delete _owners[tokenId];
emit Transfer(_owner, address(0), tokenId);
_afterTokenTransfer(_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 {
address _owner = ERC721.ownerOf(tokenId);
require(
_owner == from
, "ERC721: transfer from incorrect owner"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(
from
, to
, tokenId
);
// Clear approvals from the previous owner
delete _tokenApprovals[tokenId][_owner];
emit Approval(
_owner
, address(0)
, tokenId
);
_owners[tokenId] = to;
emit Transfer(
from
, to
, tokenId
);
_afterTokenTransfer(
from
, to
, tokenId
);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to
, uint256 tokenId
)
internal
virtual
{
address _owner = ERC721.ownerOf(tokenId);
_tokenApprovals[tokenId][_owner] = to;
emit Approval(_owner, 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 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 {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
|
See {IERC721-setApprovalForAll}./
|
function setApprovalForAll(
address operator
, bool approved
)
public
virtual
override
{
_setApprovalForAll(
_msgSender()
, operator
, approved
);
}
| 1,049,347
|
pragma solidity ^0.5.7;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract EIP20Interface {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public view returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// solhint-disable-next-line no-simple-event-func-name
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract EIP20 is EIP20Interface {
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
constructor(
uint256 _initialAmount,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol
) public {
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];
}
}
contract BitbattleExchange{
using SafeMath for uint256;
constructor(address _escrow, address _namiMultiSigWallet) public {
require(_namiMultiSigWallet != address(0));
escrow = _escrow;
namiMultiSigWallet = _namiMultiSigWallet;
// init token
// BinanceCoin
TokenAddress[0] = 0xB8c77482e45F1F44dE1745F52C74426C631bDD52;
// Maker
TokenAddress[1] = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2;
// BasicAttentionToken
TokenAddress[2] = 0x0D8775F648430679A709E98d2b0Cb6250d2887EF;
// OmiseGo
TokenAddress[3] = 0xd26114cd6EE289AccF82350c8d8487fedB8A0C07;
// Chainlink
TokenAddress[4] = 0x514910771AF9Ca656af840dff83E8264EcF986CA;
// Holo
TokenAddress[5] = 0x6c6EE5e31d828De241282B9606C8e98Ea48526E2;
// Zilliqa
TokenAddress[6] = 0x05f4a42e251f2d52b8ed15E9FEdAacFcEF1FAD27;
// Augur
TokenAddress[7] = 0x1985365e9f78359a9B6AD760e32412f4a445E862;
// 0x
TokenAddress[8] = 0xE41d2489571d322189246DaFA5ebDe1F4699F498;
// THETA
TokenAddress[9] = 0x3883f5e181fccaF8410FA61e12b59BAd963fb645;
// PundiX
TokenAddress[10] = 0xA15C7Ebe1f07CaF6bFF097D8a589fb8AC49Ae5B3;
// IOST
TokenAddress[11] = 0xFA1a856Cfa3409CFa145Fa4e20Eb270dF3EB21ab;
// EnjinCoin
TokenAddress[12] = 0xF629cBd94d3791C9250152BD8dfBDF380E2a3B9c;
// HuobiToken
TokenAddress[13] = 0x6f259637dcD74C767781E37Bc6133cd6A68aa161;
// Status
TokenAddress[14] = 0x744d70FDBE2Ba4CF95131626614a1763DF805B9E;
// Nami
TokenAddress[15] = 0x8d80de8A78198396329dfA769aD54d24bF90E7aa;
// Dai
TokenAddress[16] = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359;
// KyberNetwork
TokenAddress[17] = 0xdd974D5C2e2928deA5F71b9825b8b646686BD200;
// Golem
TokenAddress[18] = 0xa74476443119A942dE498590Fe1f2454d7D4aC0d;
// Populous
TokenAddress[19] = 0xd4fa1460F537bb9085d22C7bcCB5DD450Ef28e3a;
// CryptoCom
TokenAddress[20] = 0xB63B606Ac810a52cCa15e44bB630fd42D8d1d83d;
// Waltonchain
TokenAddress[21] = 0xb7cB1C96dB6B22b0D3d9536E0108d062BD488F74;
// Decentraland
TokenAddress[22] = 0x0F5D2fB29fb7d3CFeE444a200298f468908cC942;
// LoomNetwork
TokenAddress[23] = 0xA4e8C3Ec456107eA67d3075bF9e3DF3A75823DB0;
// Loopring
TokenAddress[24] = 0xEF68e7C694F40c8202821eDF525dE3782458639f;
// Aelf
TokenAddress[25] = 0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e;
// PowerLedger
TokenAddress[26] = 0x595832F8FC6BF59c85C527fEC3740A1b7a361269;
// USDCoin
TokenAddress[27] = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
}
// escrow has exclusive priveleges to call administrative
// functions on this contract.
address public escrow;
uint public minWithdraw = 1 * 10**18;
uint public maxWithdraw = 1000000 * 10**18;
// Gathered funds can be withdraw only to namimultisigwallet's address.
address public namiMultiSigWallet;
// Token Address
mapping(uint256 => address) public TokenAddress;
/**
* list setting function
*/
mapping(address => bool) public isController;
/**
* List event
*/
event Withdraw(address indexed user, uint amount, uint timeWithdraw, uint tokenIndex);
modifier onlyEscrow() {
require(msg.sender == escrow);
_;
}
modifier onlyNamiMultisig {
require(msg.sender == namiMultiSigWallet);
_;
}
modifier onlyController {
require(isController[msg.sender] == true);
_;
}
/**
* Admin function
*/
function() external payable {}
function changeEscrow(address _escrow) public
onlyNamiMultisig
{
require(_escrow != address(0));
escrow = _escrow;
}
function changeMinWithdraw(uint _minWithdraw) public
onlyEscrow
{
require(_minWithdraw != 0);
minWithdraw = _minWithdraw;
}
function changeMaxWithdraw(uint _maxNac) public
onlyEscrow
{
require(_maxNac != 0);
maxWithdraw = _maxNac;
}
/// @dev withdraw ether, only escrow can call
/// @param _amount value ether in wei to withdraw
function withdrawEther(uint _amount, address payable _to) public
onlyEscrow
{
require(_to != address(0x0));
// Available at any phase.
if (address(this).balance > 0) {
_to.transfer(_amount);
}
}
/**
* make new controller
* require input address is not a controller
* execute any time in sc state
*/
function setController(address _controller)
public
onlyEscrow
{
require(!isController[_controller]);
isController[_controller] = true;
}
/**
* remove controller
* require input address is a controller
* execute any time in sc state
*/
function removeController(address _controller)
public
onlyEscrow
{
require(isController[_controller]);
isController[_controller] = false;
}
/**
* update token address
*/
function updateTokenAddress(address payable _tokenAddress, uint _tokenIndex) public
onlyEscrow
{
require(_tokenAddress != address(0));
TokenAddress[_tokenIndex] = _tokenAddress;
}
function withdrawToken(address _account, uint _amount, uint _tokenIndex) public
onlyController
{
require(_account != address(0x0) && _amount != 0);
require(_amount >= minWithdraw && _amount <= maxWithdraw);
// check valid token index
require(TokenAddress[_tokenIndex] != address(0));
EIP20 ERC20Token = EIP20(TokenAddress[_tokenIndex]);
if (ERC20Token.balanceOf(address(this)) >= _amount) {
ERC20Token.transfer(_account, _amount);
} else {
revert();
}
// emit event
emit Withdraw(_account, _amount, now, _tokenIndex);
}
}
|
update token address/
|
function updateTokenAddress(address payable _tokenAddress, uint _tokenIndex) public
onlyEscrow
{
require(_tokenAddress != address(0));
TokenAddress[_tokenIndex] = _tokenAddress;
}
| 6,365,886
|
./full_match/1/0xf83c53c080E48e78A6B114eAB682d528562d33B5/sources/contracts/v2/OperatorFilterer/FairxyzOperatorFiltererUpgradeable.sol
|
See {IFairxyzOperatorFiltererUpgradeable-toggleOperatorFilterDisabled}./
|
function toggleOperatorFilterDisabled()
external
virtual
override
onlyOperatorFilterAdmin
{
bool disabled = !operatorFilterDisabled;
operatorFilterDisabled = disabled;
emit OperatorFilterDisabled(disabled);
}
| 3,850,765
|
pragma solidity ^0.5.2;
import "../openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "../openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "../openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol";
import "../openzeppelin-solidity/contracts/token/ERC721/IERC721.sol";
import "./interfaces/IHRSYToken.sol";
import "./WalletUser.sol";
/**
@dev HorseyExchange contract - handles horsey market exchange which
includes the following set of functions:
1. Deposit to Exchange
2. Cancel sale
3. Purchase token
**/
contract HorseyExchange is WalletUser, Pausable, Ownable, ERC721Holder { //also Ownable
event HorseyDeposit(uint256 indexed tokenId, uint256 price);
event SaleCanceled(uint256 indexed tokenId);
event HorseyPurchased(uint256 indexed tokenId, address newOwner, uint256 totalToPay);
/// @dev Fee applied to market maker - measured as percentage
uint256 public marketMakerFee = 3;
/// @dev Fee applied to market maker - measured as percentage
uint256 public devEquity = 50;
/// @dev Percent of the sale price going to the original owner of a token when its sold
uint256 public creatorEquity = 10;
/// @dev HRSY TOKEN
IERC721 public HRSY_ERC721;
IHRSYToken public HRSYToken;
/// @dev Devs cut is the amount of HORSE earned by devs through their equity
uint256 devCut;
/**
@dev used to store the price and the owner address of a token on sale
*/
struct SaleData {
uint256 price;
address owner;
}
/// @dev Market spec to lookup price and original owner based on token id
mapping (uint256 => SaleData) market;
/// @dev mapping of current tokens on market by owner
mapping (address => uint256[]) userBarn;
/**
@dev Creates a new HorseyExchange contract
This is the market to exchange HRSY tokens
@param walletAddress address of the Horsey wallet to use for purchases and fees
@param tokenAddress address of the HRSY token contract
*/
constructor(address walletAddress, address tokenAddress)
WalletUser(walletAddress)
Pausable()
Ownable()
ERC721Holder() public {
require(tokenAddress != address(0),"Invalid HRSY token address!");
HRSY_ERC721 = IERC721(tokenAddress);
HRSYToken = IHRSYToken(tokenAddress);
}
/**
@dev Allows the owner to change market fees
@param fees The new fees to apply (can be zero)
*/
function setMarketFees(uint256 fees) external
onlyOwner()
{
marketMakerFee = fees;
}
/**
@dev Allows the owner to change dev equities
@param equity The new equity to apply (can be zero)
*/
function setDevEquity(uint256 equity) external
onlyOwner()
{
devEquity = equity;
}
/**
@dev Allows the owner to change original token creator equity
@param equity The new equity to apply (can be zero)
*/
function setCreatorEquity(uint256 equity) external
onlyOwner()
{
creatorEquity = equity;
}
/// @return the tokens on sale based on the user address
function getTokensOnSale(address user) external view returns(uint256[] memory) {
return userBarn[user];
}
/// @return the token price with the fees
function getTokenPrice(uint256 tokenId) public view
isOnMarket(tokenId) returns (uint256) {
return market[tokenId].price + (market[tokenId].price / 100 * marketMakerFee);
}
/**
@dev User sends token to sell to exchange - at this point the exchange contract takes
ownership, but will map token ownership back to owner for auotmated withdraw on
cancel - requires that user is the rightful owner and is not
asking for a null price
*/
function depositToExchange(uint256 tokenId, uint256 price) external
whenNotPaused()
isTokenOwner(tokenId)
nonZeroPrice(price){
require(HRSY_ERC721.getApproved(tokenId) == address(this),"Exchange is not allowed to transfer");
uint8 upgradeCounter;
(,,,upgradeCounter) = IHRSYToken(address(HRSYToken)).horseys(tokenId);
require(upgradeCounter > 0,"Basic HRSY aren't tradable");
//Transfers token from depositee to exchange (contract address)
HRSY_ERC721.transferFrom(msg.sender, address(this), tokenId);
//add the token to the market
market[tokenId] = SaleData(price,msg.sender);
//Add token to exchange map - tracking by owner of all tokens
userBarn[msg.sender].push(tokenId);
emit HorseyDeposit(tokenId, price);
}
/**
@dev Allows true owner of token to cancel sale at anytime
@param tokenId ID of the token to remove from the market
@return true if user still has tokens for sale
*/
function cancelSale(uint256 tokenId) external
whenNotPaused()
originalOwnerOf(tokenId)
returns (bool) {
//throws on fail - transfers token from exchange back to original owner
HRSY_ERC721.transferFrom(address(this),msg.sender,tokenId);
//Reset token on market - remove
delete market[tokenId];
//Reset barn tracker for user
_removeTokenFromBarn(tokenId, msg.sender);
emit SaleCanceled(tokenId);
//Return true if this user is still 'active' within the exchange
//This will help with client side actions
return userBarn[msg.sender].length > 0;
}
/**
@dev Performs the purchase of a token that is present on the market - this includes checking that the
proper amount is sent + applied fee, updating seller's balance, updated collected fees and
transfering token to buyer
Only market tokens can be purchased
@param tokenId ID of the token we wish to purchase
*/
function purchaseToken(uint256 tokenId) external
whenNotPaused()
isOnMarket(tokenId)
notOriginalOwnerOf(tokenId)
{
uint256 totalToPay = getTokenPrice(tokenId);
require(_wallet.balanceOf(msg.sender) >= totalToPay,"Insufficient HORSE funds!");
//fetch this tokens sale data
SaleData memory sale = market[tokenId];
//Add to collected fee amount payable to DEVS
uint256 collectedFees = totalToPay - sale.price;
uint256 devFees = collectedFees / 100 * devEquity;
//pay the original owner
address originalOwner = IHRSYToken(HRSYToken).owners(tokenId);
uint256 creatorDue = sale.price / 100 * creatorEquity;
_wallet.transferFromAndTo(msg.sender,originalOwner,creatorDue);
//pay the seller
_wallet.transferFromAndTo(msg.sender,sale.owner,sale.price-creatorDue);
//pay the market fee to pool
_wallet.transferFromAndTo(msg.sender,address(_wallet),collectedFees);
//pay the devs
devCut = devCut + devFees;
//Reset barn tracker for user
_removeTokenFromBarn(tokenId, sale.owner);
//Reset token on market - remove
delete market[tokenId];
//Transfer the ERC721 to the buyer - we leave the sale amount
//to be withdrawn by the user (transferred from exchange)
HRSY_ERC721.transferFrom(address(this), msg.sender, tokenId);
emit HorseyPurchased(tokenId, msg.sender, totalToPay);
}
/**
@dev Owner can withdraw the current HORSE balance
*/
function withdraw() external
onlyOwner() {
if(devCut > 0) {
_wallet.withdrawPool(devCut); //get all the HORSE we earned from the wallet
//send them to our owner
_horseToken.transfer(owner(),devCut);
devCut = 0;
}
}
/**
@dev Internal function to remove a token from the users barn array
@param tokenId ID of the token to remove
@param barnAddress Address of the user selling tokens
*/
function _removeTokenFromBarn(uint tokenId, address barnAddress) internal {
uint256[] storage barnArray = userBarn[barnAddress];
require(barnArray.length > 0,"No tokens to remove");
int index = _indexOf(tokenId, barnArray);
require(index >= 0, "Token not found in barn");
// Shift entire array :(
for (uint256 i = uint256(index); i<barnArray.length-1; i++){
barnArray[i] = barnArray[i+1];
}
// Remove element, update length, return array
// this should be enough since https://ethereum.stackexchange.com/questions/1527/how-to-delete-an-element-at-a-certain-index-in-an-array
barnArray.length--;
}
/**
@dev Helper function which stores in memory an array which is passed in, and
@param item element we are looking for
@param array the array to look into
@return the index of the item of interest
*/
function _indexOf(uint item, uint256[] memory array) internal pure returns (int256){
//Iterate over array to find indexOf(token)
for(uint256 i = 0; i < array.length; i++){
if(array[i] == item){
return int256(i);
}
}
//Item not found
return -1;
}
/// @dev requires token to be on the market = current owner is exchange
modifier isOnMarket(uint256 tokenId) {
require(HRSYToken.ownerOf(tokenId) == address(this),"Token not on market");
_;
}
/// @dev Is the user the owner of this token?
modifier isTokenOwner(uint256 tokenId) {
require(HRSYToken.ownerOf(tokenId) == msg.sender,"Not tokens owner");
_;
}
/// @dev Is this the original owner of the token - at exchange level
modifier originalOwnerOf(uint256 tokenId) {
require(market[tokenId].owner == msg.sender,"Not the original owner of");
_;
}
/// @dev Is this the original owner of the token - at exchange level
modifier notOriginalOwnerOf(uint256 tokenId) {
require(market[tokenId].owner != msg.sender,"Is the original owner");
_;
}
/// @dev Is a nonzero price being sent?
modifier nonZeroPrice(uint256 price){
require(price > 0,"Price is zero");
_;
}
}
|
/ Shift entire array :(
|
function _removeTokenFromBarn(uint tokenId, address barnAddress) internal {
uint256[] storage barnArray = userBarn[barnAddress];
require(barnArray.length > 0,"No tokens to remove");
int index = _indexOf(tokenId, barnArray);
require(index >= 0, "Token not found in barn");
@dev Internal function to remove a token from the users barn array
@param tokenId ID of the token to remove
@param barnAddress Address of the user selling tokens
for (uint256 i = uint256(index); i<barnArray.length-1; i++){
barnArray[i] = barnArray[i+1];
}
barnArray.length--;
}
| 2,521,517
|
./full_match/1/0x657859E9d8fC27E2a9c72660db3938f83f368Ce0/sources/contracts/ELEMENTALPUNKS23.sol
|
Verify whitelist requirements
|
function whitelistMint(uint256 _mintAmount, bytes32[] calldata _merkleProof)
public
payable
mintCompliance(_mintAmount)
mintPriceCompliance(_mintAmount)
{
require(whitelistMintEnabled, "The whitelist sale is not enabled!");
require(totalSupply() + _mintAmount <= whitelistSupply, "wl supply exceeded!");
require(!whitelistClaimed[_msgSender()], "Address already claimed!");
bytes32 leaf = keccak256(abi.encodePacked(_msgSender()));
require(
MerkleProof.verify(_merkleProof, merkleRoot, leaf),
"Invalid proof!"
);
whitelistClaimed[_msgSender()] = true;
_safeMint(_msgSender(), _mintAmount);
}
| 9,781,630
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.7;
/*
██████╗ ███████╗ █████╗ ██╗ ██╗████████╗██╗ ██╗ ██████╗ █████╗ ██████╗ ██████╗ ███████╗
██╔══██╗██╔════╝██╔══██╗██║ ██║╚══██╔══╝╚██╗ ██╔╝██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔════╝
██████╔╝█████╗ ███████║██║ ██║ ██║ ╚████╔╝ ██║ ███████║██████╔╝██║ ██║███████╗
██╔══██╗██╔══╝ ██╔══██║██║ ██║ ██║ ╚██╔╝ ██║ ██╔══██║██╔══██╗██║ ██║╚════██║
██║ ██║███████╗██║ ██║███████╗██║ ██║ ██║ ╚██████╗██║ ██║██║ ██║██████╔╝███████║
╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═════╝ ╚══════╝
*/
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "hardhat/console.sol";
import "./interfaces/IRealitio.sol";
import "./interfaces/IRCFactory.sol";
import "./interfaces/IRCLeaderboard.sol";
import "./interfaces/IRCTreasury.sol";
import "./interfaces/IRCMarket.sol";
import "./interfaces/IRCNftHubL2.sol";
import "./interfaces/IRCOrderbook.sol";
import "./lib/NativeMetaTransaction.sol";
/// @title Reality Cards Market
/// @author Andrew Stanger & Daniel Chilvers
/// @notice If you have found a bug, please contact andrew@realitycards.io- no hack pls!!
contract RCMarket is Initializable, NativeMetaTransaction, IRCMarket {
/*╔═════════════════════════════════╗
║ VARIABLES ║
╚═════════════════════════════════╝*/
// CONTRACT SETUP
uint256 public constant PER_MILLE = 1000; // in MegaBip so (1000 = 100%)
/// @dev minimum rental value per day, setting to 24mil means 1 USDC/hour
uint256 public constant MIN_RENTAL_VALUE = 24_000_000;
/// @dev the number of cards in this market
uint256 public override numberOfCards;
/// @dev current market state, Closed -> Open -> Locked -> Withdraw
States public override state;
/// @dev type of event.
Mode public override mode;
/// @dev so the Factory can check it's a market
bool public constant override isMarket = true;
/// @dev how many nfts to award to the leaderboard
uint256 public override nftsToAward;
/// @dev the unique token id for each card
uint256[] public tokenIds;
// CONTRACT VARIABLES
IRCTreasury public override treasury;
IRCFactory public override factory;
IRCNftHubL2 public override nfthub;
IRCOrderbook public override orderbook;
IRCLeaderboard public override leaderboard;
IRealitio public override realitio;
// PRICE, DEPOSITS, RENT
/// @dev keeps track of all the rent paid by each user. So that it can be returned in case of an invalid market outcome.
mapping(address => uint256) public override rentCollectedPerUser;
/// @dev keeps track of the rent each user has paid for each card, for Safe mode payout
mapping(address => mapping(uint256 => uint256))
public
override rentCollectedPerUserPerCard;
/// @dev an easy way to track the above across all cards
uint256 public override totalRentCollected;
/// @dev prevents user from exiting and re-renting in the same block (limits troll attacks)
mapping(address => uint256) public override exitedTimestamp;
// PARAMETERS
/// @dev read from the Factory upon market creation, can not be changed for existing market
/// @dev the minimum required price increase in %
uint256 public override minimumPriceIncreasePercent;
/// @dev minimum rental duration (1 day divisor: i.e. 24 = 1 hour, 48 = 30 mins)
uint256 public override minRentalDayDivisor;
/// @dev maximum number of times to calculate rent in one transaction
uint256 public override maxRentIterations;
/// @dev maximum number of times to calculate rent and continue locking the market
uint256 public maxRentIterationsToLockMarket;
struct Card {
/// @dev how many seconds each user has held each card for, for determining winnings
mapping(address => uint256) timeHeld;
/// @dev sums all the timeHelds for each. Used when paying out. Should always increment at the same time as timeHeld
uint256 totalTimeHeld;
/// @dev used to determine the rent due. Rent is due for the period (now - timeLastCollected), at which point timeLastCollected is set to now.
uint256 timeLastCollected;
/// @dev to track who has owned it the most (for giving NFT to winner)
address longestOwner;
/// @dev to track the card timeHeldLimit for the current owner
uint256 cardTimeLimit;
/// @dev card price in wei
uint256 cardPrice;
/// @dev keeps track of all the rent paid for each card, for card specific affiliate payout
uint256 rentCollectedPerCard;
/// @dev prevent users claiming twice
mapping(address => bool) userAlreadyClaimed; // cardID // user // bool
/// @dev has this card affiliate been paid
bool cardAffiliatePaid;
}
mapping(uint256 => Card) public card;
// TIMESTAMPS
/// @dev when the market opens
uint32 public override marketOpeningTime;
/// @dev when the market locks
uint32 public override marketLockingTime;
/// @dev when the question can be answered on realitio
uint32 public override oracleResolutionTime;
// PAYOUT VARIABLES
/// @dev the winning card if known, otherwise type(uint256).max
uint256 public override winningOutcome;
/// @dev prevent users withdrawing twice
mapping(address => bool) public override userAlreadyWithdrawn;
/// @dev the artist
address public override artistAddress;
uint256 public override artistCut;
bool public override artistPaid;
/// @dev the affiliate
address public override affiliateAddress;
uint256 public override affiliateCut;
bool public override affiliatePaid;
/// @dev the winner
uint256 public override winnerCut;
/// @dev the market creator
address public override marketCreatorAddress;
uint256 public override creatorCut;
bool public override creatorPaid;
/// @dev card specific recipients
address[] public override cardAffiliateAddresses;
uint256 public override cardAffiliateCut;
/// @dev keeps track of which card is next to complete the
/// @dev .. accounting for when locking the market
uint256 public override cardAccountingIndex;
/// @dev has the market locking accounting been completed yet
bool public override accountingComplete;
/// @dev if true then copies of the NFT can only be minted for the winning outcome.
bool limitNFTsToWinners;
// ORACLE VARIABLES
bytes32 public override questionId;
address public override arbitrator;
uint32 public override timeout; // the time allowed for the answer to be corrected
/*╔═════════════════════════════════╗
║ EVENTS ║
╚═════════════════════════════════╝*/
event LogNewOwner(uint256 indexed cardId, address indexed newOwner);
event LogRentCollection(
uint256 rentCollected,
uint256 indexed newTimeHeld,
uint256 indexed cardId,
address indexed owner
);
event LogContractLocked(bool indexed didTheEventFinish);
event LogWinnerKnown(uint256 indexed winningOutcome);
event LogWinningsPaid(address indexed paidTo, uint256 indexed amountPaid);
event LogStakeholderPaid(
address indexed paidTo,
uint256 indexed amountPaid
);
event LogRentReturned(
address indexed returnedTo,
uint256 indexed amountReturned
);
event LogStateChange(uint256 indexed newState);
event LogUpdateTimeHeldLimit(
address indexed owner,
uint256 newLimit,
uint256 cardId
);
event LogSponsor(address indexed sponsor, uint256 indexed amount);
event LogPayoutDetails(
address indexed artistAddress,
address marketCreatorAddress,
address affiliateAddress,
address[] cardAffiliateAddresses,
uint256 indexed artistCut,
uint256 winnerCut,
uint256 creatorCut,
uint256 affiliateCut,
uint256 cardAffiliateCut
);
event LogSettings(
uint256 minRentalDayDivisor,
uint256 minimumPriceIncreasePercent,
uint256 nftsToAward,
bool nftsToWinningOutcomeOnly
);
event LogLongestOwner(uint256 cardId, address longestOwner);
event LogQuestionPostedToOracle(
address indexed marketAddress,
bytes32 indexed questionId
);
/*╔═════════════════════════════════╗
║ CONSTRUCTOR ║
╚═════════════════════════════════╝*/
/// @param _mode 0 = normal, 1 = winner takes all, 2 = Safe Mode
/// @param _timestamps for market opening, locking, and oracle resolution
/// @param _numberOfCards how many Cards in this market
/// @param _artistAddress where to send artist's cut, if any (zero address is valid)
/// @param _affiliateAddress where to send affiliate's cut, if any (zero address is valid)
/// @param _cardAffiliateAddresses where to send card specific affiliate's cut, if any (zero address is valid)
/// @param _marketCreatorAddress where to send market creator's cut, if any (zero address is valid)
/// @param _realitioQuestion the question posted to the Oracle
function initialize(
Mode _mode,
uint32[] memory _timestamps,
uint256 _numberOfCards,
address _artistAddress,
address _affiliateAddress,
address[] memory _cardAffiliateAddresses,
address _marketCreatorAddress,
string calldata _realitioQuestion,
uint256 _nftsToAward
) external override initializer {
mode = Mode(_mode);
// initialise MetaTransactions
_initializeEIP712("RealityCardsMarket", "1");
// external contract variables:
factory = IRCFactory(msgSender());
treasury = factory.treasury();
nfthub = factory.nfthub();
orderbook = factory.orderbook();
leaderboard = factory.leaderboard();
// get adjustable parameters from the factory/treasury
uint256[5] memory _potDistribution = factory.getPotDistribution();
minRentalDayDivisor = treasury.minRentalDayDivisor();
(
minimumPriceIncreasePercent,
maxRentIterations,
maxRentIterationsToLockMarket,
limitNFTsToWinners
) = factory.getMarketSettings();
// Initialize!
winningOutcome = type(uint256).max; // default invalid
// assign arguments to public variables
numberOfCards = _numberOfCards;
nftsToAward = _nftsToAward;
marketOpeningTime = _timestamps[0];
marketLockingTime = _timestamps[1];
oracleResolutionTime = _timestamps[2];
artistAddress = _artistAddress;
marketCreatorAddress = _marketCreatorAddress;
affiliateAddress = _affiliateAddress;
cardAffiliateAddresses = _cardAffiliateAddresses;
artistCut = _potDistribution[0];
winnerCut = _potDistribution[1];
creatorCut = _potDistribution[2];
affiliateCut = _potDistribution[3];
cardAffiliateCut = _potDistribution[4];
(realitio, arbitrator, timeout) = factory.getOracleSettings();
for (uint256 i = 0; i < _numberOfCards; i++) {
tokenIds.push(type(uint256).max);
}
// reduce artist cut to zero if zero address set
if (_artistAddress == address(0)) {
artistCut = 0;
}
// reduce affiliate cut to zero if zero address set
if (_affiliateAddress == address(0)) {
affiliateCut = 0;
}
// check the validity of card affiliate array.
// if not valid, reduce payout to zero
if (_cardAffiliateAddresses.length == _numberOfCards) {
for (uint256 i = 0; i < _numberOfCards; i++) {
if (_cardAffiliateAddresses[i] == address(0)) {
cardAffiliateCut = 0;
break;
}
}
} else {
cardAffiliateCut = 0;
}
// if winner takes all mode, set winnerCut to max
if (_mode == Mode.WINNER_TAKES_ALL) {
winnerCut =
(((uint256(PER_MILLE) - artistCut) - creatorCut) -
affiliateCut) -
cardAffiliateCut;
}
// post question to Oracle
_postQuestionToOracle(_realitioQuestion, _timestamps[2]);
// move to OPEN immediately if market opening time in the past
if (marketOpeningTime <= block.timestamp) {
_incrementState();
}
emit LogPayoutDetails(
_artistAddress,
_marketCreatorAddress,
_affiliateAddress,
cardAffiliateAddresses,
artistCut,
winnerCut,
creatorCut,
affiliateCut,
cardAffiliateCut
);
emit LogSettings(
minRentalDayDivisor,
minimumPriceIncreasePercent,
nftsToAward,
limitNFTsToWinners
);
}
/*╔═════════════════════════════════╗
║ MODIFIERS ║
╚═════════════════════════════════╝*/
/// @notice automatically opens market if appropriate
modifier autoUnlock() {
if (marketOpeningTime <= block.timestamp && state == States.CLOSED) {
_incrementState();
}
_;
}
/// @notice automatically locks market if appropriate
modifier autoLock() {
if (marketLockingTime <= block.timestamp) {
lockMarket();
}
_;
}
/*╔═════════════════════════════════╗
║ NFT HUB CONTRACT CALLS ║
╚═════════════════════════════════╝*/
/// @notice gets the owner of the NFT via their Card Id
function ownerOf(uint256 _cardId) public view override returns (address) {
require(_cardId < numberOfCards, "Card does not exist");
if (tokenExists(_cardId)) {
uint256 _tokenId = getTokenId(_cardId);
return nfthub.ownerOf(_tokenId);
} else {
return address(this);
}
}
/// @notice transfer ERC 721 between users
function _transferCard(
address _from,
address _to,
uint256 _cardId
) internal {
require(
_from != address(0) && _to != address(0),
"Cannot send to/from zero address"
);
uint256 _tokenId = getTokenId(_cardId);
nfthub.transferNft(_from, _to, _tokenId);
emit LogNewOwner(_cardId, _to);
}
/// @notice transfer ERC 721 between users
/// @dev called externally by Orderbook
function transferCard(
address _from,
address _to,
uint256 _cardId,
uint256 _price,
uint256 _timeLimit
) external override {
require(msgSender() == address(orderbook), "Not orderbook");
_checkState(States.OPEN);
if (_to != _from) {
_transferCard(_from, _to, _cardId);
}
card[_cardId].cardTimeLimit = _timeLimit;
card[_cardId].cardPrice = _price;
}
/*╔═════════════════════════════════╗
║ ORACLE FUNCTIONS ║
╚═════════════════════════════════╝*/
/// @dev called within initializer only
function _postQuestionToOracle(
string calldata _question,
uint32 _oracleResolutionTime
) internal {
uint256 templateId = 2; //template 2 works for all RealityCards questions
uint256 nonce = 0; // We don't need to ask it again, always use 0
bytes32 questionHash = keccak256(
abi.encodePacked(templateId, _oracleResolutionTime, _question)
);
questionId = keccak256(
abi.encodePacked(
questionHash,
arbitrator,
timeout,
address(this),
nonce
)
);
if (realitio.getContentHash(questionId) != questionHash) {
// check if our questionHash matches an existing questionId
// otherwise ask the question.
questionId = realitio.askQuestion(
templateId,
_question,
arbitrator,
timeout,
_oracleResolutionTime,
nonce
);
}
emit LogQuestionPostedToOracle(address(this), questionId);
}
/// @notice has the oracle finalised
function isFinalized() public view override returns (bool) {
bool _isFinalized = realitio.isFinalized(questionId);
return _isFinalized;
}
/// @dev sets the winning outcome
/// @dev market.setWinner() will revert if done twice, because wrong state
function getWinnerFromOracle() external override {
require(isFinalized(), "Oracle not finalised");
// check market state to prevent market closing early
require(marketLockingTime <= block.timestamp, "Market not finished");
bytes32 _winningOutcome = realitio.resultFor(questionId);
// call the market
setWinner(uint256(_winningOutcome));
}
/// @dev admin override of the oracle
function setAmicableResolution(uint256 _winningOutcome) external override {
require(
treasury.checkPermission(keccak256("OWNER"), msgSender()),
"Not authorised"
);
setWinner(_winningOutcome);
}
/*╔═════════════════════════════════╗
║ MARKET RESOLUTION FUNCTIONS ║
╚═════════════════════════════════╝*/
/// @notice Checks whether the competition has ended, if so moves to LOCKED state
/// @notice May require multiple calls as all accounting must be completed before
/// @notice the market should be locked.
/// @dev can be called by anyone
/// @dev public because called within autoLock modifier & setWinner
function lockMarket() public override {
_checkState(States.OPEN);
require(
uint256(marketLockingTime) <= block.timestamp,
"Market has not finished"
);
bool _cardAccountingComplete = false;
uint256 _rentIterationCounter = 0;
// do a final rent collection before the contract is locked down
while (cardAccountingIndex < numberOfCards && !accountingComplete) {
(_cardAccountingComplete, _rentIterationCounter) = _collectRent(
cardAccountingIndex,
_rentIterationCounter
);
if (_cardAccountingComplete) {
_cardAccountingComplete = false;
cardAccountingIndex++;
}
if (cardAccountingIndex == numberOfCards) {
accountingComplete = true;
break;
}
if (_rentIterationCounter >= maxRentIterations) {
break;
}
}
// check the accounting is complete but only continue if we haven't used much gas so far
/// @dev using gasleft() would be nice, but it causes problems with tx gas estimations
if (
accountingComplete &&
_rentIterationCounter < maxRentIterationsToLockMarket
) {
// and check that the orderbook has shut the market
if (orderbook.closeMarket()) {
// now lock the market
_incrementState();
for (uint256 i = 0; i < numberOfCards; i++) {
if (tokenExists(i)) {
// bring the cards back to the market so the winners get the satisfaction of claiming them
_transferCard(ownerOf(i), address(this), i);
}
emit LogLongestOwner(i, card[i].longestOwner);
}
emit LogContractLocked(true);
}
}
}
/// @notice called by getWinnerFromOracle, sets the winner
/// @param _winningOutcome the index of the winning card
function setWinner(uint256 _winningOutcome) internal {
if (state == States.OPEN) {
// change the locking time to allow lockMarket to lock
/// @dev implementing our own SafeCast as this is the only place we need it
require(block.timestamp <= type(uint32).max, "Overflow");
marketLockingTime = uint32(block.timestamp);
lockMarket();
}
if (state == States.LOCKED) {
// get the winner. This will revert if answer is not resolved.
winningOutcome = _winningOutcome;
_incrementState();
emit LogWinnerKnown(_winningOutcome);
}
}
/// @notice pays out winnings, or returns funds
function withdraw() external override {
_checkState(States.WITHDRAW);
require(!userAlreadyWithdrawn[msgSender()], "Already withdrawn");
userAlreadyWithdrawn[msgSender()] = true;
if (card[winningOutcome].totalTimeHeld > 0) {
_payoutWinnings();
} else {
_returnRent();
}
}
/// @notice the longest owner of each NFT gets to keep it
/// @notice users on the leaderboard can make a copy of it
/// @dev LOCKED or WITHDRAW states are fine- does not need to wait for winner to be known
/// @param _card the id of the card, the index
function claimCard(uint256 _card) external override {
_checkState(States.WITHDRAW);
require(
!treasury.marketPaused(address(this)) && !treasury.globalPause(),
"Market is Paused"
);
address _user = msgSender();
uint256 _tokenId = getTokenId(_card);
bool _winner = _card == winningOutcome; // invalid outcome defaults to losing
require(!card[_card].userAlreadyClaimed[_user], "Already claimed");
card[_card].userAlreadyClaimed[_user] = true;
if (_user == card[_card].longestOwner) {
factory.updateTokenOutcome(_card, _tokenId, _winner);
_transferCard(ownerOf(_card), card[_card].longestOwner, _card);
} else {
if (limitNFTsToWinners) {
require(_winner, "Not winning outcome");
}
leaderboard.claimNFT(_user, _card);
factory.mintCopyOfNFT(_user, _card, _tokenId, _winner);
}
}
/// @notice pays winnings
function _payoutWinnings() internal {
uint256 _winningsToTransfer = 0;
uint256 _remainingCut = ((((uint256(PER_MILLE) - artistCut) -
affiliateCut) - cardAffiliateCut) - winnerCut) - creatorCut;
address _msgSender = msgSender();
// calculate longest owner's extra winnings, if relevant
if (card[winningOutcome].longestOwner == _msgSender && winnerCut > 0) {
_winningsToTransfer =
(totalRentCollected * winnerCut) /
(PER_MILLE);
}
uint256 _remainingPot = 0;
if (mode == Mode.SAFE_MODE) {
// return all rent paid on winning card
_remainingPot =
((totalRentCollected -
card[winningOutcome].rentCollectedPerCard) *
_remainingCut) /
PER_MILLE;
_winningsToTransfer +=
(rentCollectedPerUserPerCard[_msgSender][winningOutcome] *
_remainingCut) /
PER_MILLE;
} else {
// calculate normal winnings, if any
_remainingPot = (totalRentCollected * _remainingCut) / (PER_MILLE);
}
uint256 _winnersTimeHeld = card[winningOutcome].timeHeld[_msgSender];
uint256 _numerator = _remainingPot * _winnersTimeHeld;
_winningsToTransfer += (_numerator /
card[winningOutcome].totalTimeHeld);
require(_winningsToTransfer > 0, "Not a winner");
_payout(_msgSender, _winningsToTransfer);
emit LogWinningsPaid(_msgSender, _winningsToTransfer);
}
/// @notice returns all funds to users in case of invalid outcome
function _returnRent() internal {
// deduct artist share and card specific share if relevant but NOT market creator share or winner's share (no winner, market creator does not deserve)
uint256 _remainingCut = ((uint256(PER_MILLE) - artistCut) -
affiliateCut) - cardAffiliateCut;
uint256 _rentCollected = rentCollectedPerUser[msgSender()];
require(_rentCollected > 0, "Paid no rent");
uint256 _rentCollectedAdjusted = (_rentCollected * _remainingCut) /
(PER_MILLE);
_payout(msgSender(), _rentCollectedAdjusted);
emit LogRentReturned(msgSender(), _rentCollectedAdjusted);
}
/// @notice all payouts happen through here
function _payout(address _recipient, uint256 _amount) internal {
treasury.payout(_recipient, _amount);
}
/// @dev the below functions pay stakeholders (artist, creator, affiliate, card specific affiliates)
/// @dev they are not called within setWinner() because of the risk of an
/// @dev .... address being a contract which refuses payment, then nobody could get winnings
/// @dev [hangover from when ether was native currency, keeping in case we return to this]
/// @notice pay artist
function payArtist() external override {
_checkState(States.WITHDRAW);
require(!artistPaid, "Artist already paid");
artistPaid = true;
_processStakeholderPayment(artistCut, artistAddress);
}
/// @notice pay market creator
function payMarketCreator() external override {
_checkState(States.WITHDRAW);
require(card[winningOutcome].totalTimeHeld > 0, "No winner");
require(!creatorPaid, "Creator already paid");
creatorPaid = true;
_processStakeholderPayment(creatorCut, marketCreatorAddress);
}
/// @notice pay affiliate
function payAffiliate() external override {
_checkState(States.WITHDRAW);
require(!affiliatePaid, "Affiliate already paid");
affiliatePaid = true;
_processStakeholderPayment(affiliateCut, affiliateAddress);
}
/// @notice pay card affiliate
/// @dev does not call _processStakeholderPayment because it works differently
function payCardAffiliate(uint256 _card) external override {
_checkState(States.WITHDRAW);
require(!card[_card].cardAffiliatePaid, "Card affiliate already paid");
card[_card].cardAffiliatePaid = true;
uint256 _cardAffiliatePayment = (card[_card].rentCollectedPerCard *
cardAffiliateCut) / (PER_MILLE);
if (_cardAffiliatePayment > 0) {
_payout(cardAffiliateAddresses[_card], _cardAffiliatePayment);
emit LogStakeholderPaid(
cardAffiliateAddresses[_card],
_cardAffiliatePayment
);
}
}
function _processStakeholderPayment(uint256 _cut, address _recipient)
internal
{
if (_cut > 0) {
uint256 _payment = (totalRentCollected * _cut) / (PER_MILLE);
_payout(_recipient, _payment);
emit LogStakeholderPaid(_recipient, _payment);
}
}
/*╔═════════════════════════════════╗
║ CORE FUNCTIONS ║
╠═════════════════════════════════╣
║ EXTERNAL ║
╚═════════════════════════════════╝*/
/// @dev basically functions that have _checkState(States.OPEN) on first line
/// @notice collects rent a specific card
function collectRent(uint256 _cardId) external override returns (bool) {
_checkState(States.OPEN);
bool _success;
(_success, ) = _collectRent(_cardId, 0);
if (_success) {
return true;
}
return false;
}
/// @notice rent every Card at the minimum price
/// @param _maxSumOfPrices a limit to the sum of the bids to place
function rentAllCards(uint256 _maxSumOfPrices) external override {
_checkState(States.OPEN);
// check that not being front run
uint256 _actualSumOfPrices = 0;
address _user = msgSender();
for (uint256 i = 0; i < numberOfCards; i++) {
if (ownerOf(i) != _user) {
_actualSumOfPrices += minPriceIncreaseCalc(card[i].cardPrice);
}
}
require(_actualSumOfPrices <= _maxSumOfPrices, "Prices too high");
for (uint256 i = 0; i < numberOfCards; i++) {
if (ownerOf(i) != _user) {
uint256 _newPrice = minPriceIncreaseCalc(card[i].cardPrice);
newRental(_newPrice, 0, address(0), i);
}
}
}
/// @notice to rent a Card
/// @param _newPrice the price to rent the card for
/// @param _timeHeldLimit an optional time limit to rent the card for
/// @param _startingPosition where to start looking to insert the bid into the orderbook
/// @param _card the index of the card to update
function newRental(
uint256 _newPrice,
uint256 _timeHeldLimit,
address _startingPosition,
uint256 _card
) public override autoUnlock autoLock {
// if the market isn't open then don't do anything else, not reverting
// .. will allow autoLock to process the accounting to lock the market
if (state == States.OPEN) {
require(_newPrice >= MIN_RENTAL_VALUE, "Price below min");
require(_card < numberOfCards, "Card does not exist");
// if the NFT hasn't been minted, we should probably do that
if (!tokenExists(_card)) {
tokenIds[_card] = nfthub.totalSupply();
factory.mintMarketNFT(_card);
}
address _user = msgSender();
// prevent re-renting, this limits (but doesn't eliminate) a frontrunning attack
require(
exitedTimestamp[_user] != block.timestamp,
"Cannot lose and re-rent in same block"
);
require(
!treasury.marketPaused(address(this)) &&
!treasury.globalPause(),
"Rentals are disabled"
);
// restrict certain markets to specific whitelists
require(
treasury.marketWhitelistCheck(_user),
"Not approved for this market"
);
// if the user is foreclosed then delete some old bids
// .. this could remove their foreclosure
if (treasury.isForeclosed(_user)) {
orderbook.removeUserFromOrderbook(_user);
}
require(
!treasury.isForeclosed(_user),
"Can't rent while foreclosed"
);
if (ownerOf(_card) == _user) {
// the owner may only increase by more than X% or reduce their price
uint256 _requiredPrice = (card[_card].cardPrice *
(minimumPriceIncreasePercent + 100)) / (100);
require(
_newPrice >= _requiredPrice ||
_newPrice < card[_card].cardPrice,
"Invalid price"
);
}
// do some cleaning up before we collect rent or check their bidRate
orderbook.removeOldBids(_user);
/// @dev ignore the return value and let the user post the bid for the sake of UX
_collectRent(_card, 0);
// check sufficient deposit
uint256 _userTotalBidRate = (treasury.userTotalBids(_user) -
orderbook.getBidValue(_user, _card)) + _newPrice;
require(
treasury.userDeposit(_user) >=
_userTotalBidRate / minRentalDayDivisor,
"Insufficient deposit"
);
_checkTimeHeldLimit(_timeHeldLimit);
orderbook.addBidToOrderbook(
_user,
_card,
_newPrice,
_timeHeldLimit,
_startingPosition
);
treasury.updateLastRentalTime(_user);
}
}
/// @notice to change your timeHeldLimit without having to re-rent
/// @param _timeHeldLimit an optional time limit to rent the card for
/// @param _card the index of the card to update
function updateTimeHeldLimit(uint256 _timeHeldLimit, uint256 _card)
external
override
{
_checkState(States.OPEN);
address _user = msgSender();
bool rentCollected;
(rentCollected, ) = _collectRent(_card, 0);
if (rentCollected) {
_checkTimeHeldLimit(_timeHeldLimit);
orderbook.setTimeHeldlimit(_user, _card, _timeHeldLimit);
if (ownerOf(_card) == _user) {
card[_card].cardTimeLimit = _timeHeldLimit;
}
emit LogUpdateTimeHeldLimit(_user, _timeHeldLimit, _card);
}
}
/// @notice stop renting all cards
function exitAll() external override {
for (uint256 i = 0; i < numberOfCards; i++) {
exit(i);
}
}
/// @notice stop renting a card and/or remove from orderbook
/// @dev public because called by exitAll()
/// @dev doesn't need to be current owner so user can prevent ownership returning to them
/// @dev does not apply minimum rental duration, because it returns ownership to the next user
/// @dev doesn't revert if non-existant bid because user might be trying to exitAll()
/// @param _card The card index to exit
function exit(uint256 _card) public override {
_checkState(States.OPEN);
address _msgSender = msgSender();
// collectRent first
/// @dev ignore the return value and let the user exit the bid for the sake of UX
_collectRent(_card, 0);
if (ownerOf(_card) == _msgSender) {
// block frontrunning attack
exitedTimestamp[_msgSender] = block.timestamp;
// if current owner, find a new one
orderbook.findNewOwner(_card, block.timestamp);
assert(!orderbook.bidExists(_msgSender, address(this), _card));
} else {
// if not owner, just delete from orderbook
if (orderbook.bidExists(_msgSender, address(this), _card)) {
// block frontrunning attack
exitedTimestamp[_msgSender] = block.timestamp;
orderbook.removeBidFromOrderbook(_msgSender, _card);
}
}
}
/// @notice ability to add liquidity to the pot without being able to win.
/// @dev called by user, sponsor is msgSender
function sponsor(uint256 _amount) external override {
address _creator = msgSender();
_sponsor(_creator, _amount);
}
/// @notice ability to add liquidity to the pot without being able to win.
/// @dev called by Factory during market creation
/// @param _sponsorAddress the msgSender of createMarket in the Factory
function sponsor(address _sponsorAddress, uint256 _amount)
external
override
{
address _msgSender = msgSender();
if (_msgSender != address(factory)) {
_sponsorAddress = _msgSender;
}
_sponsor(_sponsorAddress, _amount);
}
/*╔═════════════════════════════════╗
║ CORE FUNCTIONS ║
╠═════════════════════════════════╣
║ INTERNAL ║
╚═════════════════════════════════╝*/
/// @dev actually processes the sponsorship
function _sponsor(address _sponsorAddress, uint256 _amount) internal {
_checkNotState(States.LOCKED);
_checkNotState(States.WITHDRAW);
require(_amount > 0, "Must send something");
// send tokens to the Treasury
treasury.sponsor(_sponsorAddress, _amount);
totalRentCollected = totalRentCollected + _amount;
// just so user can get it back if invalid outcome
rentCollectedPerUser[_sponsorAddress] =
rentCollectedPerUser[_sponsorAddress] +
_amount;
// allocate equally to each card, in case card specific affiliates
for (uint256 i = 0; i < numberOfCards; i++) {
card[i].rentCollectedPerCard =
card[i].rentCollectedPerCard +
(_amount / numberOfCards);
}
emit LogSponsor(_sponsorAddress, _amount);
}
function _checkTimeHeldLimit(uint256 _timeHeldLimit) internal view {
if (_timeHeldLimit != 0) {
uint256 _minRentalTime = uint256(1 days) / minRentalDayDivisor;
require(_timeHeldLimit >= _minRentalTime, "Limit too low");
}
}
/// @dev _collectRentAction goes back one owner at a time, this function repeatedly calls
/// @dev ... _collectRentAction until the backlog of next owners has been processed, or maxRentIterations hit
/// @param _card the card id to collect rent for
/// @return true if the rent collection was completed, (ownership updated to the current time)
function _collectRent(uint256 _card, uint256 _counter)
internal
returns (bool, uint256)
{
bool shouldContinue = true;
while (_counter < maxRentIterations && shouldContinue) {
shouldContinue = _collectRentAction(_card);
_counter++;
}
return (!shouldContinue, _counter);
}
/// @notice collects rent for a specific card
/// @dev also calculates and updates how long the current user has held the card for
/// @dev is not a problem if called externally, but making internal over public to save gas
/// @param _card the card id to collect rent for
/// @return true if we should repeat the rent collection
function _collectRentAction(uint256 _card) internal returns (bool) {
address _user = ownerOf(_card);
uint256 _timeOfThisCollection = block.timestamp;
// don't collect rent beyond the locking time
if (marketLockingTime <= block.timestamp) {
_timeOfThisCollection = marketLockingTime;
}
//only collect rent if the card is owned (ie, if owned by the contract this implies unowned)
// AND if the last collection was in the past (ie, don't do 2+ rent collections in the same block)
if (
_user != address(this) &&
card[_card].timeLastCollected < _timeOfThisCollection
) {
// User rent collect and fetch the time the user foreclosed, 0 means they didn't foreclose yet
uint256 _timeUserForeclosed = treasury.collectRentUser(
_user,
_timeOfThisCollection
);
// Calculate the card timeLimitTimestamp
uint256 _cardTimeLimitTimestamp = card[_card].timeLastCollected +
card[_card].cardTimeLimit;
// input bools
bool _foreclosed = _timeUserForeclosed != 0;
bool _limitHit = card[_card].cardTimeLimit != 0 &&
_cardTimeLimitTimestamp < block.timestamp;
// outputs
bool _newOwner = false;
uint256 _refundTime = 0; // seconds of rent to refund the user
/* Permutations of the events: Foreclosure and Time limit
┌───────────┬─┬─┬─┬─┐
│Case │1│2│3│4│
├───────────┼─┼─┼─┼─┤
│Foreclosure│0│0│1│1│
│Time Limit │0│1│0│1│
└───────────┴─┴─┴─┴─┘
*/
if (!_foreclosed && !_limitHit) {
// CASE 1
// didn't foreclose AND
// didn't hit time limit
// THEN simple rent collect, same owner
_timeOfThisCollection = _timeOfThisCollection;
_newOwner = false;
_refundTime = 0;
} else if (!_foreclosed && _limitHit) {
// CASE 2
// didn't foreclose AND
// did hit time limit
// THEN refund rent between time limit and now
_timeOfThisCollection = _cardTimeLimitTimestamp;
_newOwner = true;
_refundTime = block.timestamp - _cardTimeLimitTimestamp;
} else if (_foreclosed && !_limitHit) {
// CASE 3
// did foreclose AND
// didn't hit time limit
// THEN rent OK, find new owner
_timeOfThisCollection = _timeUserForeclosed;
_newOwner = true;
_refundTime = 0;
} else if (_foreclosed && _limitHit) {
// CASE 4
// did foreclose AND
// did hit time limit
// THEN if foreclosed first rent ok, otherwise refund after limit
if (_timeUserForeclosed < _cardTimeLimitTimestamp) {
// user foreclosed before time limit
_timeOfThisCollection = _timeUserForeclosed;
_newOwner = true;
_refundTime = 0;
} else {
// time limit hit before user foreclosed
_timeOfThisCollection = _cardTimeLimitTimestamp;
_newOwner = true;
_refundTime = _timeUserForeclosed - _cardTimeLimitTimestamp;
}
}
if (_refundTime != 0) {
uint256 _refundAmount = (_refundTime * card[_card].cardPrice) /
1 days;
treasury.refundUser(_user, _refundAmount);
}
_processRentCollection(_user, _card, _timeOfThisCollection); // where the rent collection actually happens
if (_newOwner) {
orderbook.findNewOwner(_card, _timeOfThisCollection);
return true;
}
} else {
// timeLastCollected is updated regardless of whether the card is owned, so that the clock starts ticking
// ... when the first owner buys it, because this function is run before ownership changes upon calling newRental
card[_card].timeLastCollected = _timeOfThisCollection;
}
return false;
}
/// @dev processes actual rent collection and updates the state
function _processRentCollection(
address _user,
uint256 _card,
uint256 _timeOfCollection
) internal {
uint256 _timeHeldToIncrement = (_timeOfCollection -
card[_card].timeLastCollected);
uint256 _rentOwed = (card[_card].cardPrice * _timeHeldToIncrement) /
1 days;
// if the user has a timeLimit, adjust it as necessary
if (card[_card].cardTimeLimit != 0) {
orderbook.reduceTimeHeldLimit(_user, _card, _timeHeldToIncrement);
card[_card].cardTimeLimit -= _timeHeldToIncrement;
}
// update time
card[_card].timeHeld[_user] += _timeHeldToIncrement;
card[_card].totalTimeHeld += _timeHeldToIncrement;
card[_card].timeLastCollected = _timeOfCollection;
// longest owner tracking
if (
card[_card].timeHeld[_user] >
card[_card].timeHeld[card[_card].longestOwner]
) {
card[_card].longestOwner = _user;
}
// update amounts
/// @dev get back the actual rent collected, it may be less than owed
uint256 _rentCollected = treasury.payRent(_rentOwed);
card[_card].rentCollectedPerCard += _rentCollected;
rentCollectedPerUserPerCard[_user][_card] += _rentCollected;
rentCollectedPerUser[_user] += _rentCollected;
totalRentCollected += _rentCollected;
leaderboard.updateLeaderboard(
_user,
_card,
card[_card].timeHeld[_user]
);
emit LogRentCollection(
_rentCollected,
_timeHeldToIncrement,
_card,
_user
);
}
function _checkState(States currentState) internal view {
require(state == currentState, "Incorrect state");
}
function _checkNotState(States currentState) internal view {
require(state != currentState, "Incorrect state");
}
/// @dev should only be called thrice
function _incrementState() internal {
state = States(uint256(state) + 1);
emit LogStateChange(uint256(state));
}
/// @notice returns the tokenId (the unique NFT index) given the cardId (the market specific index)
/// @param _card the market specific index of the card
/// @return _tokenId the unique NFT index
function getTokenId(uint256 _card)
public
view
override
returns (uint256 _tokenId)
{
require(tokenExists(_card));
return tokenIds[_card];
}
function minPriceIncreaseCalc(uint256 _oldPrice)
internal
view
returns (uint256 _newPrice)
{
if (_oldPrice == 0) {
return MIN_RENTAL_VALUE;
} else {
return (_oldPrice * (minimumPriceIncreasePercent + 100)) / 100;
}
}
/*╔═════════════════════════════════╗
║ VIEW FUNCTIONS ║
╚═════════════════════════════════╝*/
/// @notice Check if the NFT has been minted yet
/// @param _card the market specific index of the card
/// @return true if the NFT has been minted
function tokenExists(uint256 _card) internal view returns (bool) {
if (_card >= numberOfCards) return false;
return tokenIds[_card] != type(uint256).max;
}
/// @dev a simple getter for the time a user has held a given card
function timeHeld(uint256 _card, address _user)
external
view
override
returns (uint256)
{
return card[_card].timeHeld[_user];
}
/// @dev a simple getter for the time a card last had rent collected
function timeLastCollected(uint256 _card)
external
view
override
returns (uint256)
{
return card[_card].timeLastCollected;
}
/// @dev a simple getter for the longest owner of a card
function longestOwner(uint256 _card)
external
view
override
returns (address)
{
return card[_card].longestOwner;
}
/*╔═════════════════════════════════╗
║ BACKUP MODE ║
╚═════════════════════════════════╝*/
/// @dev in the event of failures in the UI we need a simple reliable way to poll
/// @dev ..the contracts for relevant info, this view function helps facilitate this.
/// @dev quick and easy view function to get all market data relevant to the UI
function getMarketInfo()
external
view
returns (
States,
string memory,
uint256,
uint256,
address[] memory,
uint256[] memory
)
{
address[] memory _owners = new address[](numberOfCards);
uint256[] memory _prices = new uint256[](numberOfCards);
for (uint256 i = 0; i < numberOfCards; i++) {
_owners[i] = ownerOf(i);
_prices[i] = card[i].cardPrice;
}
return (
state,
factory.ipfsHash(address(this)),
winningOutcome,
totalRentCollected,
_owners,
_prices
);
}
/*
▲
▲ ▲
*/
}
|
pays out winnings, or returns funds
|
function withdraw() external override {
_checkState(States.WITHDRAW);
require(!userAlreadyWithdrawn[msgSender()], "Already withdrawn");
userAlreadyWithdrawn[msgSender()] = true;
if (card[winningOutcome].totalTimeHeld > 0) {
_payoutWinnings();
_returnRent();
}
}
| 12,778,634
|
/**
*Submitted for verification at Etherscan.io on 2022-01-19
*/
//SPDX-License-Identifier: lgplv3 OR MIT
// File: @openzeppelin/contracts/proxy/Proxy.sol
// OpenZeppelin Contracts v4.4.1 (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
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 This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// File: @openzeppelin/contracts/proxy/beacon/IBeacon.sol
// 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 IBeacon {
/**
* @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/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^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;
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);
}
}
}
}
// File: @openzeppelin/contracts/utils/StorageSlot.sol
// 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 StorageSlot {
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/proxy/ERC1967/ERC1967Upgrade.sol
// 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 ERC1967Upgrade {
// 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 StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.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) {
Address.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) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.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 StorageSlot.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");
StorageSlot.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 StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.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) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// File: @openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an
* implementation address that can be changed. This address is stored in storage in the location specified by
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the
* implementation behind the proxy.
*/
contract ERC1967Proxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.
*
* If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded
* function call, and allows initializating the storage of the proxy like a Solidity constructor.
*/
constructor(address _logic, bytes memory _data) payable {
assert(_IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_upgradeToAndCall(_logic, _data, false);
}
/**
* @dev Returns the current implementation address.
*/
function _implementation() internal view virtual override returns (address impl) {
return ERC1967Upgrade._getImplementation();
}
}
// File: @openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol
// OpenZeppelin Contracts v4.4.1 (proxy/transparent/TransparentUpgradeableProxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This contract implements a proxy that is upgradeable by an admin.
*
* To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector
* clashing], which can potentially be used in an attack, this contract uses the
* https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two
* things that go hand in hand:
*
* 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if
* that call matches one of the admin functions exposed by the proxy itself.
* 2. If the admin calls the proxy, it can access the admin functions, but its calls will never be forwarded to the
* implementation. If the admin tries to call a function on the implementation it will fail with an error that says
* "admin cannot fallback to proxy target".
*
* These properties mean that the admin account can only be used for admin actions like upgrading the proxy or changing
* the admin, so it's best if it's a dedicated account that is not used for anything else. This will avoid headaches due
* to sudden errors when trying to call a function from the proxy implementation.
*
* Our recommendation is for the dedicated account to be an instance of the {ProxyAdmin} contract. If set up this way,
* you should think of the `ProxyAdmin` instance as the real administrative interface of your proxy.
*/
contract TransparentUpgradeableProxy is ERC1967Proxy {
/**
* @dev Initializes an upgradeable proxy managed by `_admin`, backed by the implementation at `_logic`, and
* optionally initialized with `_data` as explained in {ERC1967Proxy-constructor}.
*/
constructor(
address _logic,
address admin_,
bytes memory _data
) payable ERC1967Proxy(_logic, _data) {
assert(_ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_changeAdmin(admin_);
}
/**
* @dev Modifier used internally that will delegate the call to the implementation unless the sender is the admin.
*/
modifier ifAdmin() {
if (msg.sender == _getAdmin()) {
_;
} else {
_fallback();
}
}
/**
* @dev Returns the current admin.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyAdmin}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function admin() external ifAdmin returns (address admin_) {
admin_ = _getAdmin();
}
/**
* @dev Returns the current implementation.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-getProxyImplementation}.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using the
* https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc`
*/
function implementation() external ifAdmin returns (address implementation_) {
implementation_ = _implementation();
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-changeProxyAdmin}.
*/
function changeAdmin(address newAdmin) external virtual ifAdmin {
_changeAdmin(newAdmin);
}
/**
* @dev Upgrade the implementation of the proxy.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgrade}.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeToAndCall(newImplementation, bytes(""), false);
}
/**
* @dev Upgrade the implementation of the proxy, and then call a function from the new implementation as specified
* by `data`, which should be an encoded function call. This is useful to initialize new storage variables in the
* proxied contract.
*
* NOTE: Only the admin can call this function. See {ProxyAdmin-upgradeAndCall}.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeToAndCall(newImplementation, data, true);
}
/**
* @dev Returns the current admin.
*/
function _admin() internal view virtual returns (address) {
return _getAdmin();
}
/**
* @dev Makes sure the admin cannot access the fallback function. See {Proxy-_beforeFallback}.
*/
function _beforeFallback() internal virtual override {
require(msg.sender != _getAdmin(), "TransparentUpgradeableProxy: admin cannot fallback to proxy target");
super._beforeFallback();
}
}
// File: contracts/ERC721TokenReceiver.sol
pragma solidity ^0.8.0;
contract ERC721TokenReceiver {
function onERC721Received(
address,
address,
uint256,
bytes memory
) external pure returns (bytes4) {
return ERC721TokenReceiver.onERC721Received.selector;
}
}
// File: contracts/MultiSigWallet.sol
pragma solidity ^0.8.0;
/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
/// @author Stefan George - <[email protected]>
contract MultiSigWallet {
/*
* Events
*/
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
/*
* Constants
*/
uint constant public MAX_OWNER_COUNT = 50;
/*
* Storage
*/
mapping(uint => Transaction) public transactions;
mapping(uint => mapping(address => bool)) public confirmations;
mapping(address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
/*
* Modifiers
*/
modifier onlyWallet() {
require(msg.sender == address(this));
_;
}
modifier ownerDoesNotExist(address owner) {
require(!isOwner[owner]);
_;
}
modifier ownerExists(address owner) {
require(isOwner[owner]);
_;
}
modifier transactionExists(uint transactionId) {
require(transactions[transactionId].destination != (address)(0));
_;
}
modifier confirmed(uint transactionId, address owner) {
require(confirmations[transactionId][owner]);
_;
}
modifier notConfirmed(uint transactionId, address owner) {
require(!confirmations[transactionId][owner]);
_;
}
modifier notExecuted(uint transactionId) {
require(!transactions[transactionId].executed);
_;
}
modifier notNull(address _address) {
require(_address != (address)(0));
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
require(ownerCount <= MAX_OWNER_COUNT
&& _required <= ownerCount
&& _required != 0
&& ownerCount != 0);
_;
}
/// @dev Fallback function allows to deposit ether.
fallback() external payable
{
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
receive() external payable
{
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor(address[] memory _owners, uint _required)
// validRequirement(_owners.length, _required)
{
required = 0;
if (_owners.length > 0 || _required > 0){
initialize(_owners, _required);
}
}
function initialize(address[] memory _owners, uint _required) internal
validRequirement(_owners.length, _required)
{
require(required == 0, "MS00");
for (uint i = 0; i < _owners.length; i++) {
require(!isOwner[_owners[i]] && _owners[i] != (address)(0));
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public virtual
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
emit OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public virtual
onlyWallet
ownerExists(owner)
{
require (owners.length > 1, "owners.length must larger than 1");
isOwner[owner] = false;
for (uint i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
owners.pop();
break;
}
// owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param newOwner Address of new owner.
function replaceOwner(address owner, address newOwner)
public virtual
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i = 0; i < owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public virtual
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId Returns transaction ID.
function submitTransaction(address destination, uint value, bytes memory data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public payable
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public payable virtual
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txn = transactions[transactionId];
txn.executed = true;
if (external_call(txn.destination, txn.value, txn.data.length, txn.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txn.executed = false;
}
}
}
// call has been separated into its own function in order to take advantage
// of the Solidity's code generator to produce a loop that copies tx.data into memory.
function external_call(address destination, uint value, uint dataLength, bytes memory data) internal returns (bool) {
//return tx.destination.call.gas(gasleft()-34710).value(tx.value)(tx.data);
bool result;
uint __gas = gasleft() - 34710;
assembly {
let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention)
let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that
// 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) +
// callNewAccountGas (25000, in case the destination address does not exist and needs creating)
result := call(
__gas,
destination,
value,
d,
dataLength, // Size of the input (in bytes) - this is what fixes the padding problem
x,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return confirmedResult Confirmation status.
function isConfirmed(uint transactionId)
public
view
returns (bool confirmedResult)
{
confirmedResult=false;
uint count = 0;
for (uint i = 0; i < owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required){
confirmedResult=true;
return confirmedResult;
}
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return transactionId Returns transaction ID.
function addTransaction(address destination, uint value, bytes memory data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination : destination,
value : value,
data : data,
executed : false
});
transactionCount += 1;
emit Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return count Number of confirmations.
function getConfirmationCount(uint transactionId)
public
view
returns (uint count)
{
for (uint i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return count Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
view
returns (uint count)
{
for (uint i = 0; i < transactionCount; i++)
if (pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
view
returns (address[] memory)
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return _confirmations Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
view
returns (address[] memory _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i = 0; i < count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return _transactionIds Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
view
returns (uint[] memory _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i = 0; i < transactionCount; i++)
if (pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i = from; i < to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
// File: contracts/MultiSigWalletWithPermit.sol
pragma solidity ^0.8.0;
/// @title MultiSigWalletWithPermit wallet with permit -
/// @author [email protected]
contract MultiSigWalletWithPermit is MultiSigWallet {
mapping(bytes4 => bool) internal supportedInterfaces;
bool internal ownersImmutable = true;
bool internal initialized = false;
modifier notImmutable() {
require(!ownersImmutable, "MS01");
_;
}
function addOwner(address owner) public override notImmutable {
super.addOwner(owner);
}
function removeOwner(address owner) public override notImmutable {
super.removeOwner(owner);
}
function replaceOwner(address owner, address newOwner)
public
override
notImmutable
{
super.replaceOwner(owner, newOwner);
}
function changeRequirement(uint256 _required) public override notImmutable {
super.changeRequirement(_required);
}
function supportsInterface(bytes4 interfaceID)
external
view
returns (bool)
{
return supportedInterfaces[interfaceID];
}
function setSupportsInterface(bytes4 interfaceID, bool support)
external
onlyWallet
{
supportedInterfaces[interfaceID] = support;
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners, required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
/// @param _immutable is owners immutable
constructor(
address[] memory _owners,
uint256 _required,
bool _immutable
) MultiSigWallet(_owners, _required) {
if (_required > 0) {
initialized = true;
setup0(_immutable);
}
}
function setup(
address[] memory _owners,
uint256 _required,
bool _immutable
) public {
require(!initialized, "MS02");
initialized = true;
super.initialize(_owners, _required);
setup0(_immutable);
}
function setup0(bool _immutable) private {
ownersImmutable = _immutable;
supportedInterfaces[0x01ffc9a7] = true;
uint256 chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256(
// "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
// ),
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
// keccak256(bytes("MultiSigWalletWithPermit")),
0x911a814036e00323c4ca54d47b0a363338990ca044824eba7a28205763e6115a,
// keccak256(bytes("1")),
0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6,
chainId,
address(this)
)
);
}
bytes32 public DOMAIN_SEPARATOR;
bytes32 public constant PERMIT_TYPEHASH =
0x8d14977a529be0cde9be2de41261d56c536e10c2bfb3f797a663ac4f3676d2fe;
/*
* executeTxWithPermits
*/
/// @dev delegate call
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @param nonce Transaction ID.
/// @return newTransactionId Returns transaction ID.
function executeTxWithPermits(
address destination,
uint256 value,
bytes memory data,
uint256 nonce,
bytes32[] memory rs,
bytes32[] memory ss,
uint8[] memory vs
) public returns (uint256 newTransactionId) {
require(isOwner[msg.sender], "MS90");
require(rs.length == ss.length, "MS91");
require(rs.length == vs.length, "MS92");
require(nonce == transactionCount, "MS93");
require(rs.length + 1 == required, "MS94");
require(destination != address(0), "MS95");
newTransactionId = addTransaction(destination, value, data);
confirmations[newTransactionId][msg.sender] = true;
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
msg.sender,
destination,
value,
keccak256(data),
nonce
)
)
)
);
for (uint8 i = 0; i < rs.length; ++i) {
address owner = ecrecover(digest, vs[i], rs[i], ss[i]);
require(owner != address(0), "MS03");
require(isOwner[owner], "MS04");
confirmations[newTransactionId][owner] = true;
}
if (isConfirmed(newTransactionId)) {
executeTransactionInner(destination, value, data, newTransactionId);
} else {
revert("MS06");
}
}
function executeTransactionInner(
address destination,
uint256 value,
bytes memory data,
uint256 transactionId
) private {
require(address(this).balance >= value, "MS07");
(bool success, bytes memory returndata) = destination.call{
value: value
}(data);
if (success) {
transactions[transactionId].executed = true;
emit Execution(transactionId);
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("MS08");
}
}
}
}
// File: contracts/ERC1155TokenReceiver.sol
pragma solidity ^0.8.0;
contract ERC1155TokenReceiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) external pure returns (bytes4) {
return ERC1155TokenReceiver.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) external pure returns (bytes4) {
return ERC1155TokenReceiver.onERC1155BatchReceived.selector;
}
}
// File: contracts/MultiSigV1.sol
pragma solidity ^0.8.0;
/// @title MultiSigV1
/// @author [email protected]
contract MultiSigV1 is
MultiSigWalletWithPermit,
ERC721TokenReceiver,
ERC1155TokenReceiver
{
constructor(address[] memory _owners, uint256 _required,
bool _immutable)
MultiSigWalletWithPermit(_owners, _required, _immutable)
{}
function eipFeatures() public pure returns (uint256[3] memory fs) {
fs = [uint256(165), uint256(721), uint256(1155)];
}
function version() public pure returns (uint256) {
return 1;
}
}
// File: contracts/UpgradeableMultiSignWalletFactory.sol
pragma solidity ^0.8.0;
contract UpgradeableMultiSignWalletFactory {
event UpgradeableMultiSignWalletDeployed(
address indexed admin,
address indexed proxy,
address indexed impl
);
function create(
address[] memory _owners,
uint256 _required,
bool _immutable,
address _impl
) public returns (address wallet) {
MultiSigWalletWithPermit proxyAdmin = new MultiSigWalletWithPermit{
salt: keccak256(
abi.encodePacked(_owners, _required, msg.sender, _immutable)
)
}(_owners, _required, true);
bytes32 newsalt = keccak256(
abi.encodePacked(_owners, _required, msg.sender)
);
TransparentUpgradeableProxy proxy = new TransparentUpgradeableProxy{
salt: newsalt
}(_impl, address(proxyAdmin), "");
setup(_owners, _required, _immutable, address(proxy));
wallet = address(proxy);
emit UpgradeableMultiSignWalletDeployed(
address(proxyAdmin),
address(proxy),
_impl
);
}
function setup(
address[] memory _owners,
uint256 _required,
bool _immutable,
address proxy
) internal {
MultiSigWalletWithPermit walletImpl = (
MultiSigWalletWithPermit(payable(proxy))
);
walletImpl.setup(_owners, _required, _immutable);
}
}
|
Web3 call functions/ Returns number of confirmations of a transaction. transactionId Transaction ID. return count Number of confirmations.
|
function getConfirmationCount(uint transactionId)
public
view
returns (uint count)
{
for (uint i = 0; i < owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
| 2,278,059
|
//Address: 0x92736b3bff1bbd72a72478d78f18a6ab9b68b791
//Contract name: SatisfactionToken
//Balance: 0 Ether
//Verification Date: 5/15/2018
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.23;
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
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;
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 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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
contract HasNoContracts is Ownable {
/**
* @dev Reclaim ownership of Ownable contracts
* @param contractAddr The address of the Ownable to be reclaimed.
*/
function reclaimContract(address contractAddr) external onlyOwner {
Ownable contractInst = Ownable(contractAddr);
contractInst.transferOwnership(owner);
}
}
contract HasNoEther is Ownable {
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
function HasNoEther() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
// solium-disable-next-line security/no-send
assert(owner.send(address(this).balance));
}
}
contract HasNoTokens is CanReclaimToken {
/**
* @dev Reject all ERC223 compatible tokens
* @param from_ address The address that is transferring the tokens
* @param value_ uint256 the amount of the specified token
* @param data_ Bytes The data passed from the caller.
*/
function tokenFallback(address from_, uint256 value_, bytes data_) external {
from_;
value_;
data_;
revert();
}
}
contract NoOwner is HasNoEther, HasNoTokens, HasNoContracts {
}
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);
}
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);
}
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
contract CheckpointStorage {
/**
* @dev `Checkpoint` is the structure that attaches a block number to a
* @dev given value, the block number attached is the one that last changed the
* @dev value
*/
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// Tracks the history of the `totalSupply` of the token
Checkpoint[] public totalSupplyHistory;
/**
* @dev `getValueAt` retrieves the number of tokens at a given block number
*
* @param checkpoints The history of values being queried
* @param _block The block number to retrieve the value at
* @return The number of tokens being queried
*/
function getValueAt(Checkpoint[] storage checkpoints, uint _block) internal view returns (uint) {
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length - 1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
/**
* @dev `updateValueAtNow` used to update the `balances` map and the
* @dev `totalSupplyHistory`
*
* @param checkpoints The history of data being updated
* @param _value The new number of tokens
*/
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
}
contract SatisfactionToken is ERC20, CheckpointStorage, NoOwner {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Mint(address indexed to, uint256 amount);
event MintFinished();
event Burn(address indexed burner, uint256 value);
using SafeMath for uint256;
string public name = "Satisfaction Token";
uint8 public decimals = 18;
string public symbol = "SAT";
string public version;
/**
* `parentToken` is the Token address that was cloned to produce this token;
* it will be 0x0 for a token that was not cloned
*/
SatisfactionToken public parentToken;
/**
* `parentSnapShotBlock` is the block number from the Parent Token that was
* used to determine the initial distribution of the Clone Token
*/
uint256 public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint256 public creationBlock;
/**
* `balances` is the map that tracks the balance of each address, in this
* contract when the balance changes the block number that the change
* occurred is also included in the map
*/
mapping(address => Checkpoint[]) internal balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping(address => mapping(address => uint256)) internal allowed;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
constructor(
address _parentToken,
uint256 _parentSnapShotBlock,
string _tokenVersion,
bool _transfersEnabled) public
{
version = _tokenVersion;
parentToken = SatisfactionToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
/**
* @dev Transfer token for a specified address
*
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(transfersEnabled);
require(parentSnapShotBlock < block.number);
require(_to != address(0));
uint256 lastBalance = balanceOfAt(msg.sender, block.number);
require(_value <= lastBalance);
return doTransfer(msg.sender, _to, _value, lastBalance);
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens to a specified
* @dev address and execute a call with the sent data on the same transaction
*
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
* @param _data ABI-encoded contract call to call `_to` address.
*
* @return true if the call function was executed successfully
*/
function transferAndCall(address _to, uint256 _value, bytes _data) public payable returns (bool) {
require(_to != address(this));
transfer(_to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
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(transfersEnabled);
require(parentSnapShotBlock < block.number);
require(_to != address(0));
require(_value <= allowed[_from][msg.sender]);
uint256 lastBalance = balanceOfAt(_from, block.number);
require(_value <= lastBalance);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
return doTransfer(_from, _to, _value, lastBalance);
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens from one address to
* @dev another and make a contract call on the same transaction
*
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amout of tokens to be transferred
* @param _data ABI-encoded contract call to call `_to` address.
*
* @return true if the call function was executed successfully
*/
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public payable returns (bool)
{
require(_to != address(this));
transferFrom(_from, _to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
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 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.
*
* @dev approve should be called when allowed[_spender] == 0. To increment
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* t@dev he first transaction is mined)
* @dev 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 Addition to StandardToken methods. Increase the amount of tokens that
* @dev an owner allowed to a spender and execute a call with the sent data.
*
* @dev approve should be called when allowed[_spender] == 0. To increment
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* @dev the first transaction is mined)
* @dev From MonolithDAO Token.sol
*
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApprovalAndCall(address _spender, uint _addedValue, bytes _data) public payable returns (bool) {
require(_spender != address(this));
increaseApproval(_spender, _addedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* @dev approve should be called when allowed[_spender] == 0. To decrement
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* @dev the first transaction is mined)
* @dev 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;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* @dev an owner allowed to a spender and execute a call with the sent data.
*
* @dev approve should be called when allowed[_spender] == 0. To decrement
* @dev allowed value is better to use this function to avoid 2 calls (and wait until
* @dev the first transaction is mined)
* @dev From MonolithDAO Token.sol
*
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApprovalAndCall(address _spender, uint _subtractedValue, bytes _data) public payable returns (bool) {
require(_spender != address(this));
decreaseApproval(_spender, _subtractedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @param _owner The address that's balance is being requested
* @return The balance of `_owner` at the current block
*/
function balanceOf(address _owner) public view returns (uint256) {
return balanceOfAt(_owner, block.number);
}
/**
* @dev Queries the balance of `_owner` at a specific `_blockNumber`
*
* @param _owner The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at `_blockNumber`
*/
function balanceOfAt(address _owner, uint256 _blockNumber) public view returns (uint256) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != address(0)) {
return parentToken.balanceOfAt(_owner, Math.min256(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/**
* @dev This function makes it easy to get the total number of tokens
*
* @return The total number of tokens
*/
function totalSupply() public view returns (uint256) {
return totalSupplyAt(block.number);
}
/**
* @dev Total amount of tokens at a specific `_blockNumber`.
*
* @param _blockNumber The block number when the totalSupply is queried
* @return The total amount of tokens at `_blockNumber`
*/
function totalSupplyAt(uint256 _blockNumber) public view returns(uint256) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != 0) {
return parentToken.totalSupplyAt(Math.min256(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
/**
* @dev Function to mint tokens
*
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) public onlyOwner canMint returns (bool) {
uint256 curTotalSupply = totalSupply();
uint256 lastBalance = balanceOf(_to);
updateValueAtNow(totalSupplyHistory, curTotalSupply.add(_amount));
updateValueAtNow(balances[_to], lastBalance.add(_amount));
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
*
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
/**
* @dev Burns a specific amount of tokens.
*
* @param _value uint256 The amount of token to be burned.
*/
function burn(uint256 _value) public {
uint256 lastBalance = balanceOf(msg.sender);
require(_value <= lastBalance);
address burner = msg.sender;
uint256 curTotalSupply = totalSupply();
updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_value));
updateValueAtNow(balances[burner], lastBalance.sub(_value));
emit Burn(burner, _value);
}
/**
* @dev Burns a specific amount of tokens from an address
*
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned.
*/
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
uint256 lastBalance = balanceOfAt(_from, block.number);
require(_value <= lastBalance);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
address burner = _from;
uint256 curTotalSupply = totalSupply();
updateValueAtNow(totalSupplyHistory, curTotalSupply.sub(_value));
updateValueAtNow(balances[burner], lastBalance.sub(_value));
emit Burn(burner, _value);
}
/**
* @dev Enables token holders to transfer their tokens freely if true
*
* @param _transfersEnabled True if transfers are allowed in the clone
*/
function enableTransfers(bool _transfersEnabled) public onlyOwner canMint {
transfersEnabled = _transfersEnabled;
}
/**
* @dev This is the actual transfer function in the token contract, it can
* @dev only be called by other functions in this contract.
*
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _value The amount of tokens to be transferred
* @param _lastBalance The last balance of from
* @return True if the transfer was successful
*/
function doTransfer(address _from, address _to, uint256 _value, uint256 _lastBalance) internal returns (bool) {
if (_value == 0) {
return true;
}
updateValueAtNow(balances[_from], _lastBalance.sub(_value));
uint256 previousBalance = balanceOfAt(_to, block.number);
updateValueAtNow(balances[_to], previousBalance.add(_value));
emit Transfer(_from, _to, _value);
return true;
}
}
|
_owner The address that's balance is being requested return The balance of `_owner` at the current block/
|
function balanceOf(address _owner) public view returns (uint256) {
return balanceOfAt(_owner, block.number);
}
| 1,027,655
|
pragma solidity ^0.4.0;
import {ScryptFramework} from "./scryptFramework.sol";
contract ScryptRunner is ScryptFramework {
function initMemory(State memory state) pure internal {
state.fullMemory = new uint[](4 * 1024);
}
function run(bytes input, uint upToStep) pure public returns (uint[4] vars, bytes32 memoryHash, bytes32[] proof, bytes output) {
State memory s = inputToState(input);
Proofs memory proofs;
if (upToStep > 0) {
uint internalStep = upToStep - 1;
for (uint i = 0; i < internalStep; i++) {
runStep(s, i, proofs);
}
proofs.generateProofs = true;
if (internalStep < 2048) {
runStep(s, internalStep, proofs);
} else {
output = finalStateToOutput(s);
}
}
return (s.vars, s.memoryHash, proofs.proof, output);
}
// The proof for reading memory consists of a list of proof from
// leaf to root plus the four values read from memory.
function readMemory(State memory state, uint index, Proofs memory proofs) pure internal returns (uint a, uint b, uint c, uint d) {
require(index < 1024);
uint pos = 0x20 * 4 * index;
uint[] memory fullMem = state.fullMemory;
assembly {
pos := add(pos, 0x20)
a := mload(add(fullMem, pos))
pos := add(pos, 0x20)
b := mload(add(fullMem, pos))
pos := add(pos, 0x20)
c := mload(add(fullMem, pos))
pos := add(pos, 0x20)
d := mload(add(fullMem, pos))
}
if (proofs.generateProofs) {
bytes32[] memory proof;
(proof, state.memoryHash) = generateMemoryProof(state.fullMemory, index);
proofs.proof = new bytes32[](proof.length + 4);
for (uint i = 0; i < proof.length; i++)
proofs.proof[i] = proof[i];
proofs.proof[proof.length + 0] = bytes32(a);
proofs.proof[proof.length + 1] = bytes32(b);
proofs.proof[proof.length + 2] = bytes32(c);
proofs.proof[proof.length + 3] = bytes32(d);
}
}
// The proof for writing to memory consists of a list of proof
// from leaf to root.
function writeMemory(State memory state, uint index, uint[4] values, Proofs memory proofs) pure internal {
require(index < 1024);
uint pos = 0x20 * 4 * index;
uint[] memory fullMem = state.fullMemory;
uint[4] memory oldValues;
if (proofs.generateProofs) {
oldValues[0] = fullMem[4 * index + 0];
oldValues[1] = fullMem[4 * index + 1];
oldValues[2] = fullMem[4 * index + 2];
oldValues[3] = fullMem[4 * index + 3];
}
var (a, b, c, d) = (values[0], values[1], values[2], values[3]);
assembly {
pos := add(pos, 0x20)
mstore(add(fullMem, pos), a)
pos := add(pos, 0x20)
mstore(add(fullMem, pos), b)
pos := add(pos, 0x20)
mstore(add(fullMem, pos), c)
pos := add(pos, 0x20)
mstore(add(fullMem, pos), d)
}
if (proofs.generateProofs) {
(proofs.proof, state.memoryHash) = generateMemoryProof(state.fullMemory, index);
// We need the values before we write - the siblings will still be the same.
proofs.proof[0] = bytes32(oldValues[0]);
proofs.proof[1] = bytes32(oldValues[1]);
proofs.proof[2] = bytes32(oldValues[2]);
proofs.proof[3] = bytes32(oldValues[3]);
}
}
// Generate a proof that shows that the memory root hash was updated correctly.
// Returns the value stored at the index (4 array elemets) followed by
// a list of siblings (from leaf to root) and the new root hash.
// This assumes that index is multiplied by four.
// Since we know that memory is only written in sequence, this might be
// optimized, but we keep it general for now.
function generateMemoryProof(uint[] fullMem, uint index) internal pure returns (bytes32[] proof, bytes32) {
uint access = index;
proof = new bytes32[](14);
proof[0] = bytes32(fullMem[4 * i]);
proof[1] = bytes32(fullMem[4 * i + 1]);
proof[2] = bytes32(fullMem[4 * i + 2]);
proof[3] = bytes32(fullMem[4 * i + 3]);
bytes32[] memory hashes = new bytes32[](1024);
for (uint i = 0; i < 1024; i++)
hashes[i] = keccak256(proof[0], proof[1], proof[2], proof[3]);
uint numHashes = 1024;
for (uint step = 4; step < proof.length; step++) {
proof[step] = hashes[access ^ 1];
access /= 2;
numHashes /= 2;
for (i = 0; i < numHashes; i++) {
hashes[i] = keccak256(hashes[2 * i], hashes[2 * i + 1]);
}
}
assert(numHashes == 1);
return (proof, hashes[0]);
}
}
|
The proof for reading memory consists of a list of proof from leaf to root plus the four values read from memory.
|
function readMemory(State memory state, uint index, Proofs memory proofs) pure internal returns (uint a, uint b, uint c, uint d) {
require(index < 1024);
uint pos = 0x20 * 4 * index;
uint[] memory fullMem = state.fullMemory;
assembly {
pos := add(pos, 0x20)
a := mload(add(fullMem, pos))
pos := add(pos, 0x20)
b := mload(add(fullMem, pos))
pos := add(pos, 0x20)
c := mload(add(fullMem, pos))
pos := add(pos, 0x20)
d := mload(add(fullMem, pos))
}
if (proofs.generateProofs) {
bytes32[] memory proof;
(proof, state.memoryHash) = generateMemoryProof(state.fullMemory, index);
proofs.proof = new bytes32[](proof.length + 4);
for (uint i = 0; i < proof.length; i++)
proofs.proof[i] = proof[i];
proofs.proof[proof.length + 0] = bytes32(a);
proofs.proof[proof.length + 1] = bytes32(b);
proofs.proof[proof.length + 2] = bytes32(c);
proofs.proof[proof.length + 3] = bytes32(d);
}
}
| 12,703,872
|
/**
* Lucky Block Network Project Smart-Contracts
* @authors https://grox.solutions
*/
pragma solidity 0.5.7;
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
contract MultiOwnable {
mapping (address => bool) _owner;
modifier onlyOwner() {
require(isOwner(msg.sender));
_;
}
function isOwner(address addr) public view returns (bool) {
return _owner[addr];
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-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);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* See https://eips.ethereum.org/EIPS/eip-20
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
function paused() public view returns (bool) {
return _paused;
}
modifier whenNotPaused() {
require(!_paused);
_;
}
modifier whenPaused() {
require(_paused);
_;
}
function pause() public whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
function unpause() public whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, 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 increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
/**
* @title ApproveAndCall Interface.
* @dev ApproveAndCall system hepls to communicate with smart-contracts.
*/
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 amount, address token, bytes calldata extraData) external;
}
/**
* @title The main project contract.
* @author https://grox.solutions
*/
contract LBNToken is ERC20Pausable, MultiOwnable {
// name of the token
string private _name = "Lucky Block Network";
// symbol of the token
string private _symbol = "LBN";
// decimals of the token
uint8 private _decimals = 18;
// initial supply
uint256 public constant INITIAL_SUPPLY = 99990000 * (10 ** 18);
// an amount of votes required to process an action
uint8 public consensusValue = 1;
// struct for proposals
struct Proposal {
// amount of votes
uint8 votes;
// count of proposals
uint256 count;
// double mapping to prevent the error of repeating the same proposal
mapping (uint256 => mapping (address => bool)) voted;
}
// mapping to implement muptiple owners
mapping (address => bool) _owner;
// boolean value if minting is finished of not
bool public mintingIsFinished;
/**
* @dev Throws if called while minting is finished.
*/
modifier isNotFinished {
require(!mintingIsFinished);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(msg.sender));
_;
}
// events
event LogProposal(string indexed method, address param1, address param2, uint256 param3, string param4, address indexed voter, uint8 votes, uint8 consensusValue);
event LogAction(string indexed method, address param1, address param2, uint256 param3, string param4);
/**
* @dev constructor function that is called once at deployment of the contract.
* @param owners 5 initial owners to set.
* @param recipient Address to receive initial supply.
*/
constructor(address[] memory owners, address recipient) public {
for (uint8 i = 0; i < 5; i++) {
_owner[owners[i]] = true;
}
_mint(recipient, INITIAL_SUPPLY);
}
/**
* @dev Internal function that process voting in a given proposal, returns `true` if the voting has succesfully ended.
* @param props The proposal storage.
* @notice Every next parameter is given only to emit events.
* @param method Name of the called method.
* @param param1 First address parameter.
* @param param2 Second address parameter.
* @param param3 uint256 parameter.
* @param param4 string parameter.
*/
function _vote(Proposal storage props, string memory method, address param1, address param2, uint256 param3, string memory param4) internal returns(bool) {
// if that is the new proposal add a number to count to prevent the error of repeating the same proposal
if (props.votes == 0) {
props.count++;
}
// if msg.sender hasn't voted yet, do this
if (!props.voted[props.count][msg.sender]) {
props.votes++;
props.voted[props.count][msg.sender] = true;
emit LogProposal(method, param1, param2, param3, param4, msg.sender, props.votes, consensusValue);
}
// if an amount of votes is equal or more than consensusValue renew the proposal and return `true` to process the action
if (props.votes >= consensusValue) {
props.votes = 0;
emit LogAction(method, param1, param2, param3, param4);
return true;
}
}
/**
* @dev Storage for owner proposals.
*/
mapping (address => mapping(address => Proposal)) public ownerProp;
/**
* @dev Vote to transfer control of the contract from one account to another.
* @param previousOwner The address to remove ownership from.
* @param newOwner The address to transfer ownership to.
* @notice There are only 5 owners of this contract
*/
function changeOwner(address previousOwner, address newOwner) public onlyOwner {
require(isOwner(previousOwner) && !isOwner(newOwner));
if (_vote(ownerProp[previousOwner][newOwner], "changeOwner", previousOwner, newOwner, 0, "")) {
_owner[previousOwner] = false;
_owner[newOwner] = true;
}
}
/**
* @dev Storage for consensus proposals.
*/
mapping (uint8 => Proposal) public consProp;
/**
* @dev Vote to change the consensusValue.
* @param newConsensusValue new value.
*/
function setConsensusValue(uint8 newConsensusValue) public onlyOwner {
if (_vote(consProp[newConsensusValue], "setConsensusValue", address(0), address(0), newConsensusValue, "")) {
consensusValue = newConsensusValue;
}
}
/**
* @dev Storage for minting finalize proposal.
*/
Proposal public finMintProp;
/**
* @dev Vote to stop minting of tokens forever.
*/
function finalizeMinting() public onlyOwner {
if (_vote(finMintProp, "finalizeMinting", address(0), address(0), 0, "")) {
mintingIsFinished = true;
}
}
/**
* @dev Storage for mint proposals.
*/
mapping (address => mapping (uint256 => mapping (string => Proposal))) public mintProp;
/**
* @dev Vote to mint an amount of the token and assigns it to
* an account.
* @param to The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function mint(address to, uint256 value) public isNotFinished onlyOwner returns (bool) {
if (_vote(mintProp[to][value]["mint"], "mint", to, address(0), value, "")) {
_mint(to, value);
}
}
/**
* @dev Storage for burn proposals.
*/
mapping (address => mapping (uint256 => mapping (string => Proposal))) public burnProp;
/**
* @dev Vote to burn an amount of the token of a given
* account.
* @param from The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function burnFrom(address from, uint256 value) public onlyOwner {
if (_vote(burnProp[from][value]["burnFrom"], "burnFrom", from, address(0), value, "")) {
_burn(from, value);
}
}
/**
* @dev Storage for pause proposals.
*/
Proposal public pauseProp;
/**
* @dev Vote to pause any transfer of tokens.
* Called by a owner to pause, triggers stopped state.
*/
function pause() public onlyOwner {
if (_vote(pauseProp, "pause", address(0), address(0), 0, "")) {
super.pause();
}
}
/**
* @dev Storage for unpause proposals.
*/
Proposal public unpauseProp;
/**
* @dev Vote to pause any transfer of tokens.
* Called by a owner to unpause, triggers normal state.
*/
function unpause() public onlyOwner {
if (_vote(unpauseProp, "unpause", address(0), address(0), 0, "")) {
super.unpause();
}
}
/**
* @dev Storage for name proposals.
*/
mapping (string => mapping (string => Proposal)) public nameProp;
/**
* @dev Change the name of the token.
* @param newName New name of the token.
*/
function changeName(string memory newName) public onlyOwner {
if (_vote(nameProp[newName]["name"], "changeName", address(0), address(0), 0, newName)) {
_name = newName;
}
}
/**
* @dev Storage for symbol proposals.
*/
mapping (string => mapping (string => Proposal)) public symbolProp;
/**
* @dev Change the symbol of the token.
* @param newSymbol New symbol of the token.
*/
function changeSymbol(string memory newSymbol) public onlyOwner {
if (_vote(symbolProp[newSymbol]["symbol"], "changeSymbol", address(0), address(0), 0, newSymbol)) {
_symbol = newSymbol;
}
}
/**
* @dev Allows to send tokens (via Approve and TransferFrom) to other smart contract.
* @param spender Address of smart contracts to work with.
* @param amount Amount of tokens to send.
* @param extraData Any extra data.
*/
function approveAndCall(address spender, uint256 amount, bytes calldata extraData) external returns (bool) {
require(approve(spender, amount));
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, amount, address(this), extraData);
return true;
}
/**
* @dev Allows to any owner of the contract withdraw needed ERC20 token from this contract (promo or bounties for example).
* @param ERC20Token Address of ERC20 token.
* @param recipient Account to receive tokens.
*/
function withdrawERC20(address ERC20Token, address recipient) external onlyOwner {
uint256 amount = IERC20(ERC20Token).balanceOf(address(this));
IERC20(ERC20Token).transfer(recipient, amount);
}
/**
* @return true if `addr` is the owner of the contract.
*/
function isOwner(address addr) public view returns (bool) {
return _owner[addr];
}
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
|
Vote to pause any transfer of tokens. Called by a owner to unpause, triggers normal state./
|
function unpause() public onlyOwner {
if (_vote(unpauseProp, "unpause", address(0), address(0), 0, "")) {
super.unpause();
}
}
| 922,399
|
./full_match/80001/0x8794b656d34B4895a16823fF0943d4942d9FBC59/sources/contracts/NFTAttack2.sol
|
Internal function to perform a defense defender The defender's address attacker The attacker's address/ Only a grumpy cat owner can defend Find the highest-level cat owned by the defender
|
function _defend(address defender, address attacker) internal {
require(balanceOf[defender][1] > 0, "You need a Grumpy cat to defend!");
uint256 highestLevelCat;
for (uint256 i = 2; i >= 0; i--) {
if (balanceOf[defender][i] > 0) {
highestLevelCat = i;
break;
}
}
emit Smashed(defender, attacker, highestLevelCat + 1);
}
| 851,148
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {
ReentrancyGuardUpgradeable
} from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import {
OwnableUpgradeable
} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {
ERC20Upgradeable
} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {Vault} from "../../libraries/Vault.sol";
import {
VaultLifecycleTreasury
} from "../../libraries/VaultLifecycleTreasury.sol";
import {
RibbonTreasuryVaultStorage
} from "../../storage/RibbonTreasuryVaultStorage.sol";
import {ShareMath} from "../../libraries/ShareMath.sol";
import {IWETH} from "../../interfaces/IWETH.sol";
import {GnosisAuction} from "../../libraries/GnosisAuction.sol";
import {IERC20Detailed} from "../../interfaces/IERC20Detailed.sol";
contract RibbonTreasuryVault is
ReentrancyGuardUpgradeable,
OwnableUpgradeable,
ERC20Upgradeable,
RibbonTreasuryVaultStorage
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
using ShareMath for Vault.DepositReceipt;
/************************************************
* IMMUTABLES & CONSTANTS
***********************************************/
/// @notice WETH9 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2
address public immutable WETH;
/// @notice USDC 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48
address public immutable USDC;
/// @notice 15 minute timelock between commitAndClose and rollToNexOption.
uint256 public constant DELAY = 0;
// Number of weeks per year = 52.142857 weeks * FEE_MULTIPLIER = 52142857
// Dividing by weeks per year requires doing num.mul(FEE_MULTIPLIER).div(WEEKS_PER_YEAR)
uint256 private constant WEEKS_PER_YEAR = 52142857;
// GAMMA_CONTROLLER is the top-level contract in Gamma protocol
// which allows users to perform multiple actions on their vaults
// and positions https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/Controller.sol
address public immutable GAMMA_CONTROLLER;
// MARGIN_POOL is Gamma protocol's collateral pool.
// Needed to approve collateral.safeTransferFrom for minting otokens.
// https://github.com/opynfinance/GammaProtocol/blob/master/contracts/core/MarginPool.sol
address public immutable MARGIN_POOL;
// GNOSIS_EASY_AUCTION is Gnosis protocol's contract for initiating auctions and placing bids
// https://github.com/gnosis/ido-contracts/blob/main/contracts/EasyAuction.sol
address public immutable GNOSIS_EASY_AUCTION;
/// OTOKEN_FACTORY is the factory contract used to spawn otokens. Used to lookup otokens.
address public immutable OTOKEN_FACTORY;
// The minimum duration for an option auction.
uint256 private constant MIN_AUCTION_DURATION = 5 minutes;
// The minimum amount above which premium distribution will occur during commitAndClose
uint256 private constant MIN_DUST_AMOUNT = 10000000;
/************************************************
* EVENTS
***********************************************/
event Deposit(address indexed account, uint256 amount, uint256 round);
event InitiateWithdraw(
address indexed account,
uint256 shares,
uint256 round
);
event Redeem(address indexed account, uint256 share, uint256 round);
event ManagementFeeSet(uint256 managementFee, uint256 newManagementFee);
event PerformanceFeeSet(uint256 performanceFee, uint256 newPerformanceFee);
event CapSet(uint256 oldCap, uint256 newCap);
event Withdraw(address indexed account, uint256 amount, uint256 shares);
event CollectManagementFee(
uint256 managementFee,
uint256 round,
address indexed feeRecipient
);
event CollectPerformanceFee(
uint256 performanceFee,
uint256 round,
address indexed feeRecipient
);
event DistributePremium(
uint256 amount,
uint256[] amounts,
address[] recipients,
uint256 round
);
event OpenShort(
address indexed options,
uint256 depositAmount,
address indexed manager
);
event CloseShort(
address indexed options,
uint256 withdrawAmount,
address indexed manager
);
event NewOptionStrikeSelected(uint256 strikePrice, uint256 delta);
event PremiumDiscountSet(
uint256 premiumDiscount,
uint256 newPremiumDiscount
);
event AuctionDurationSet(
uint256 auctionDuration,
uint256 newAuctionDuration
);
event InstantWithdraw(
address indexed account,
uint256 amount,
uint256 round
);
event InitiateGnosisAuction(
address indexed auctioningToken,
address indexed biddingToken,
uint256 auctionCounter,
address indexed manager
);
/************************************************
* CONSTRUCTOR & INITIALIZATION
***********************************************/
/**
* @notice Initializes the contract with immutable variables
* @param _weth is the Wrapped Ether contract
* @param _usdc is the USDC contract
* @param _oTokenFactory is the contract address for minting new opyn option types (strikes, asset, expiry)
* @param _gammaController is the contract address for opyn actions
* @param _marginPool is the contract address for providing collateral to opyn
* @param _gnosisEasyAuction is the contract address that facilitates gnosis auctions
*/
constructor(
address _weth,
address _usdc,
address _oTokenFactory,
address _gammaController,
address _marginPool,
address _gnosisEasyAuction
) {
require(_weth != address(0), "!_weth");
require(_usdc != address(0), "!_usdc");
require(_oTokenFactory != address(0), "!_oTokenFactory");
require(_gammaController != address(0), "!_gammaController");
require(_marginPool != address(0), "!_marginPool");
require(_gnosisEasyAuction != address(0), "!_gnosisEasyAuction");
WETH = _weth;
USDC = _usdc;
OTOKEN_FACTORY = _oTokenFactory;
GAMMA_CONTROLLER = _gammaController;
MARGIN_POOL = _marginPool;
GNOSIS_EASY_AUCTION = _gnosisEasyAuction;
}
/**
* @notice Initializes the OptionVault contract with storage variables.
*/
function initialize(
VaultLifecycleTreasury.InitParams calldata _initParams,
Vault.VaultParams calldata _vaultParams
) external initializer {
VaultLifecycleTreasury.verifyInitializerParams(
_initParams,
_vaultParams,
MIN_AUCTION_DURATION
);
__ReentrancyGuard_init();
__ERC20_init(_initParams._tokenName, _initParams._tokenSymbol);
__Ownable_init();
transferOwnership(_initParams._owner);
keeper = _initParams._keeper;
period = _initParams._period;
optionsPremiumPricer = _initParams._optionsPremiumPricer;
strikeSelection = _initParams._strikeSelection;
premiumDiscount = _initParams._premiumDiscount;
auctionDuration = _initParams._auctionDuration;
feeRecipient = _initParams._feeRecipient;
performanceFee = _initParams._performanceFee;
managementFee = _perRoundManagementFee(_initParams._managementFee);
maxDepositors = _initParams._maxDepositors;
minDeposit = _initParams._minDeposit;
vaultParams = _vaultParams;
vaultState.round = 1;
uint256 assetBalance =
IERC20(vaultParams.asset).balanceOf(address(this));
ShareMath.assertUint104(assetBalance);
vaultState.lastLockedAmount = uint104(assetBalance);
}
/**
* @dev Throws if called by any account other than the keeper.
*/
modifier onlyKeeper() {
require(msg.sender == keeper, "!keeper");
_;
}
/************************************************
* SETTERS
***********************************************/
/**
* @notice Sets the new keeper
* @param newKeeper is the address of the new keeper
*/
function setNewKeeper(address newKeeper) external onlyOwner {
require(newKeeper != address(0), "!newKeeper");
keeper = newKeeper;
}
/**
* @notice Sets the new fee recipient
* @param newFeeRecipient is the address of the new fee recipient
*/
function setFeeRecipient(address newFeeRecipient) external onlyOwner {
require(newFeeRecipient != address(0), "!newFeeRecipient");
require(newFeeRecipient != feeRecipient, "Must be new feeRecipient");
feeRecipient = newFeeRecipient;
}
/**
* @notice Sets the management fee for the vault
* @param newManagementFee is the management fee (6 decimals). ex: 2 * 10 ** 6 = 2%
*/
function setManagementFee(uint256 newManagementFee) external onlyOwner {
require(
newManagementFee < 100 * Vault.FEE_MULTIPLIER,
"Invalid management fee"
);
managementFee = _perRoundManagementFee(newManagementFee);
emit ManagementFeeSet(managementFee, newManagementFee);
}
/**
* @notice Internal function to set the management fee for the vault
* @param managementFee is the management fee (6 decimals). ex: 2 * 10 ** 6 = 2
* @return perRoundManagementFee is the management divided by the number of rounds per year
*/
function _perRoundManagementFee(uint256 managementFee)
internal
view
returns (uint256)
{
uint256 _period = period;
uint256 feeDivider =
_period % 30 == 0
? Vault.FEE_MULTIPLIER * (12 / (_period / 30))
: WEEKS_PER_YEAR / (_period / 7);
// We are dividing annualized management fee by num weeks in a year
return managementFee.mul(Vault.FEE_MULTIPLIER).div(feeDivider);
}
/**
* @notice Sets the performance fee for the vault
* @param newPerformanceFee is the performance fee (6 decimals). ex: 20 * 10 ** 6 = 20%
*/
function setPerformanceFee(uint256 newPerformanceFee) external onlyOwner {
require(
newPerformanceFee < 100 * Vault.FEE_MULTIPLIER,
"Invalid performance fee"
);
emit PerformanceFeeSet(performanceFee, newPerformanceFee);
performanceFee = newPerformanceFee;
}
/**
* @notice Sets a new cap for deposits
* @param newCap is the new cap for deposits
*/
function setCap(uint256 newCap) external onlyOwner {
require(newCap > 0, "!newCap");
ShareMath.assertUint104(newCap);
emit CapSet(vaultParams.cap, newCap);
vaultParams.cap = uint104(newCap);
}
/**
* @notice Sets the new discount on premiums for options we are selling
* @param newPremiumDiscount is the premium discount
*/
function setPremiumDiscount(uint256 newPremiumDiscount) external onlyOwner {
require(
newPremiumDiscount > 0 &&
newPremiumDiscount < 100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER,
"Invalid discount"
);
emit PremiumDiscountSet(premiumDiscount, newPremiumDiscount);
premiumDiscount = newPremiumDiscount;
}
/**
* @notice Sets the new auction duration
* @param newAuctionDuration is the auction duration
*/
function setAuctionDuration(uint256 newAuctionDuration) external onlyOwner {
require(
newAuctionDuration >= MIN_AUCTION_DURATION,
"Invalid auction duration"
);
emit AuctionDurationSet(auctionDuration, newAuctionDuration);
auctionDuration = newAuctionDuration;
}
/**
* @notice Sets the new strike selection contract
* @param newStrikeSelection is the address of the new strike selection contract
*/
function setStrikeSelection(address newStrikeSelection) external onlyOwner {
require(newStrikeSelection != address(0), "!newStrikeSelection");
strikeSelection = newStrikeSelection;
}
/**
* @notice Sets the new options premium pricer contract
* @param newOptionsPremiumPricer is the address of the new strike selection contract
*/
function setOptionsPremiumPricer(address newOptionsPremiumPricer)
external
onlyOwner
{
require(
newOptionsPremiumPricer != address(0),
"!newOptionsPremiumPricer"
);
optionsPremiumPricer = newOptionsPremiumPricer;
}
/**
* @notice Optionality to set strike price manually
* @param strikePrice is the strike price of the new oTokens (decimals = 8)
*/
function setStrikePrice(uint128 strikePrice)
external
onlyOwner
nonReentrant
{
require(strikePrice > 0, "!strikePrice");
overriddenStrikePrice = strikePrice;
lastStrikeOverrideRound = vaultState.round;
}
/**
* @notice Set the maximum number of depositors
* @param newMaxDepositors is the new cap for number of depositors
*/
function setMaxDepositors(uint256 newMaxDepositors)
external
onlyOwner
nonReentrant
{
require(newMaxDepositors > 0, "!newMaxDepositors");
maxDepositors = newMaxDepositors;
}
/**
* @notice Set the minimum deposit amount
* @param newMinDeposit is the new minimum amount for deposit
*/
function setMinDeposit(uint256 newMinDeposit)
external
onlyOwner
nonReentrant
{
require(newMinDeposit > 0, "!newMinDeposit");
minDeposit = newMinDeposit;
}
/************************************************
* DEPOSIT & WITHDRAWALS
***********************************************/
/**
* @notice Internal function to add new depositor address
* @param newDepositor is the address to include in the depositors list
*/
function _addDepositor(address newDepositor) internal {
if (!depositorsMap[newDepositor]) {
require(newDepositor != address(0), "Depositor address null");
require(
(depositorsArray.length + 1) <= maxDepositors,
"Number of depositors exceeds limit"
);
depositorsMap[newDepositor] = true;
depositorsArray.push(newDepositor);
}
}
/**
* @notice Remove addresses from depositors list
* @param excludeDepositor is the address to exclude from the depositors list
*/
function _removeDepositor(address excludeDepositor) internal {
address[] storage array = depositorsArray;
uint256 arrayLength = array.length;
require(depositorsMap[excludeDepositor], "Depositor does not exist");
depositorsMap[excludeDepositor] = false;
for (uint256 i = 0; i < arrayLength - 1; i++) {
if (excludeDepositor == array[i]) {
(array[i], array[arrayLength - 1]) = (
array[arrayLength - 1],
array[i]
);
}
}
array.pop();
}
/**
* @notice Deposits the `asset` from msg.sender.
* @param amount is the amount of `asset` to deposit
*/
function deposit(uint256 amount) external nonReentrant {
require(amount > 0, "!amount");
_addDepositor(msg.sender);
_depositFor(amount, msg.sender);
// An approve() by the msg.sender is required beforehand
IERC20(vaultParams.asset).safeTransferFrom(
msg.sender,
address(this),
amount
);
}
/**
* @notice Mints the vault shares to the creditor
* @param amount is the amount of `asset` deposited
* @param creditor is the address to receieve the deposit
*/
function _depositFor(uint256 amount, address creditor) private {
uint256 currentRound = vaultState.round;
uint256 totalWithDepositedAmount = totalBalance().add(amount);
Vault.DepositReceipt memory depositReceipt = depositReceipts[creditor];
uint256 totalUserDeposit =
accountVaultBalance(msg.sender).add(depositReceipt.amount).add(
amount
);
require(totalWithDepositedAmount <= vaultParams.cap, "Exceed cap");
require(
totalWithDepositedAmount >= vaultParams.minimumSupply,
"Insufficient balance"
);
require(totalUserDeposit >= minDeposit, "Minimum deposit not reached");
emit Deposit(creditor, amount, currentRound);
// If we have an unprocessed pending deposit from the previous rounds, we have to process it.
uint256 unredeemedShares =
depositReceipt.getSharesFromReceipt(
currentRound,
roundPricePerShare[depositReceipt.round],
vaultParams.decimals
);
uint256 depositAmount = amount;
// If we have a pending deposit in the current round, we add on to the pending deposit
if (currentRound == depositReceipt.round) {
uint256 newAmount = uint256(depositReceipt.amount).add(amount);
depositAmount = newAmount;
}
ShareMath.assertUint104(depositAmount);
depositReceipts[creditor] = Vault.DepositReceipt({
round: uint16(currentRound),
amount: uint104(depositAmount),
unredeemedShares: uint128(unredeemedShares)
});
uint256 newTotalPending = uint256(vaultState.totalPending).add(amount);
ShareMath.assertUint128(newTotalPending);
vaultState.totalPending = uint128(newTotalPending);
}
/**
* @notice Initiates a withdrawal that can be processed once the round completes
* @param numShares is the number of shares to withdraw
*/
function initiateWithdraw(uint256 numShares) external nonReentrant {
require(numShares > 0, "!numShares");
// We do a max redeem before initiating a withdrawal
// But we check if they must first have unredeemed shares
Vault.DepositReceipt storage depositReceipt =
depositReceipts[msg.sender];
if (depositReceipt.amount > 0 || depositReceipt.unredeemedShares > 0) {
_redeem(0, true);
}
// This caches the `round` variable used in shareBalances
uint256 currentRound = vaultState.round;
Vault.Withdrawal storage withdrawal = withdrawals[msg.sender];
uint256 withdrawalRound = withdrawal.round;
bool withdrawalIsSameRound = withdrawalRound == currentRound;
emit InitiateWithdraw(msg.sender, numShares, currentRound);
uint256 existingShares = uint256(withdrawal.shares);
uint256 withdrawalShares;
if (withdrawalIsSameRound) {
withdrawalShares = existingShares.add(numShares);
} else {
require(existingShares == 0, "Existing withdraw");
withdrawalShares = numShares;
withdrawals[msg.sender].round = uint16(currentRound);
}
// Ensure withdrawal does not reduce user deposit below the minimum amount
uint256 vaultDecimals = vaultParams.decimals;
uint256 userBalance = accountVaultBalance(msg.sender);
uint256 withdrawAmount =
ShareMath.sharesToAsset(
numShares,
currentRound != 1
? roundPricePerShare[currentRound - 1]
: 10**vaultDecimals,
vaultDecimals
);
if (userBalance > withdrawAmount) {
uint256 totalDeposit = userBalance.sub(withdrawAmount);
require(totalDeposit >= minDeposit, "Minimum deposit not reached");
}
ShareMath.assertUint128(withdrawalShares);
withdrawals[msg.sender].shares = uint128(withdrawalShares);
uint256 newQueuedWithdrawShares =
uint256(vaultState.queuedWithdrawShares).add(numShares);
ShareMath.assertUint128(newQueuedWithdrawShares);
vaultState.queuedWithdrawShares = uint128(newQueuedWithdrawShares);
if (depositReceipt.amount == 0 && balanceOf(msg.sender) == numShares) {
_removeDepositor(msg.sender);
}
_transfer(msg.sender, address(this), numShares);
}
/**
* @notice Completes a scheduled withdrawal from a past round. Uses finalized pps for the round
* @return withdrawAmount the current withdrawal amount
*/
function _completeWithdraw() internal returns (uint256) {
Vault.Withdrawal storage withdrawal = withdrawals[msg.sender];
uint256 withdrawalShares = withdrawal.shares;
uint256 withdrawalRound = withdrawal.round;
// This checks if there is a withdrawal
require(withdrawalShares > 0, "Not initiated");
require(withdrawalRound < vaultState.round, "Round not closed");
// We leave the round number as non-zero to save on gas for subsequent writes
withdrawals[msg.sender].shares = 0;
vaultState.queuedWithdrawShares = uint128(
uint256(vaultState.queuedWithdrawShares).sub(withdrawalShares)
);
uint256 withdrawAmount =
ShareMath.sharesToAsset(
withdrawalShares,
roundPricePerShare[withdrawalRound],
vaultParams.decimals
);
emit Withdraw(msg.sender, withdrawAmount, withdrawalShares);
_burn(address(this), withdrawalShares);
require(withdrawAmount > 0, "!withdrawAmount");
transferAsset(msg.sender, withdrawAmount);
return withdrawAmount;
}
/**
* @notice Redeems shares that are owed to the account
* @param numShares is the number of shares to redeem
*/
function redeem(uint256 numShares) external nonReentrant {
require(numShares > 0, "!numShares");
_redeem(numShares, false);
}
/**
* @notice Redeems the entire unredeemedShares balance that is owed to the account
*/
function maxRedeem() external nonReentrant {
_redeem(0, true);
}
/**
* @notice Redeems shares that are owed to the account
* @param numShares is the number of shares to redeem, could be 0 when isMax=true
* @param isMax is flag for when callers do a max redemption
*/
function _redeem(uint256 numShares, bool isMax) internal {
Vault.DepositReceipt memory depositReceipt =
depositReceipts[msg.sender];
// This handles the null case when depositReceipt.round = 0
// Because we start with round = 1 at `initialize`
uint256 currentRound = vaultState.round;
uint256 unredeemedShares =
depositReceipt.getSharesFromReceipt(
currentRound,
roundPricePerShare[depositReceipt.round],
vaultParams.decimals
);
numShares = isMax ? unredeemedShares : numShares;
if (numShares == 0) {
return;
}
require(numShares <= unredeemedShares, "Exceeds available");
// If we have a depositReceipt on the same round, BUT we have some unredeemed shares
// we debit from the unredeemedShares, but leave the amount field intact
// If the round has past, with no new deposits, we just zero it out for new deposits.
if (depositReceipt.round < currentRound) {
depositReceipts[msg.sender].amount = 0;
}
ShareMath.assertUint128(numShares);
depositReceipts[msg.sender].unredeemedShares = uint128(
unredeemedShares.sub(numShares)
);
emit Redeem(msg.sender, numShares, depositReceipt.round);
_transfer(address(this), msg.sender, numShares);
}
/**
* @notice Withdraws the assets on the vault using the outstanding `DepositReceipt.amount`
* @param amount is the amount to withdraw
*/
function withdrawInstantly(uint256 amount) external nonReentrant {
Vault.DepositReceipt storage depositReceipt =
depositReceipts[msg.sender];
uint256 currentRound = vaultState.round;
require(amount > 0, "!amount");
require(depositReceipt.round == currentRound, "Invalid round");
uint256 receiptAmount = depositReceipt.amount;
require(receiptAmount >= amount, "Exceed amount");
uint256 userBalance =
accountVaultBalance(msg.sender).add(receiptAmount);
if (userBalance > amount) {
uint256 totalUserDeposit = userBalance.sub(amount);
require(
totalUserDeposit >= minDeposit,
"Minimum deposit not reached"
);
}
// Subtraction underflow checks already ensure it is smaller than uint104
depositReceipt.amount = uint104(receiptAmount.sub(amount));
vaultState.totalPending = uint128(
uint256(vaultState.totalPending).sub(amount)
);
emit InstantWithdraw(msg.sender, amount, currentRound);
if (depositReceipt.amount == 0 && shares(msg.sender) == 0) {
_removeDepositor(msg.sender);
}
transferAsset(msg.sender, amount);
}
/**
* @notice Completes a scheduled withdrawal from a past round. Uses finalized pps for the round
*/
function completeWithdraw() external nonReentrant {
uint256 withdrawAmount = _completeWithdraw();
lastQueuedWithdrawAmount = uint128(
uint256(lastQueuedWithdrawAmount).sub(withdrawAmount)
);
}
/************************************************
* VAULT OPERATIONS
***********************************************/
/*
* @notice Helper function that helps to save gas for writing values into the roundPricePerShare map.
* Writing `1` into the map makes subsequent writes warm, reducing the gas from 20k to 5k.
* Having 1 initialized beforehand will not be an issue as long as we round down share calculations to 0.
* @param numRounds is the number of rounds to initialize in the map
*/
function initRounds(uint256 numRounds) external nonReentrant {
require(numRounds > 0, "!numRounds");
uint256 _round = vaultState.round;
for (uint256 i = 0; i < numRounds; i++) {
uint256 index = _round + i;
require(roundPricePerShare[index] == 0, "Initialized"); // AVOID OVERWRITING ACTUAL VALUES
roundPricePerShare[index] = ShareMath.PLACEHOLDER_UINT;
}
}
/*
* @notice Helper function that performs most administrative tasks
* such as setting next option, minting new shares, getting vault fees, etc.
* @param lastQueuedWithdrawAmount is old queued withdraw amount
* @return newOption is the new option address
* @return lockedBalance is the new balance used to calculate next option purchase size or collateral size
* @return queuedWithdrawAmount is the new queued withdraw amount for this round
*/
function _rollToNextOption(uint256 lastQueuedWithdrawAmount)
internal
returns (
address newOption,
uint256 lockedBalance,
uint256 queuedWithdrawAmount
)
{
require(block.timestamp >= optionState.nextOptionReadyAt, "!ready");
newOption = optionState.nextOption;
require(newOption != address(0), "!nextOption");
uint256 currentRound = vaultState.round;
address recipient = feeRecipient;
uint256 mintShares;
uint256 managementFeeInAsset;
{
uint256 newPricePerShare;
(
lockedBalance,
queuedWithdrawAmount,
newPricePerShare,
mintShares,
managementFeeInAsset
) = VaultLifecycleTreasury.rollover(
vaultState,
VaultLifecycleTreasury.RolloverParams(
vaultParams.decimals,
IERC20(vaultParams.asset).balanceOf(address(this)),
totalSupply(),
lastQueuedWithdrawAmount,
currentRound != 1 ? managementFee : 0
)
);
optionState.currentOption = newOption;
optionState.nextOption = address(0);
// Finalize the pricePerShare at the end of the round
roundPricePerShare[currentRound] = newPricePerShare;
emit CollectManagementFee(
managementFeeInAsset,
currentRound,
recipient
);
vaultState.totalPending = 0;
vaultState.round = uint16(currentRound + 1);
}
_mint(address(this), mintShares);
if (managementFeeInAsset > 0) {
transferAsset(payable(recipient), managementFeeInAsset);
}
return (newOption, lockedBalance, queuedWithdrawAmount);
}
/**
* @notice Helper function to make an ERC20 transfer
* @param recipient is the receiving address
* @param amount is the transfer amount
*/
function transferAsset(address recipient, uint256 amount) internal {
address asset = vaultParams.asset;
IERC20(asset).safeTransfer(recipient, amount);
}
/**
* @notice Sets the next option the vault will be shorting, and closes the existing short.
* This allows all the users to withdraw if the next option is malicious.
*/
function commitAndClose() external nonReentrant {
address oldOption = optionState.currentOption;
VaultLifecycleTreasury.CloseParams memory closeParams =
VaultLifecycleTreasury.CloseParams({
OTOKEN_FACTORY: OTOKEN_FACTORY,
USDC: USDC,
currentOption: oldOption,
delay: DELAY,
lastStrikeOverrideRound: lastStrikeOverrideRound,
overriddenStrikePrice: overriddenStrikePrice,
period: period
});
(
address otokenAddress,
uint256 premium,
uint256 strikePrice,
uint256 delta
) =
VaultLifecycleTreasury.commitAndClose(
strikeSelection,
optionsPremiumPricer,
premiumDiscount,
closeParams,
vaultParams,
vaultState
);
emit NewOptionStrikeSelected(strikePrice, delta);
ShareMath.assertUint104(premium);
currentOtokenPremium = uint104(premium);
optionState.nextOption = otokenAddress;
uint256 nextOptionReady = block.timestamp.add(DELAY);
require(
nextOptionReady <= type(uint32).max,
"Overflow nextOptionReady"
);
optionState.nextOptionReadyAt = uint32(nextOptionReady);
_closeShort(oldOption);
// In case chargeAndDistribute was not called last round, call
// the function to conclude last round's performance fee and distribution
if (IERC20(USDC).balanceOf(address(this)) > MIN_DUST_AMOUNT) {
_chargeAndDistribute();
}
}
/**
* @notice Closes the existing short position for the vault.
*/
function _closeShort(address oldOption) private {
uint256 lockedAmount = vaultState.lockedAmount;
if (oldOption != address(0)) {
vaultState.lastLockedAmount = uint104(lockedAmount);
}
vaultState.lockedAmount = 0;
optionState.currentOption = address(0);
if (oldOption != address(0)) {
uint256 withdrawAmount =
VaultLifecycleTreasury.settleShort(GAMMA_CONTROLLER);
emit CloseShort(oldOption, withdrawAmount, msg.sender);
}
}
/**
* @notice Rolls the vault's funds into a new short position.
*/
function rollToNextOption() external onlyKeeper nonReentrant {
(
address newOption,
uint256 lockedBalance,
uint256 queuedWithdrawAmount
) = _rollToNextOption(uint256(lastQueuedWithdrawAmount));
lastQueuedWithdrawAmount = queuedWithdrawAmount;
ShareMath.assertUint104(lockedBalance);
vaultState.lockedAmount = uint104(lockedBalance);
emit OpenShort(newOption, lockedBalance, msg.sender);
VaultLifecycleTreasury.createShort(
GAMMA_CONTROLLER,
MARGIN_POOL,
newOption,
lockedBalance
);
_startAuction();
}
/**
* @notice Initiate the gnosis auction.
*/
function startAuction() external onlyKeeper nonReentrant {
_startAuction();
}
function _startAuction() private {
GnosisAuction.AuctionDetails memory auctionDetails;
uint256 currOtokenPremium = currentOtokenPremium;
require(currOtokenPremium > 0, "!currentOtokenPremium");
uint256 stableDecimals = IERC20Detailed(USDC).decimals();
auctionDetails.oTokenAddress = optionState.currentOption;
auctionDetails.gnosisEasyAuction = GNOSIS_EASY_AUCTION;
auctionDetails.asset = USDC;
auctionDetails.assetDecimals = stableDecimals;
auctionDetails.oTokenPremium = currOtokenPremium;
auctionDetails.duration = auctionDuration;
optionAuctionID = VaultLifecycleTreasury.startAuction(auctionDetails);
}
/**
* @notice Burn the remaining oTokens left over from gnosis auction.
*/
function burnRemainingOTokens() external onlyKeeper nonReentrant {
uint256 unlockedAssetAmount =
VaultLifecycleTreasury.burnOtokens(
GAMMA_CONTROLLER,
optionState.currentOption
);
vaultState.lockedAmount = uint104(
uint256(vaultState.lockedAmount).sub(unlockedAssetAmount)
);
}
/**
* @notice Settles the round's Gnosis auction and distribute the premiums earned
*/
function concludeOptionsSale() external onlyKeeper nonReentrant {
VaultLifecycleTreasury.settleAuction(
GNOSIS_EASY_AUCTION,
optionAuctionID
);
if (IERC20(USDC).balanceOf(address(this)) > MIN_DUST_AMOUNT) {
_chargeAndDistribute();
}
}
/**
* @notice Charge performance fee and distribute remaining to depositors addresses
*/
function chargeAndDistribute() external onlyKeeper nonReentrant {
_chargeAndDistribute();
}
/**
* @notice Calculate performance fee and transfer to fee recipient
*/
function _chargeAndDistribute() internal {
IERC20 stableAsset = IERC20(USDC);
uint256 stableBalance = stableAsset.balanceOf(address(this));
require(stableBalance > 0, "no premium to distribute");
_chargePerformanceFee(stableAsset, stableBalance);
_distributePremium(
stableAsset,
stableAsset.balanceOf(address(this)) // Get the new balance
);
}
/**
* @notice Charge performance fee
*/
function _chargePerformanceFee(IERC20 token, uint256 amount) internal {
address recipient = feeRecipient;
uint256 transferAmount =
amount.mul(performanceFee).div(100 * Vault.FEE_MULTIPLIER);
token.safeTransfer(recipient, transferAmount);
// Performance fee for the round is charged after rollover
// hence we need to adjust the round to the previous
emit CollectPerformanceFee(
transferAmount,
vaultState.round - 1,
recipient
);
}
/**
* @notice Distribute the premium to depositor addresses
*/
function _distributePremium(IERC20 token, uint256 amount) internal {
// Distribute to depositor address
address[] storage _depositors = depositorsArray;
uint256[] memory _amounts = new uint256[](_depositors.length);
uint256 totalSupply = totalSupply() - lastQueuedWithdrawAmount;
for (uint256 i = 0; i < _depositors.length; i++) {
// Distribute to depositors proportional to the amount of
// shares they own
address depositorAddress = _depositors[i];
_amounts[i] = shares(depositorAddress).mul(amount).div(totalSupply);
token.safeTransfer(depositorAddress, _amounts[i]);
}
emit DistributePremium(
amount,
_amounts,
_depositors,
vaultState.round - 1
);
}
/************************************************
* GETTERS
***********************************************/
/**
* @notice Returns the asset balance held on the vault for the account
* @param account is the address to lookup balance for
* @return the amount of `asset` custodied by the vault for the user
*/
function accountVaultBalance(address account)
public
view
returns (uint256)
{
uint256 _decimals = vaultParams.decimals;
uint256 assetPerShare =
ShareMath.pricePerShare(
totalSupply(),
totalBalance(),
vaultState.totalPending,
_decimals
);
return
ShareMath.sharesToAsset(shares(account), assetPerShare, _decimals);
}
/**
* @notice Getter for returning the account's share balance including unredeemed shares
* @param account is the account to lookup share balance for
* @return the share balance
*/
function shares(address account) public view returns (uint256) {
(uint256 heldByAccount, uint256 heldByVault) = shareBalances(account);
return heldByAccount.add(heldByVault);
}
/**
* @notice Getter for returning the account's share balance split between account and vault holdings
* @param account is the account to lookup share balance for
* @return heldByAccount is the shares held by account
* @return heldByVault is the shares held on the vault (unredeemedShares)
*/
function shareBalances(address account)
public
view
returns (uint256 heldByAccount, uint256 heldByVault)
{
Vault.DepositReceipt memory depositReceipt = depositReceipts[account];
if (depositReceipt.round < ShareMath.PLACEHOLDER_UINT) {
return (balanceOf(account), 0);
}
uint256 unredeemedShares =
depositReceipt.getSharesFromReceipt(
vaultState.round,
roundPricePerShare[depositReceipt.round],
vaultParams.decimals
);
return (balanceOf(account), unredeemedShares);
}
/**
* @notice The price of a unit of share denominated in the `asset`
*/
function pricePerShare() external view returns (uint256) {
return
ShareMath.pricePerShare(
totalSupply(),
totalBalance(),
vaultState.totalPending,
vaultParams.decimals
);
}
/**
* @notice Returns the vault's total balance, including the amounts locked into a short position
* @return total balance of the vault, including the amounts locked in third party protocols
*/
function totalBalance() public view returns (uint256) {
return
uint256(vaultState.lockedAmount).add(
IERC20(vaultParams.asset).balanceOf(address(this))
);
}
/**
* @notice Returns the token decimals
*/
function decimals() public view override returns (uint8) {
return vaultParams.decimals;
}
/**
* @notice Returns the maximum capacity of the vault in terms of the vault's asset
*/
function cap() external view returns (uint256) {
return vaultParams.cap;
}
/**
* @notice Returns the date and time for the next options sale
*/
function nextOptionReadyAt() external view returns (uint256) {
return optionState.nextOptionReadyAt;
}
/**
* @notice Returns the options specification for the current round
*/
function currentOption() external view returns (address) {
return optionState.currentOption;
}
/**
* @notice Returns the options specification for the next round
*/
function nextOption() external view returns (address) {
return optionState.nextOption;
}
/**
* @notice Returns total pending deposit for the current round
*/
function totalPending() external view returns (uint256) {
return vaultState.totalPending;
}
/**
* @notice ERC20 _transfer override function
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
require(
recipient == address(this) || sender == address(this),
"Treasury rToken is not transferrable"
);
return ERC20Upgradeable._transfer(sender, recipient, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// 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;
}
}
}
// SPDX-License-Identifier: MIT
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 `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.8.0;
import "../IERC20.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 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");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 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 initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_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 {
_setOwner(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");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.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 Contracts guidelines: functions revert
* instead 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* 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:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(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:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
library Vault {
/************************************************
* IMMUTABLES & CONSTANTS
***********************************************/
// Fees are 6-decimal places. For example: 20 * 10**6 = 20%
uint256 internal constant FEE_MULTIPLIER = 10**6;
// Premium discount has 1-decimal place. For example: 80 * 10**1 = 80%. Which represents a 20% discount.
uint256 internal constant PREMIUM_DISCOUNT_MULTIPLIER = 10;
// Otokens have 8 decimal places.
uint256 internal constant OTOKEN_DECIMALS = 8;
// Percentage of funds allocated to options is 2 decimal places. 10 * 10**2 = 10%
uint256 internal constant OPTION_ALLOCATION_MULTIPLIER = 10**2;
// Placeholder uint value to prevent cold writes
uint256 internal constant PLACEHOLDER_UINT = 1;
struct VaultParams {
// Option type the vault is selling
bool isPut;
// Token decimals for vault shares
uint8 decimals;
// Asset used in Theta / Delta Vault
address asset;
// Underlying asset of the options sold by vault
address underlying;
// Minimum supply of the vault shares issued, for ETH it's 10**10
uint56 minimumSupply;
// Vault cap
uint104 cap;
}
struct OptionState {
// Option that the vault is shorting / longing in the next cycle
address nextOption;
// Option that the vault is currently shorting / longing
address currentOption;
// The timestamp when the `nextOption` can be used by the vault
uint32 nextOptionReadyAt;
}
struct VaultState {
// 32 byte slot 1
// Current round number. `round` represents the number of `period`s elapsed.
uint16 round;
// Amount that is currently locked for selling options
uint104 lockedAmount;
// Amount that was locked for selling options in the previous round
// used for calculating performance fee deduction
uint104 lastLockedAmount;
// 32 byte slot 2
// Stores the total tally of how much of `asset` there is
// to be used to mint rTHETA tokens
uint128 totalPending;
// Amount locked for scheduled withdrawals;
uint128 queuedWithdrawShares;
}
struct DepositReceipt {
// Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.
uint16 round;
// Deposit amount, max 20,282,409,603,651 or 20 trillion ETH deposit
uint104 amount;
// Unredeemed shares balance
uint128 unredeemedShares;
}
struct Withdrawal {
// Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.
uint16 round;
// Number of shares withdrawn
uint128 shares;
}
struct AuctionSellOrder {
// Amount of `asset` token offered in auction
uint96 sellAmount;
// Amount of oToken requested in auction
uint96 buyAmount;
// User Id of delta vault in latest gnosis auction
uint64 userId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Vault} from "./Vault.sol";
import {ShareMath} from "./ShareMath.sol";
import {IStrikeSelection} from "../interfaces/IRibbon.sol";
import {GnosisAuction} from "./GnosisAuction.sol";
import {DateTime} from "./DateTime.sol";
import {
IOtokenFactory,
IOtoken,
IController,
GammaTypes
} from "../interfaces/GammaInterface.sol";
import {IERC20Detailed} from "../interfaces/IERC20Detailed.sol";
import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol";
import {SupportsNonCompliantERC20} from "./SupportsNonCompliantERC20.sol";
library VaultLifecycleTreasury {
using SafeMath for uint256;
using SupportsNonCompliantERC20 for IERC20;
struct CloseParams {
address OTOKEN_FACTORY;
address USDC;
address currentOption;
uint256 delay;
uint16 lastStrikeOverrideRound;
uint256 overriddenStrikePrice;
uint256 period;
}
/**
* @notice Initialization parameters for the vault.
* @param _owner is the owner of the vault with critical permissions
* @param _feeRecipient is the address to recieve vault performance and management fees
* @param _managementFee is the management fee pct.
* @param _performanceFee is the perfomance fee pct.
* @param _tokenName is the name of the token
* @param _tokenSymbol is the symbol of the token
* @param _optionsPremiumPricer is the address of the contract with the
black-scholes premium calculation logic
* @param _strikeSelection is the address of the contract with strike selection logic
* @param _premiumDiscount is the vault's discount applied to the premium
* @param _auctionDuration is the duration of the gnosis auction
* @param _period is the period between each option sales
*/
struct InitParams {
address _owner;
address _keeper;
address _feeRecipient;
uint256 _managementFee;
uint256 _performanceFee;
string _tokenName;
string _tokenSymbol;
address _optionsPremiumPricer;
address _strikeSelection;
uint32 _premiumDiscount;
uint256 _auctionDuration;
uint256 _period;
uint256 _maxDepositors;
uint256 _minDeposit;
}
/**
* @notice Sets the next option the vault will be shorting, and calculates its premium for the auction
* @param strikeSelection is the address of the contract with strike selection logic
* @param optionsPremiumPricer is the address of the contract with the
black-scholes premium calculation logic
* @param premiumDiscount is the vault's discount applied to the premium
* @param closeParams is the struct with details on previous option and strike selection details
* @param vaultParams is the struct with vault general data
* @param vaultState is the struct with vault accounting state
* @return otokenAddress is the address of the new option
* @return premium is the premium of the new option
* @return strikePrice is the strike price of the new option
* @return delta is the delta of the new option
*/
function commitAndClose(
address strikeSelection,
address optionsPremiumPricer,
uint256 premiumDiscount,
CloseParams calldata closeParams,
Vault.VaultParams storage vaultParams,
Vault.VaultState storage vaultState
)
external
returns (
address otokenAddress,
uint256 premium,
uint256 strikePrice,
uint256 delta
)
{
uint256 expiry;
// uninitialized state
if (closeParams.currentOption == address(0)) {
expiry = getNextExpiry(block.timestamp, closeParams.period);
} else {
expiry = getNextExpiry(
IOtoken(closeParams.currentOption).expiryTimestamp(),
closeParams.period
);
}
IStrikeSelection selection = IStrikeSelection(strikeSelection);
bool isPut = vaultParams.isPut;
address underlying = vaultParams.underlying;
address asset = vaultParams.asset;
(strikePrice, delta) = closeParams.lastStrikeOverrideRound ==
vaultState.round
? (closeParams.overriddenStrikePrice, 0)
: selection.getStrikePrice(expiry, isPut);
require(strikePrice != 0, "!strikePrice");
// retrieve address if option already exists, or deploy it
otokenAddress = getOrDeployOtoken(
closeParams,
vaultParams,
underlying,
asset,
strikePrice,
expiry,
isPut
);
// get the black scholes premium of the option
premium = GnosisAuction.getOTokenPremiumInStables(
otokenAddress,
optionsPremiumPricer,
premiumDiscount
);
require(premium > 0, "!premium");
return (otokenAddress, premium, strikePrice, delta);
}
/**
* @notice Verify the otoken has the correct parameters to prevent vulnerability to opyn contract changes
* @param otokenAddress is the address of the otoken
* @param vaultParams is the struct with vault general data
* @param collateralAsset is the address of the collateral asset
* @param USDC is the address of usdc
* @param delay is the delay between commitAndClose and rollToNextOption
*/
function verifyOtoken(
address otokenAddress,
Vault.VaultParams storage vaultParams,
address collateralAsset,
address USDC,
uint256 delay
) private view {
require(otokenAddress != address(0), "!otokenAddress");
IOtoken otoken = IOtoken(otokenAddress);
require(otoken.isPut() == vaultParams.isPut, "Type mismatch");
require(
otoken.underlyingAsset() == vaultParams.underlying,
"Wrong underlyingAsset"
);
require(
otoken.collateralAsset() == collateralAsset,
"Wrong collateralAsset"
);
// we just assume all options use USDC as the strike
require(otoken.strikeAsset() == USDC, "strikeAsset != USDC");
uint256 readyAt = block.timestamp.add(delay);
require(otoken.expiryTimestamp() >= readyAt, "Expiry before delay");
}
/**
* @param currentShareSupply is the supply of the shares invoked with totalSupply()
* @param asset is the address of the vault's asset
* @param decimals is the decimals of the asset
* @param lastQueuedWithdrawAmount is the amount queued for withdrawals from last round
* @param managementFee is the management fee percent to charge on the AUM
*/
struct RolloverParams {
uint256 decimals;
uint256 totalBalance;
uint256 currentShareSupply;
uint256 lastQueuedWithdrawAmount;
uint256 managementFee;
}
/**
* @notice Calculate the shares to mint, new price per share, and
amount of funds to re-allocate as collateral for the new round
* @param vaultState is the storage variable vaultState passed from RibbonVault
* @param params is the rollover parameters passed to compute the next state
* @return newLockedAmount is the amount of funds to allocate for the new round
* @return queuedWithdrawAmount is the amount of funds set aside for withdrawal
* @return newPricePerShare is the price per share of the new round
* @return mintShares is the amount of shares to mint from deposits
* @return managementFeeInAsset is the amount of management fee charged by vault
*/
function rollover(
Vault.VaultState storage vaultState,
RolloverParams calldata params
)
external
view
returns (
uint256 newLockedAmount,
uint256 queuedWithdrawAmount,
uint256 newPricePerShare,
uint256 mintShares,
uint256 managementFeeInAsset
)
{
uint256 currentBalance = params.totalBalance;
uint256 pendingAmount = vaultState.totalPending;
uint256 queuedWithdrawShares = vaultState.queuedWithdrawShares;
uint256 balanceForVaultFees;
{
uint256 pricePerShareBeforeFee =
ShareMath.pricePerShare(
params.currentShareSupply,
currentBalance,
pendingAmount,
params.decimals
);
uint256 queuedWithdrawBeforeFee =
params.currentShareSupply > 0
? ShareMath.sharesToAsset(
queuedWithdrawShares,
pricePerShareBeforeFee,
params.decimals
)
: 0;
// Deduct the difference between the newly scheduled withdrawals
// and the older withdrawals
// so we can charge them fees before they leave
uint256 withdrawAmountDiff =
queuedWithdrawBeforeFee > params.lastQueuedWithdrawAmount
? queuedWithdrawBeforeFee.sub(
params.lastQueuedWithdrawAmount
)
: 0;
balanceForVaultFees = currentBalance
.sub(queuedWithdrawBeforeFee)
.add(withdrawAmountDiff);
}
managementFeeInAsset = getManagementFee(
balanceForVaultFees,
vaultState.totalPending,
params.managementFee
);
// Take into account the fee
// so we can calculate the newPricePerShare
currentBalance = currentBalance.sub(managementFeeInAsset);
{
newPricePerShare = ShareMath.pricePerShare(
params.currentShareSupply,
currentBalance,
pendingAmount,
params.decimals
);
// After closing the short, if the options expire in-the-money
// vault pricePerShare would go down because vault's asset balance decreased.
// This ensures that the newly-minted shares do not take on the loss.
mintShares = ShareMath.assetToShares(
pendingAmount,
newPricePerShare,
params.decimals
);
uint256 newSupply = params.currentShareSupply.add(mintShares);
queuedWithdrawAmount = newSupply > 0
? ShareMath.sharesToAsset(
queuedWithdrawShares,
newPricePerShare,
params.decimals
)
: 0;
}
return (
currentBalance.sub(queuedWithdrawAmount), // new locked balance subtracts the queued withdrawals
queuedWithdrawAmount,
newPricePerShare,
mintShares,
managementFeeInAsset
);
}
/**
* @notice Creates the actual Opyn short position by depositing collateral and minting otokens
* @param gammaController is the address of the opyn controller contract
* @param marginPool is the address of the opyn margin contract which holds the collateral
* @param oTokenAddress is the address of the otoken to mint
* @param depositAmount is the amount of collateral to deposit
* @return the otoken mint amount
*/
function createShort(
address gammaController,
address marginPool,
address oTokenAddress,
uint256 depositAmount
) external returns (uint256) {
IController controller = IController(gammaController);
uint256 newVaultID =
(controller.getAccountVaultCounter(address(this))).add(1);
// An otoken's collateralAsset is the vault's `asset`
// So in the context of performing Opyn short operations we call them collateralAsset
IOtoken oToken = IOtoken(oTokenAddress);
address collateralAsset = oToken.collateralAsset();
uint256 collateralDecimals =
uint256(IERC20Detailed(collateralAsset).decimals());
uint256 mintAmount;
if (oToken.isPut()) {
// For minting puts, there will be instances where the full depositAmount will not be used for minting.
// This is because of an issue with precision.
//
// For ETH put options, we are calculating the mintAmount (10**8 decimals) using
// the depositAmount (10**18 decimals), which will result in truncation of decimals when scaling down.
// As a result, there will be tiny amounts of dust left behind in the Opyn vault when minting put otokens.
//
// For simplicity's sake, we do not refund the dust back to the address(this) on minting otokens.
// We retain the dust in the vault so the calling contract can withdraw the
// actual locked amount + dust at settlement.
//
// To test this behavior, we can console.log
// MarginCalculatorInterface(0x7A48d10f372b3D7c60f6c9770B91398e4ccfd3C7).getExcessCollateral(vault)
// to see how much dust (or excess collateral) is left behind.
mintAmount = depositAmount
.mul(10**Vault.OTOKEN_DECIMALS)
.mul(10**18) // we use 10**18 to give extra precision
.div(oToken.strikePrice().mul(10**(10 + collateralDecimals)));
} else {
mintAmount = depositAmount;
if (collateralDecimals > 8) {
uint256 scaleBy = 10**(collateralDecimals.sub(8)); // oTokens have 8 decimals
if (mintAmount > scaleBy) {
mintAmount = depositAmount.div(scaleBy); // scale down from 10**18 to 10**8
}
}
}
// double approve to fix non-compliant ERC20s
IERC20 collateralToken = IERC20(collateralAsset);
collateralToken.safeApproveNonCompliant(marginPool, depositAmount);
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](3);
actions[0] = IController.ActionArgs(
IController.ActionType.OpenVault,
address(this), // owner
address(this), // receiver
address(0), // asset, otoken
newVaultID, // vaultId
0, // amount
0, //index
"" //data
);
actions[1] = IController.ActionArgs(
IController.ActionType.DepositCollateral,
address(this), // owner
address(this), // address to transfer from
collateralAsset, // deposited asset
newVaultID, // vaultId
depositAmount, // amount
0, //index
"" //data
);
actions[2] = IController.ActionArgs(
IController.ActionType.MintShortOption,
address(this), // owner
address(this), // address to transfer to
oTokenAddress, // option address
newVaultID, // vaultId
mintAmount, // amount
0, //index
"" //data
);
controller.operate(actions);
return mintAmount;
}
/**
* @notice Close the existing short otoken position. Currently this implementation is simple.
* It closes the most recent vault opened by the contract. This assumes that the contract will
* only have a single vault open at any given time. Since calling `_closeShort` deletes vaults by
calling SettleVault action, this assumption should hold.
* @param gammaController is the address of the opyn controller contract
* @return amount of collateral redeemed from the vault
*/
function settleShort(address gammaController) external returns (uint256) {
IController controller = IController(gammaController);
// gets the currently active vault ID
uint256 vaultID = controller.getAccountVaultCounter(address(this));
GammaTypes.Vault memory vault =
controller.getVault(address(this), vaultID);
require(vault.shortOtokens.length > 0, "No short");
// An otoken's collateralAsset is the vault's `asset`
// So in the context of performing Opyn short operations we call them collateralAsset
IERC20 collateralToken = IERC20(vault.collateralAssets[0]);
// The short position has been previously closed, or all the otokens have been burned.
// So we return early.
if (address(collateralToken) == address(0)) {
return 0;
}
// This is equivalent to doing IERC20(vault.asset).balanceOf(address(this))
uint256 startCollateralBalance =
collateralToken.balanceOf(address(this));
// If it is after expiry, we need to settle the short position using the normal way
// Delete the vault and withdraw all remaining collateral from the vault
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.SettleVault,
address(this), // owner
address(this), // address to transfer to
address(0), // not used
vaultID, // vaultId
0, // not used
0, // not used
"" // not used
);
controller.operate(actions);
uint256 endCollateralBalance = collateralToken.balanceOf(address(this));
return endCollateralBalance.sub(startCollateralBalance);
}
/**
* @notice Exercises the ITM option using existing long otoken position. Currently this implementation is simple.
* It calls the `Redeem` action to claim the payout.
* @param gammaController is the address of the opyn controller contract
* @param oldOption is the address of the old option
* @param asset is the address of the vault's asset
* @return amount of asset received by exercising the option
*/
function settleLong(
address gammaController,
address oldOption,
address asset
) external returns (uint256) {
IController controller = IController(gammaController);
uint256 oldOptionBalance = IERC20(oldOption).balanceOf(address(this));
if (controller.getPayout(oldOption, oldOptionBalance) == 0) {
return 0;
}
uint256 startAssetBalance = IERC20(asset).balanceOf(address(this));
// If it is after expiry, we need to redeem the profits
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](1);
actions[0] = IController.ActionArgs(
IController.ActionType.Redeem,
address(0), // not used
address(this), // address to send profits to
oldOption, // address of otoken
0, // not used
oldOptionBalance, // otoken balance
0, // not used
"" // not used
);
controller.operate(actions);
uint256 endAssetBalance = IERC20(asset).balanceOf(address(this));
return endAssetBalance.sub(startAssetBalance);
}
/**
* @notice Burn the remaining oTokens left over from auction. Currently this implementation is simple.
* It burns oTokens from the most recent vault opened by the contract. This assumes that the contract will
* only have a single vault open at any given time.
* @param gammaController is the address of the opyn controller contract
* @param currentOption is the address of the current option
* @return amount of collateral redeemed by burning otokens
*/
function burnOtokens(address gammaController, address currentOption)
external
returns (uint256)
{
uint256 numOTokensToBurn =
IERC20(currentOption).balanceOf(address(this));
require(numOTokensToBurn > 0, "No oTokens to burn");
IController controller = IController(gammaController);
// gets the currently active vault ID
uint256 vaultID = controller.getAccountVaultCounter(address(this));
GammaTypes.Vault memory vault =
controller.getVault(address(this), vaultID);
require(vault.shortOtokens.length > 0, "No short");
IERC20 collateralToken = IERC20(vault.collateralAssets[0]);
uint256 startCollateralBalance =
collateralToken.balanceOf(address(this));
// Burning `amount` of oTokens from the ribbon vault,
// then withdrawing the corresponding collateral amount from the vault
IController.ActionArgs[] memory actions =
new IController.ActionArgs[](2);
actions[0] = IController.ActionArgs(
IController.ActionType.BurnShortOption,
address(this), // owner
address(this), // address to transfer from
address(vault.shortOtokens[0]), // otoken address
vaultID, // vaultId
numOTokensToBurn, // amount
0, //index
"" //data
);
actions[1] = IController.ActionArgs(
IController.ActionType.WithdrawCollateral,
address(this), // owner
address(this), // address to transfer to
address(collateralToken), // withdrawn asset
vaultID, // vaultId
vault.collateralAmounts[0].mul(numOTokensToBurn).div(
vault.shortAmounts[0]
), // amount
0, //index
"" //data
);
controller.operate(actions);
uint256 endCollateralBalance = collateralToken.balanceOf(address(this));
return endCollateralBalance.sub(startCollateralBalance);
}
/**
* @notice Calculates the management fee for this week's round
* @param currentBalance is the balance of funds held on the vault after closing short
* @param pendingAmount is the pending deposit amount
* @param managementFeePercent is the management fee pct.
* @return managementFeeInAsset is the management fee
*/
function getManagementFee(
uint256 currentBalance,
uint256 pendingAmount,
uint256 managementFeePercent
) internal pure returns (uint256 managementFeeInAsset) {
// At the first round, currentBalance=0, pendingAmount>0
// so we just do not charge anything on the first round
uint256 lockedBalanceSansPending =
currentBalance > pendingAmount
? currentBalance.sub(pendingAmount)
: 0;
uint256 _managementFeeInAsset;
// Always charge management fee regardless of whether the vault is
// making a profit from the previous options sale
_managementFeeInAsset = managementFeePercent > 0
? lockedBalanceSansPending.mul(managementFeePercent).div(
100 * Vault.FEE_MULTIPLIER
)
: 0;
return _managementFeeInAsset;
}
/**
* @notice Either retrieves the option token if it already exists, or deploy it
* @param closeParams is the struct with details on previous option and strike selection details
* @param vaultParams is the struct with vault general data
* @param underlying is the address of the underlying asset of the option
* @param collateralAsset is the address of the collateral asset of the option
* @param strikePrice is the strike price of the option
* @param expiry is the expiry timestamp of the option
* @param isPut is whether the option is a put
* @return the address of the option
*/
function getOrDeployOtoken(
CloseParams calldata closeParams,
Vault.VaultParams storage vaultParams,
address underlying,
address collateralAsset,
uint256 strikePrice,
uint256 expiry,
bool isPut
) internal returns (address) {
IOtokenFactory factory = IOtokenFactory(closeParams.OTOKEN_FACTORY);
address otokenFromFactory =
factory.getOtoken(
underlying,
closeParams.USDC,
collateralAsset,
strikePrice,
expiry,
isPut
);
if (otokenFromFactory != address(0)) {
return otokenFromFactory;
}
address otoken =
factory.createOtoken(
underlying,
closeParams.USDC,
collateralAsset,
strikePrice,
expiry,
isPut
);
verifyOtoken(
otoken,
vaultParams,
collateralAsset,
closeParams.USDC,
closeParams.delay
);
return otoken;
}
/**
* @notice Starts the gnosis auction
* @param auctionDetails is the struct with all the custom parameters of the auction
* @return the auction id of the newly created auction
*/
function startAuction(GnosisAuction.AuctionDetails calldata auctionDetails)
external
returns (uint256)
{
return GnosisAuction.startAuction(auctionDetails);
}
/**
* @notice Settles the gnosis auction
* @param gnosisEasyAuction is the contract address of Gnosis easy auction protocol
* @param auctionID is the auction ID of the gnosis easy auction
*/
function settleAuction(address gnosisEasyAuction, uint256 auctionID)
internal
{
IGnosisAuction(gnosisEasyAuction).settleAuction(auctionID);
}
/**
* @notice Places a bid in an auction
* @param bidDetails is the struct with all the details of the
bid including the auction's id and how much to bid
*/
function placeBid(GnosisAuction.BidDetails calldata bidDetails)
external
returns (
uint256 sellAmount,
uint256 buyAmount,
uint64 userId
)
{
return GnosisAuction.placeBid(bidDetails);
}
/**
* @notice Claims the oTokens belonging to the vault
* @param auctionSellOrder is the sell order of the bid
* @param gnosisEasyAuction is the address of the gnosis auction contract
holding custody to the funds
* @param counterpartyThetaVault is the address of the counterparty theta
vault of this delta vault
*/
function claimAuctionOtokens(
Vault.AuctionSellOrder calldata auctionSellOrder,
address gnosisEasyAuction,
address counterpartyThetaVault
) external {
GnosisAuction.claimAuctionOtokens(
auctionSellOrder,
gnosisEasyAuction,
counterpartyThetaVault
);
}
/**
* @notice Verify the constructor params satisfy requirements
* @param _initParams is the initialization parameter including owner, keeper, etc.
* @param _vaultParams is the struct with vault general data
*/
function verifyInitializerParams(
InitParams calldata _initParams,
Vault.VaultParams calldata _vaultParams,
uint256 _min_auction_duration
) external pure {
require(_initParams._owner != address(0), "!_owner");
require(_initParams._keeper != address(0), "!_keeper");
require(_initParams._feeRecipient != address(0), "!_feeRecipient");
require(
_initParams._performanceFee < 100 * Vault.FEE_MULTIPLIER,
"performanceFee >= 100%"
);
require(
_initParams._managementFee < 100 * Vault.FEE_MULTIPLIER,
"managementFee >= 100%"
);
require(bytes(_initParams._tokenName).length > 0, "!_tokenName");
require(bytes(_initParams._tokenSymbol).length > 0, "!_tokenSymbol");
require(
(_initParams._period == 7) ||
(_initParams._period == 14) ||
(_initParams._period == 30) ||
(_initParams._period == 90) ||
(_initParams._period == 180),
"!_period"
);
require(
_initParams._optionsPremiumPricer != address(0),
"!_optionsPremiumPricer"
);
require(
_initParams._strikeSelection != address(0),
"!_strikeSelection"
);
require(
_initParams._premiumDiscount > 0 &&
_initParams._premiumDiscount <
100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER,
"!_premiumDiscount"
);
require(
_initParams._auctionDuration >= _min_auction_duration,
"!_auctionDuration"
);
require(_initParams._maxDepositors > 0, "!_maxDepositors");
require(_initParams._minDeposit > 0, "!_minDeposit");
require(_vaultParams.asset != address(0), "!asset");
require(_vaultParams.underlying != address(0), "!underlying");
require(_vaultParams.minimumSupply > 0, "!minimumSupply");
require(_vaultParams.cap > 0, "!cap");
require(
_vaultParams.cap > _vaultParams.minimumSupply,
"cap has to be higher than minimumSupply"
);
}
/**
* @notice Gets the next options expiry timestamp, this function should be called
when there is sufficient guard to ensure valid period
* @param timestamp is the expiry timestamp of the current option
* @param period is no. of days in between option sales. Available periods are:
* 7(1w), 14(2w), 30(1m), 90(3m), 180(6m)
*/
function getNextExpiry(uint256 timestamp, uint256 period)
internal
pure
returns (uint256 nextExpiry)
{
if (period == 7) {
nextExpiry = DateTime.getNextFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? nextExpiry + 1 weeks
: nextExpiry;
} else if (period == 14) {
nextExpiry = DateTime.getNextFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? nextExpiry + 2 weeks
: nextExpiry;
} else if (period == 30) {
nextExpiry = DateTime.getMonthLastFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? DateTime.getMonthLastFriday(nextExpiry + 1 weeks)
: nextExpiry;
} else if (period == 90) {
nextExpiry = DateTime.getQuarterLastFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? DateTime.getQuarterLastFriday(nextExpiry + 1 weeks)
: nextExpiry;
} else if (period == 180) {
nextExpiry = DateTime.getBiannualLastFriday(timestamp);
nextExpiry = nextExpiry <= timestamp
? DateTime.getBiannualLastFriday(nextExpiry + 1 weeks)
: nextExpiry;
}
nextExpiry = nextExpiry - (nextExpiry % (24 hours)) + (8 hours);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {Vault} from "../libraries/Vault.sol";
abstract contract RibbonTreasuryVaultStorageV1 {
/// @notice Vault's parameters like cap, decimals
Vault.VaultParams public vaultParams;
/// @notice Vault's lifecycle state like round and locked amounts
Vault.VaultState public vaultState;
/// @notice Vault's state of the options sold and the timelocked option
Vault.OptionState public optionState;
/// @notice Stores the user's pending deposit for the round
mapping(address => Vault.DepositReceipt) public depositReceipts;
/// @notice On every round's close, the pricePerShare value of an rTHETA token is stored
/// This is used to determine the number of shares to be returned
/// to a user with their DepositReceipt.depositAmount
mapping(uint256 => uint256) public roundPricePerShare;
/// @notice Stores pending user withdrawals
mapping(address => Vault.Withdrawal) public withdrawals;
/// @notice Mapping of depositors in the vault
mapping(address => bool) public depositorsMap;
/// @notice Array of depositors in the vault
address[] public depositorsArray;
/// @notice Fee recipient for the performance and management fees
address public feeRecipient;
/// @notice role in charge of weekly vault operations such as rollToNextOption and burnRemainingOTokens
// no access to critical vault changes
address public keeper;
/// @notice Logic contract used to price options
address public optionsPremiumPricer;
/// @notice Logic contract used to select strike prices
address public strikeSelection;
/// @notice Performance fee charged on premiums earned in rollToNextOption. Only charged when there is no loss.
uint256 public performanceFee;
/// @notice Management fee charged on entire AUM in rollToNextOption. Only charged when there is no loss.
uint256 public managementFee;
/// @notice Premium discount on options we are selling (thousandths place: 000 - 999)
uint256 public premiumDiscount;
/// @notice Current oToken premium
uint256 public currentOtokenPremium;
/// @notice Price last overridden strike set to
uint256 public overriddenStrikePrice;
/// @notice Auction duration
uint256 public auctionDuration;
/// @notice Auction id of current option
uint256 public optionAuctionID;
/// @notice Amount locked for scheduled withdrawals last week;
uint256 public lastQueuedWithdrawAmount;
/// @notice Period between each options sale.
/// Available options 7 (weekly), 14 (biweekly), 30 (monthly), 90 (quarterly), 180 (biannually)
uint256 public period;
/// @notice Maximum number of depositors
uint256 public maxDepositors;
/// @notice Minimum amount to deposit
uint256 public minDeposit;
/// @notice Last round id at which the strike was manually overridden
uint16 public lastStrikeOverrideRound;
}
// We are following Compound's method of upgrading new contract implementations
// When we need to add new storage variables, we create a new version of RibbonTreasuryVaultStorage
// e.g. RibbonTreasuryVaultStorage<versionNumber>, so finally it would look like
// contract RibbonTreasuryVaultStorage is RibbonTreasuryVaultStorageV1, RibbonTreasuryVaultStorageV2
abstract contract RibbonTreasuryVaultStorage is RibbonTreasuryVaultStorageV1 {
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {Vault} from "./Vault.sol";
library ShareMath {
using SafeMath for uint256;
uint256 internal constant PLACEHOLDER_UINT = 1;
function assetToShares(
uint256 assetAmount,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256) {
// If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet
// which should never happen.
// Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes.
require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare");
return assetAmount.mul(10**decimals).div(assetPerShare);
}
function sharesToAsset(
uint256 shares,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256) {
// If this throws, it means that vault's roundPricePerShare[currentRound] has not been set yet
// which should never happen.
// Has to be larger than 1 because `1` is used in `initRoundPricePerShares` to prevent cold writes.
require(assetPerShare > PLACEHOLDER_UINT, "Invalid assetPerShare");
return shares.mul(assetPerShare).div(10**decimals);
}
/**
* @notice Returns the shares unredeemed by the user given their DepositReceipt
* @param depositReceipt is the user's deposit receipt
* @param currentRound is the `round` stored on the vault
* @param assetPerShare is the price in asset per share
* @param decimals is the number of decimals the asset/shares use
* @return unredeemedShares is the user's virtual balance of shares that are owed
*/
function getSharesFromReceipt(
Vault.DepositReceipt memory depositReceipt,
uint256 currentRound,
uint256 assetPerShare,
uint256 decimals
) internal pure returns (uint256 unredeemedShares) {
if (depositReceipt.round > 0 && depositReceipt.round < currentRound) {
uint256 sharesFromRound =
assetToShares(depositReceipt.amount, assetPerShare, decimals);
return
uint256(depositReceipt.unredeemedShares).add(sharesFromRound);
}
return depositReceipt.unredeemedShares;
}
function pricePerShare(
uint256 totalSupply,
uint256 totalBalance,
uint256 pendingAmount,
uint256 decimals
) internal pure returns (uint256) {
uint256 singleShare = 10**decimals;
return
totalSupply > 0
? singleShare.mul(totalBalance.sub(pendingAmount)).div(
totalSupply
)
: singleShare;
}
/************************************************
* HELPERS
***********************************************/
function assertUint104(uint256 num) internal pure {
require(num <= type(uint104).max, "Overflow uint104");
}
function assertUint128(uint256 num) internal pure {
require(num <= type(uint128).max, "Overflow uint128");
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
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);
function decimals() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {DSMath} from "../vendor/DSMath.sol";
import {IGnosisAuction} from "../interfaces/IGnosisAuction.sol";
import {IOtoken} from "../interfaces/GammaInterface.sol";
import {IOptionsPremiumPricer} from "../interfaces/IRibbon.sol";
import {Vault} from "./Vault.sol";
import {IRibbonThetaVault} from "../interfaces/IRibbonThetaVault.sol";
library GnosisAuction {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event InitiateGnosisAuction(
address indexed auctioningToken,
address indexed biddingToken,
uint256 auctionCounter,
address indexed manager
);
event PlaceAuctionBid(
uint256 auctionId,
address indexed auctioningToken,
uint256 sellAmount,
uint256 buyAmount,
address indexed bidder
);
struct AuctionDetails {
address oTokenAddress;
address gnosisEasyAuction;
address asset;
uint256 assetDecimals;
uint256 oTokenPremium;
uint256 duration;
}
struct BidDetails {
address oTokenAddress;
address gnosisEasyAuction;
address asset;
uint256 assetDecimals;
uint256 auctionId;
uint256 lockedBalance;
uint256 optionAllocation;
uint256 optionPremium;
address bidder;
}
function startAuction(AuctionDetails calldata auctionDetails)
internal
returns (uint256 auctionID)
{
uint256 oTokenSellAmount =
getOTokenSellAmount(auctionDetails.oTokenAddress);
require(oTokenSellAmount > 0, "No otokens to sell");
IERC20(auctionDetails.oTokenAddress).safeApprove(
auctionDetails.gnosisEasyAuction,
IERC20(auctionDetails.oTokenAddress).balanceOf(address(this))
);
// minBidAmount is total oTokens to sell * premium per oToken
// shift decimals to correspond to decimals of USDC for puts
// and underlying for calls
uint256 minBidAmount =
DSMath.wmul(
oTokenSellAmount.mul(10**10),
auctionDetails.oTokenPremium
);
minBidAmount = auctionDetails.assetDecimals > 18
? minBidAmount.mul(10**(auctionDetails.assetDecimals.sub(18)))
: minBidAmount.div(
10**(uint256(18).sub(auctionDetails.assetDecimals))
);
require(
minBidAmount <= type(uint96).max,
"optionPremium * oTokenSellAmount > type(uint96) max value!"
);
uint256 auctionEnd = block.timestamp.add(auctionDetails.duration);
auctionID = IGnosisAuction(auctionDetails.gnosisEasyAuction)
.initiateAuction(
// address of oToken we minted and are selling
auctionDetails.oTokenAddress,
// address of asset we want in exchange for oTokens. Should match vault `asset`
auctionDetails.asset,
// orders can be cancelled at any time during the auction
auctionEnd,
// order will last for `duration`
auctionEnd,
// we are selling all of the otokens minus a fee taken by gnosis
uint96(oTokenSellAmount),
// the minimum we are willing to sell all the oTokens for. A discount is applied on black-scholes price
uint96(minBidAmount),
// the minimum bidding amount must be 1 * 10 ** -assetDecimals
1,
// the min funding threshold
0,
// no atomic closure
false,
// access manager contract
address(0),
// bytes for storing info like a whitelist for who can bid
bytes("")
);
emit InitiateGnosisAuction(
auctionDetails.oTokenAddress,
auctionDetails.asset,
auctionID,
msg.sender
);
}
function placeBid(BidDetails calldata bidDetails)
internal
returns (
uint256 sellAmount,
uint256 buyAmount,
uint64 userId
)
{
// calculate how much to allocate
sellAmount = bidDetails
.lockedBalance
.mul(bidDetails.optionAllocation)
.div(100 * Vault.OPTION_ALLOCATION_MULTIPLIER);
// divide the `asset` sellAmount by the target premium per oToken to
// get the number of oTokens to buy (8 decimals)
buyAmount = sellAmount
.mul(10**(bidDetails.assetDecimals.add(Vault.OTOKEN_DECIMALS)))
.div(bidDetails.optionPremium)
.div(10**bidDetails.assetDecimals);
require(
sellAmount <= type(uint96).max,
"sellAmount > type(uint96) max value!"
);
require(
buyAmount <= type(uint96).max,
"buyAmount > type(uint96) max value!"
);
// approve that amount
IERC20(bidDetails.asset).safeApprove(
bidDetails.gnosisEasyAuction,
sellAmount
);
uint96[] memory _minBuyAmounts = new uint96[](1);
uint96[] memory _sellAmounts = new uint96[](1);
bytes32[] memory _prevSellOrders = new bytes32[](1);
_minBuyAmounts[0] = uint96(buyAmount);
_sellAmounts[0] = uint96(sellAmount);
_prevSellOrders[
0
] = 0x0000000000000000000000000000000000000000000000000000000000000001;
// place sell order with that amount
userId = IGnosisAuction(bidDetails.gnosisEasyAuction).placeSellOrders(
bidDetails.auctionId,
_minBuyAmounts,
_sellAmounts,
_prevSellOrders,
"0x"
);
emit PlaceAuctionBid(
bidDetails.auctionId,
bidDetails.oTokenAddress,
sellAmount,
buyAmount,
bidDetails.bidder
);
return (sellAmount, buyAmount, userId);
}
function claimAuctionOtokens(
Vault.AuctionSellOrder calldata auctionSellOrder,
address gnosisEasyAuction,
address counterpartyThetaVault
) internal {
bytes32 order =
encodeOrder(
auctionSellOrder.userId,
auctionSellOrder.buyAmount,
auctionSellOrder.sellAmount
);
bytes32[] memory orders = new bytes32[](1);
orders[0] = order;
IGnosisAuction(gnosisEasyAuction).claimFromParticipantOrder(
IRibbonThetaVault(counterpartyThetaVault).optionAuctionID(),
orders
);
}
function getOTokenSellAmount(address oTokenAddress)
internal
view
returns (uint256)
{
// We take our current oToken balance. That will be our sell amount
// but otokens will be transferred to gnosis.
uint256 oTokenSellAmount =
IERC20(oTokenAddress).balanceOf(address(this));
require(
oTokenSellAmount <= type(uint96).max,
"oTokenSellAmount > type(uint96) max value!"
);
return oTokenSellAmount;
}
function getOTokenPremiumInStables(
address oTokenAddress,
address optionsPremiumPricer,
uint256 premiumDiscount
) internal view returns (uint256) {
IOtoken newOToken = IOtoken(oTokenAddress);
IOptionsPremiumPricer premiumPricer =
IOptionsPremiumPricer(optionsPremiumPricer);
// Apply black-scholes formula (from rvol library) to option given its features
// and get price for 100 contracts denominated USDC for both call and put options
uint256 optionPremium =
premiumPricer.getPremiumInStables(
newOToken.strikePrice(),
newOToken.expiryTimestamp(),
newOToken.isPut()
);
// Apply a discount to incentivize arbitraguers
optionPremium = optionPremium.mul(premiumDiscount).div(
100 * Vault.PREMIUM_DISCOUNT_MULTIPLIER
);
require(
optionPremium <= type(uint96).max,
"optionPremium > type(uint96) max value!"
);
return optionPremium;
}
function encodeOrder(
uint64 userId,
uint96 buyAmount,
uint96 sellAmount
) internal pure returns (bytes32) {
return
bytes32(
(uint256(userId) << 192) +
(uint256(buyAmount) << 96) +
uint256(sellAmount)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IERC20Detailed is IERC20 {
function decimals() external view returns (uint8);
function symbol() external view returns (string calldata);
function name() external view returns (string calldata);
}
// SPDX-License-Identifier: MIT
pragma solidity ^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;
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);
}
}
}
}
// 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;
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 Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {Vault} from "../libraries/Vault.sol";
interface IRibbonVault {
function deposit(uint256 amount) external;
function depositETH() external payable;
function cap() external view returns (uint256);
function depositFor(uint256 amount, address creditor) external;
function vaultParams() external view returns (Vault.VaultParams memory);
}
interface IStrikeSelection {
function getStrikePrice(uint256 expiryTimestamp, bool isPut)
external
view
returns (uint256, uint256);
function delta() external view returns (uint256);
}
interface IOptionsPremiumPricer {
function getPremium(
uint256 strikePrice,
uint256 timeToExpiry,
bool isPut
) external view returns (uint256);
function getPremiumInStables(
uint256 strikePrice,
uint256 timeToExpiry,
bool isPut
) external view returns (uint256);
function getOptionDelta(
uint256 spotPrice,
uint256 strikePrice,
uint256 volatility,
uint256 expiryTimestamp
) external view returns (uint256 delta);
function getUnderlyingPrice() external view returns (uint256);
function priceOracle() external view returns (address);
function volatilityOracle() external view returns (address);
function optionId() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// Source: https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
// ----------------------------------------------------------------------------
pragma solidity =0.8.4;
library DateTime {
uint256 constant SECONDS_PER_DAY = 24 * 60 * 60;
uint256 constant SECONDS_PER_HOUR = 60 * 60;
uint256 constant SECONDS_PER_MINUTE = 60;
int256 constant OFFSET19700101 = 2440588;
uint256 constant DOW_MON = 1;
uint256 constant DOW_TUE = 2;
uint256 constant DOW_WED = 3;
uint256 constant DOW_THU = 4;
uint256 constant DOW_FRI = 5;
uint256 constant DOW_SAT = 6;
uint256 constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(
uint256 year,
uint256 month,
uint256 day
) internal pure returns (uint256 _days) {
require(year >= 1970);
int256 _year = int256(year);
int256 _month = int256(month);
int256 _day = int256(day);
int256 __days =
_day -
32075 +
(1461 * (_year + 4800 + (_month - 14) / 12)) /
4 +
(367 * (_month - 2 - ((_month - 14) / 12) * 12)) /
12 -
(3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /
4 -
OFFSET19700101;
_days = uint256(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint256 _days)
internal
pure
returns (
uint256 year,
uint256 month,
uint256 day
)
{
int256 __days = int256(_days);
int256 L = __days + 68569 + OFFSET19700101;
int256 N = (4 * L) / 146097;
L = L - (146097 * N + 3) / 4;
int256 _year = (4000 * (L + 1)) / 1461001;
L = L - (1461 * _year) / 4 + 31;
int256 _month = (80 * L) / 2447;
int256 _day = L - (2447 * _month) / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint256(_year);
month = uint256(_month);
day = uint256(_day);
}
function isLeapYear(uint256 timestamp)
internal
pure
returns (bool leapYear)
{
(uint256 year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint256 year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function getDaysInMonth(uint256 timestamp)
internal
pure
returns (uint256 daysInMonth)
{
(uint256 year, uint256 month, ) =
_daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint256 year, uint256 month)
internal
pure
returns (uint256 daysInMonth)
{
if (
month == 1 ||
month == 3 ||
month == 5 ||
month == 7 ||
month == 8 ||
month == 10 ||
month == 12
) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint256 timestamp)
internal
pure
returns (uint256 dayOfWeek)
{
uint256 _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = ((_days + 3) % 7) + 1;
}
function getYear(uint256 timestamp) internal pure returns (uint256 year) {
(year, , ) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint256 timestamp) internal pure returns (uint256 month) {
(, month, ) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint256 timestamp) internal pure returns (uint256 day) {
(, , day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampFromDate(
uint256 year,
uint256 month,
uint256 day
) internal pure returns (uint256 timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
/**
* @notice Gets the Friday of the same week
* @param timestamp is the given date and time
* @return the Friday of the same week in unix time
*/
function getThisWeekFriday(uint256 timestamp)
internal
pure
returns (uint256)
{
return timestamp + 5 days - getDayOfWeek(timestamp) * 1 days;
}
/**
* @notice Gets the next friday after the given date and time
* @param timestamp is the given date and time
* @return the next friday after the given date and time
*/
function getNextFriday(uint256 timestamp) internal pure returns (uint256) {
uint256 friday = getThisWeekFriday(timestamp);
return friday >= timestamp ? friday : friday + 1 weeks;
}
/**
* @notice Gets the last day of the month
* @param timestamp is the given date and time
* @return the last day of the same month in unix time
*/
function getLastDayOfMonth(uint256 timestamp)
internal
pure
returns (uint256)
{
return
timestampFromDate(getYear(timestamp), getMonth(timestamp) + 1, 1) -
1 days;
}
/**
* @notice Gets the last Friday of the month
* @param timestamp is the given date and time
* @return the last Friday of the same month in unix time
*/
function getMonthLastFriday(uint256 timestamp)
internal
pure
returns (uint256)
{
uint256 lastDay = getLastDayOfMonth(timestamp);
uint256 friday = getThisWeekFriday(lastDay);
return friday > lastDay ? friday - 1 weeks : friday;
}
/**
* @notice Gets the last Friday of the quarter
* @param timestamp is the given date and time
* @return the last Friday of the quarter in unix time
*/
function getQuarterLastFriday(uint256 timestamp)
internal
pure
returns (uint256)
{
uint256 month = getMonth(timestamp);
uint256 quarterMonth =
(month <= 3) ? 3 : (month <= 6) ? 6 : (month <= 9) ? 9 : 12;
uint256 quarterDate =
timestampFromDate(getYear(timestamp), quarterMonth, 1);
return getMonthLastFriday(quarterDate);
}
/**
* @notice Gets the last Friday of the half-year
* @param timestamp is the given date and time
* @return the last friday of the half-year
*/
function getBiannualLastFriday(uint256 timestamp)
internal
pure
returns (uint256)
{
uint256 month = getMonth(timestamp);
uint256 biannualMonth = (month <= 6) ? 6 : 12;
uint256 biannualDate =
timestampFromDate(getYear(timestamp), biannualMonth, 1);
return getMonthLastFriday(biannualDate);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
library GammaTypes {
// vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults.
struct Vault {
// addresses of oTokens a user has shorted (i.e. written) against this vault
address[] shortOtokens;
// addresses of oTokens a user has bought and deposited in this vault
// user can be long oTokens without opening a vault (e.g. by buying on a DEX)
// generally, long oTokens will be 'deposited' in vaults to act as collateral
// in order to write oTokens against (i.e. in spreads)
address[] longOtokens;
// addresses of other ERC-20s a user has deposited as collateral in this vault
address[] collateralAssets;
// quantity of oTokens minted/written for each oToken address in shortOtokens
uint256[] shortAmounts;
// quantity of oTokens owned and held in the vault for each oToken address in longOtokens
uint256[] longAmounts;
// quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets
uint256[] collateralAmounts;
}
}
interface IOtoken {
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
}
interface IOtokenFactory {
function getOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
function createOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external returns (address);
function getTargetOtokenAddress(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
event OtokenCreated(
address tokenAddress,
address creator,
address indexed underlying,
address indexed strike,
address indexed collateral,
uint256 strikePrice,
uint256 expiry,
bool isPut
);
}
interface IController {
// possible actions that can be performed
enum ActionType {
OpenVault,
MintShortOption,
BurnShortOption,
DepositLongOption,
WithdrawLongOption,
DepositCollateral,
WithdrawCollateral,
SettleVault,
Redeem,
Call,
Liquidate
}
struct ActionArgs {
// type of action that is being performed on the system
ActionType actionType;
// address of the account owner
address owner;
// address which we move assets from or to (depending on the action type)
address secondAddress;
// asset that is to be transfered
address asset;
// index of the vault that is to be modified (if any)
uint256 vaultId;
// amount of asset that is to be transfered
uint256 amount;
// each vault can hold multiple short / long / collateral assets
// but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// any other data that needs to be passed in for arbitrary function calls
bytes data;
}
struct RedeemArgs {
// address to which we pay out the oToken proceeds
address receiver;
// oToken that is to be redeemed
address otoken;
// amount of oTokens that is to be redeemed
uint256 amount;
}
function getPayout(address _otoken, uint256 _amount)
external
view
returns (uint256);
function operate(ActionArgs[] calldata _actions) external;
function getAccountVaultCounter(address owner)
external
view
returns (uint256);
function oracle() external view returns (address);
function getVault(address _owner, uint256 _vaultId)
external
view
returns (GammaTypes.Vault memory);
function getProceed(address _owner, uint256 _vaultId)
external
view
returns (uint256);
function isSettlementAllowed(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) external view returns (bool);
}
interface IOracle {
function setAssetPricer(address _asset, address _pricer) external;
function updateAssetPricer(address _asset, address _pricer) external;
function getPrice(address _asset) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
library AuctionType {
struct AuctionData {
IERC20 auctioningToken;
IERC20 biddingToken;
uint256 orderCancellationEndDate;
uint256 auctionEndDate;
bytes32 initialAuctionOrder;
uint256 minimumBiddingAmountPerOrder;
uint256 interimSumBidAmount;
bytes32 interimOrder;
bytes32 clearingPriceOrder;
uint96 volumeClearingPriceOrder;
bool minFundingThresholdNotReached;
bool isAtomicClosureAllowed;
uint256 feeNumerator;
uint256 minFundingThreshold;
}
}
interface IGnosisAuction {
function initiateAuction(
address _auctioningToken,
address _biddingToken,
uint256 orderCancellationEndDate,
uint256 auctionEndDate,
uint96 _auctionedSellAmount,
uint96 _minBuyAmount,
uint256 minimumBiddingAmountPerOrder,
uint256 minFundingThreshold,
bool isAtomicClosureAllowed,
address accessManagerContract,
bytes memory accessManagerContractData
) external returns (uint256);
function auctionCounter() external view returns (uint256);
function auctionData(uint256 auctionId)
external
view
returns (AuctionType.AuctionData memory);
function auctionAccessManager(uint256 auctionId)
external
view
returns (address);
function auctionAccessData(uint256 auctionId)
external
view
returns (bytes memory);
function FEE_DENOMINATOR() external view returns (uint256);
function feeNumerator() external view returns (uint256);
function settleAuction(uint256 auctionId) external returns (bytes32);
function placeSellOrders(
uint256 auctionId,
uint96[] memory _minBuyAmounts,
uint96[] memory _sellAmounts,
bytes32[] memory _prevSellOrders,
bytes calldata allowListCallData
) external returns (uint64);
function claimFromParticipantOrder(
uint256 auctionId,
bytes32[] memory orders
) external returns (uint256, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {
SafeERC20
} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* This library supports ERC20s that have quirks in their behavior.
* One such ERC20 is USDT, which requires allowance to be 0 before calling approve.
* We plan to update this library with ERC20s that display such idiosyncratic behavior.
*/
library SupportsNonCompliantERC20 {
address private constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
function safeApproveNonCompliant(
IERC20 token,
address spender,
uint256 amount
) internal {
if (address(token) == USDT) {
SafeERC20.safeApprove(token, spender, 0);
}
SafeERC20.safeApprove(token, spender, amount);
}
}
// SPDX-License-Identifier: MIT
/// math.sol -- mixin for inline numerical wizardry
// 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.4.13;
library DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
//rounds to zero if x*y < WAD / 2
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
//rounds to zero if x*y < WAD / 2
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
//rounds to zero if x*y < WAD / 2
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
//rounds to zero if x*y < RAY / 2
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {Vault} from "../libraries/Vault.sol";
interface IRibbonThetaVault {
function currentOption() external view returns (address);
function nextOption() external view returns (address);
function vaultParams() external view returns (Vault.VaultParams memory);
function vaultState() external view returns (Vault.VaultState memory);
function optionState() external view returns (Vault.OptionState memory);
function optionAuctionID() external view returns (uint256);
function pricePerShare() external view returns (uint256);
function roundPricePerShare(uint256) external view returns (uint256);
}
|
Remove addresses from depositors list excludeDepositor is the address to exclude from the depositors list/
|
function _removeDepositor(address excludeDepositor) internal {
address[] storage array = depositorsArray;
uint256 arrayLength = array.length;
require(depositorsMap[excludeDepositor], "Depositor does not exist");
depositorsMap[excludeDepositor] = false;
for (uint256 i = 0; i < arrayLength - 1; i++) {
if (excludeDepositor == array[i]) {
(array[i], array[arrayLength - 1]) = (
array[arrayLength - 1],
array[i]
);
}
}
array.pop();
}
| 6,258,000
|
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
address[] airlines;
mapping(address => bool) private RegisteredAirline;
mapping(address => uint256) private airlineAttributes;
mapping(address => uint256) private approved;
mapping(address => uint256) private balance;
mapping(bytes32 => address[]) private airlineinsurees;
mapping(address => mapping(bytes32 => uint256)) amountOfInsurance;
mapping(bytes32 => mapping(address => uint256)) payoutOfInsurance;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(address firstAirline) public {
contractOwner = msg.sender;
RegisteredAirline[firstAirline] = true;
airlines.push(firstAirline);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireIsAirlineRegistered(address caller) {
require(RegisteredAirline[caller] == true, "Caller is not registered");
_;
}
modifier requireNotRegistered(address airline) {
require(
RegisteredAirline[airline] == false,
"Airline already registered"
);
_;
}
modifier requireIsAuthorized() {
require(
approved[msg.sender] == 1,
"Caller is not contract owner"
);
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isAirline(address airline) public view returns (bool) {
return RegisteredAirline[airline];
}
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function authorizedCaller(address contractAddress)
external
requireContractOwner
{
approved[contractAddress] = 1;
}
function unauthorizedCaller(address contractAddress)
external
requireContractOwner
{
delete approved[contractAddress];
}
function registerAirline(address airline)
external
requireIsOperational
requireIsAuthorized
requireNotRegistered(airline)
returns (bool success)
{
require(airline != address(0));
RegisteredAirline[airline] = true;
airlines.push(airline);
return RegisteredAirline[airline];
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(
address airline,
string flight,
uint256 _timestamp,
address passenger,
uint256 amount
)external
requireIsOperational
requireIsAuthorized
requireIsAirlineRegistered(airline)
{
bytes32 flightkey = getKeyOfFlight(airline, flight, _timestamp);
airlineinsurees[flightkey].push(passenger);
amountOfInsurance[passenger][flightkey] = amount;
payoutOfInsurance[flightkey][passenger] = 0;
}
uint256 public total = 0;
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(
address airline,
string flight,
uint256 timestamp,
uint256 factor_numerator,
uint256 factor_denominator
)external requireIsOperational requireIsAuthorized {
//get all the insurees
bytes32 flightkey = getKeyOfFlight(airline, flight, timestamp);
address[] storage insurees = airlineinsurees[flightkey];
for (uint8 i = 0; i < insurees.length; i++) {
address passenger = insurees[i];
uint256 payout;
uint256 amount = amountOfInsurance[passenger][flightkey];
uint256 paid = payoutOfInsurance[flightkey][passenger];
if (paid == 0) {
payout = amount.mul(factor_numerator).div(factor_denominator);
payoutOfInsurance[flightkey][passenger] = payout;
balance[passenger] += payout;
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(
address airline,
string flight,
uint256 ts,
address passenger,
uint256 payout
) external requireIsOperational requireIsAuthorized {
bytes32 flightkey = getKeyOfFlight(airline, flight, ts);
payoutOfInsurance[flightkey][passenger] = payout;
balance[passenger] += payout;
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
payable
{
}
function getKeyOfFlight
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
|
Transfers eligible payout funds to insuree/
|
function pay(
address airline,
string flight,
uint256 ts,
address passenger,
uint256 payout
) external requireIsOperational requireIsAuthorized {
bytes32 flightkey = getKeyOfFlight(airline, flight, ts);
payoutOfInsurance[flightkey][passenger] = payout;
balance[passenger] += payout;
}
| 1,783,614
|
./full_match/137/0x9D5b588E5DaAC8055886D055418425c96faF9F56/sources/Special_Pool_V2.sol
|
reward = (pendingReward.div(90 days).mul(time));
|
function calculateRewards(address _stakerAddress) public view returns(uint256 reward) {
UserData storage _userData = userData[_stakerAddress];
_userData.user == _stakerAddress;
uint256 time = block.timestamp.sub(_userData.intialTimestamp);
if (block.timestamp <= _userData.intialTimestamp.add(30 days)) {
uint256 pendingReward = (_userData.tokenQuantity.mul(ENTRY_RATE))/100E18;
uint256 yearly = (pendingReward / 365 days);
reward = (yearly.mul(time));
return reward;
}
if (block.timestamp >= _userData.intialTimestamp.add(30 days) && block.timestamp <= _userData.intialTimestamp.add(90 days)) {
uint256 pendingReward = (_userData.tokenQuantity.mul(DAYS30_RATE))/100E18;
uint256 yearly = (pendingReward / 365 days);
reward = (yearly.mul(time));
return reward;
}
if (block.timestamp > _userData.intialTimestamp.add(90 days)) {
uint256 pendingReward = (_userData.tokenQuantity.mul(YEAR_RATE))/100E18;
uint256 yearly = (pendingReward / 365 days);
reward = (yearly.mul(time));
return reward;
}
}
| 4,773,755
|
// File: contracts/VeloxTransferHelper.sol
// SPDX-FileCopyrightText: © 2020 Velox <code@velox.global>
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.8.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library VeloxTransferHelper {
function safeApprove(address token, address to, uint value) internal {
require(token != address(0), 'VeloxTransferHelper: ZERO_ADDRESS');
require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS');
// 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))), 'VeloxTransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
require(token != address(0), 'VeloxTransferHelper: ZERO_ADDRESS');
require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS');
// 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))), 'VeloxTransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
require(token != address(0), 'VeloxTransferHelper: TOKEN_ZERO_ADDRESS');
require(from != address(0), 'VeloxTransferHelper: FROM_ZERO_ADDRESS');
require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS');
// 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))), 'VeloxTransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS');
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: contracts/interfaces/IERC20.sol
pragma solidity >=0.8.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File: contracts/interfaces/IERC20NONStandard.sol
pragma solidity >=0.8.0;
/**
* @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
*/
abstract contract IERC20NONStandard {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
uint256 public totalSupply;
function balanceOf(address owner) virtual public view returns (uint256 balance);
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC20 specification
/// will return Whether the transfer was successful or not
function transfer(address to, uint256 value) virtual public;
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC20 specification
/// will return Whether the transfer was successful or not
function transferFrom(address from, address to, uint256 value) virtual public;
function approve(address spender, uint256 value) virtual public returns (bool success);
function allowance(address owner, address spender) virtual public view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/SwapExceptions.sol
pragma solidity >=0.8.0;
contract SwapExceptions {
event SwapException(uint exception, uint info, uint detail);
enum Exception {
NO_ERROR,
GENERIC_ERROR,
UNAUTHORIZED,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW,
DIVISION_BY_ZERO,
BAD_INPUT,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_TRANSFER_FAILED,
MARKET_NOT_SUPPORTED,
SUPPLY_RATE_CALCULATION_FAILED,
BORROW_RATE_CALCULATION_FAILED,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_OUT_FAILED,
INSUFFICIENT_LIQUIDITY,
INSUFFICIENT_BALANCE,
INVALID_COLLATERAL_RATIO,
MISSING_ASSET_PRICE,
EQUITY_INSUFFICIENT_BALANCE,
INVALID_CLOSE_AMOUNT_REQUESTED,
ASSET_NOT_PRICED,
INVALID_LIQUIDATION_DISCOUNT,
INVALID_COMBINED_RISK_PARAMETERS,
ZERO_ORACLE_ADDRESS,
CONTRACT_PAUSED
}
/*
* Note: Reason (but not Exception) is kept in alphabetical order
* This is because Reason grows significantly faster, and
* the order of Exception has some meaning, while the order of Reason
* is arbitrary.
*/
enum Reason {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
BORROW_ACCOUNT_SHORTFALL_PRESENT,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_AMOUNT_LIQUIDITY_SHORTFALL,
BORROW_AMOUNT_VALUE_CALCULATION_FAILED,
BORROW_CONTRACT_PAUSED,
BORROW_MARKET_NOT_SUPPORTED,
BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
BORROW_ORIGINATION_FEE_CALCULATION_FAILED,
BORROW_TRANSFER_OUT_FAILED,
EQUITY_WITHDRAWAL_AMOUNT_VALIDATION,
EQUITY_WITHDRAWAL_CALCULATE_EQUITY,
EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK,
EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED,
LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED,
LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED,
LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH,
LIQUIDATE_CONTRACT_PAUSED,
LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET,
LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET,
LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET,
LIQUIDATE_FETCH_ASSET_PRICE_FAILED,
LIQUIDATE_TRANSFER_IN_FAILED,
LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_CONTRACT_PAUSED,
REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_ASSET_PRICE_CHECK_ORACLE,
SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_ORACLE_OWNER_CHECK,
SET_ORIGINATION_FEE_OWNER_CHECK,
SET_PAUSED_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RISK_PARAMETERS_OWNER_CHECK,
SET_RISK_PARAMETERS_VALIDATION,
SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED,
SUPPLY_CONTRACT_PAUSED,
SUPPLY_MARKET_NOT_SUPPORTED,
SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED,
SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
SUPPLY_TRANSFER_IN_FAILED,
SUPPLY_TRANSFER_IN_NOT_POSSIBLE,
SUPPORT_MARKET_FETCH_PRICE_FAILED,
SUPPORT_MARKET_OWNER_CHECK,
SUPPORT_MARKET_PRICE_CHECK,
SUSPEND_MARKET_OWNER_CHECK,
WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED,
WITHDRAW_ACCOUNT_SHORTFALL_PRESENT,
WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL,
WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED,
WITHDRAW_CAPACITY_CALCULATION_FAILED,
WITHDRAW_CONTRACT_PAUSED,
WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED,
WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
WITHDRAW_TRANSFER_OUT_FAILED,
WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE
}
/**
* @dev report a known exception
*/
function raiseException(Exception exception, Reason reason) internal returns (uint) {
emit SwapException(uint(exception), uint(reason), 0);
return uint(exception);
}
/**
* @dev report an opaque error from an upgradeable collaborator contract
*/
function raiseGenericException(Reason reason, uint genericException) internal returns (uint) {
emit SwapException(uint(Exception.GENERIC_ERROR), uint(reason), genericException);
return uint(Exception.GENERIC_ERROR);
}
}
// File: contracts/Swappable.sol
pragma solidity 0.8.0;
/**
* @title Swappable Interface
*/
contract Swappable is SwapExceptions {
/**
* @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and
* whether or not `from` has a balance of at least `amount`. Does NOT do a transfer.
*/
function checkTransferIn(address asset, address from, uint amount) internal view returns (Exception) {
IERC20 token = IERC20(asset);
if (token.allowance(from, address(this)) < amount) {
return Exception.TOKEN_INSUFFICIENT_ALLOWANCE;
}
if (token.balanceOf(from) < amount) {
return Exception.TOKEN_INSUFFICIENT_BALANCE;
}
return Exception.NO_ERROR;
}
/**
* @dev This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address asset, address from, uint amount) internal returns (Exception) {
IERC20NONStandard token = IERC20NONStandard(asset);
bool result;
// Should we use Helper.safeTransferFrom?
require(token.allowance(from, address(this)) >= amount, 'Not enough allowance from client');
token.transferFrom(from, address(this), amount);
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Exception.TOKEN_TRANSFER_FAILED;
}
return Exception.NO_ERROR;
}
/**
* @dev Checks balance of this contract in asset
*/
function getCash(address asset) internal view returns (uint) {
IERC20 token = IERC20(asset);
return token.balanceOf(address(this));
}
/**
* @dev Checks balance of `from` in `asset`
*/
function getBalanceOf(address asset, address from) internal view returns (uint) {
IERC20 token = IERC20(asset);
return token.balanceOf(from);
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address asset, address to, uint amount) internal returns (Exception) {
IERC20NONStandard token = IERC20NONStandard(asset);
bool result;
token.transfer(to, amount);
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
result := not(0) // set result to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
result := mload(0) // Set `result = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
if (!result) {
return Exception.TOKEN_TRANSFER_OUT_FAILED;
}
return Exception.NO_ERROR;
}
}
// File: contracts/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 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 payable(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;
}
}
// File: contracts/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 () {
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;
}
}
// File: contracts/interfaces/IVeloxSwapV3.sol
pragma solidity >=0.8.0;
interface IVeloxSwapV3 {
function withdrawToken(address token, uint256 amount) external;
function withdrawETH(uint256 amount) external;
function sellExactTokensForTokens(
string calldata exchange,
uint256 strategyId,
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 tokenInAmount,
uint256 minTokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline) external returns (uint256 amountOut);
function sellExactTokensForTokens(
string calldata exchange,
uint256 strategyId,
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 tokenInAmount,
uint256 minTokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline,
uint estimatedGasFundingCost) external returns (uint256 amountOut);
function sellTokensForExactTokens(
string calldata exchange,
uint256 strategyId,
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 maxTokenInAmount,
uint256 tokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline) external returns (uint256 amountIn);
function sellTokensForExactTokens(
string calldata exchange,
uint256 strategyId,
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 maxTokenInAmount,
uint256 tokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline,
uint estimatedGasFundingCost) external returns (uint256 amountIn);
function fundGasCost(uint256 strategyId, address seller, bytes32 txHash, uint256 wethAmount) external;
}
// File: contracts/BackingStore.sol
pragma solidity >=0.8.0;
abstract contract BackingStore {
address public MAIN_CONTRACT;
address public UNISWAP_FACTORY_ADDRESS = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address public UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
address public ADMIN_ADDRESS;
}
// File: contracts/lib/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: contracts/lib/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: contracts/lib/AccessControl.sol
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 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 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 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 {
require(hasRole(getRoleAdmin(role), _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 override {
require(hasRole(getRoleAdmin(role), _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 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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = 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());
}
}
}
// File: contracts/AccessManager.sol
pragma solidity 0.8.0;
contract AccessManager is AccessControl{
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/**
* @dev Throws if called by any account other than the admin.
*/
modifier hasAdminRole() {
require(hasRole(ADMIN_ROLE, _msgSender()), "VELOXSWAP: NOT_ADMIN");
_;
}
}
// File: contracts/VeloxSwapV3.sol
pragma solidity 0.8.0;
/**
* @title VeloxSwap based on algorithmic conditional trading exeuctions
*/
abstract contract VeloxSwapV3 is BackingStore, Ownable, Swappable, IVeloxSwapV3, AccessManager {
function setUpAdminRole(address _c) public onlyOwner returns (bool succeeded) {
require(_c != owner(), "VELOXPROXY_ADMIN_OWNER");
_setupRole(ADMIN_ROLE, _c);
return true;
}
function setRootRole() public onlyOwner returns (bool succeeded) {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
return true;
}
function grantAdminRole(address _c) public onlyOwner returns (bool succeeded) {
require(_c != owner(), "VELOXPROXY_ADMIN_OWNER");
grantRole(ADMIN_ROLE, _c);
return true;
}
function revokeAdminRole(address _c) public onlyOwner returns (bool succeeded) {
require(_c != owner(), "VELOXPROXY_ADMIN_OWNER");
revokeRole(ADMIN_ROLE, _c);
return true;
}
struct SwapInput {
address seller;
address tokenInAddress;
address tokenOutAddress;
uint256 tokenInAmount;
uint256 tokenOutAmount;
uint16 feeFactor;
bool takeFeeFromInput;
uint256 deadline;
}
address private gasFundingTokenAddress;
uint constant FEE_SCALE = 10000;
uint constant GAS_FUNDING_ESTIMATED_GAS = 26233;
event ValueSwapped(uint256 indexed strategyId, address indexed seller, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut);
event GasFunded(uint256 indexed strategyId, address indexed seller, bytes32 indexed txHash, uint256 gasCost);
event GasFundingTokenChanged(address oldValue, address newValue);
event ExchangeRegistered(string indexed exchange, address indexed routerAddress);
function setGasFundingTokenAddress(address tokenAddress) external onlyOwner {
require(tokenAddress != address(0), "VELOXSWAP: ZERO_GAS_FUNDING_TOKEN_ADDRESS");
address oldValue = gasFundingTokenAddress;
gasFundingTokenAddress = tokenAddress;
emit GasFundingTokenChanged(oldValue, gasFundingTokenAddress);
}
function getGasFundingTokenAddress() public view returns (address) {
return gasFundingTokenAddress;
}
function setKnownExchange(string calldata exchangeName, address routerAddress) onlyOwner external virtual {
require(routerAddress != address(0), "VELOXSWAP: INVALID_ROUTER_ZERO_ADDRESS");
_setKnownExchange(exchangeName, routerAddress);
emit ExchangeRegistered(exchangeName, routerAddress);
}
function withdrawToken(address token, uint256 amount) onlyOwner override external {
VeloxTransferHelper.safeTransfer(token, msg.sender, amount);
}
function withdrawETH(uint256 amount) onlyOwner override external {
VeloxTransferHelper.safeTransferETH(msg.sender, amount);
}
function fundGasCost(uint256 strategyId, address seller, bytes32 txHash, uint256 wethAmount) hasAdminRole override external {
require(txHash.length > 0, "VELOXSWAP: INVALID_TX_HASH");
_fundGasCost(strategyId, seller, txHash, wethAmount);
}
function _fundGasCost(uint256 strategyId, address seller, bytes32 txHash, uint256 wethAmount) private {
VeloxTransferHelper.safeTransferFrom(gasFundingTokenAddress, seller, _msgSender(), wethAmount);
emit GasFunded(strategyId, seller, txHash, wethAmount);
}
/**
* @dev This function should ONLY be executed when algorithmic conditons are met
* function sellExactTokensForTokens
* @param exchange string name of a existing exchange in routersByName
* @param strategyId uint256 - strategy ID
* @param seller address
* @param tokenInAddress address
* @param tokenOutAddress address
* @param tokenInAmount uint256
* @param minTokenOutAmount uint256
* @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee
* @param takeFeeFromInput bool
* @param deadline uint256 - UNIX timestamp
* @param estimatedGasFundingCost uint - estimated gas for gas funding transaction
*/
function sellExactTokensForTokens(
string calldata exchange,
uint256 strategyId,
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 tokenInAmount,
uint256 minTokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline,
uint estimatedGasFundingCost
) override hasAdminRole public returns (uint256 amountOut) {
uint256 initialGas = gasleft();
SwapInput memory input = SwapInput({
seller: seller, tokenInAddress: tokenInAddress,
tokenOutAddress: tokenOutAddress,
tokenInAmount: tokenInAmount,
tokenOutAmount: minTokenOutAmount,
feeFactor: feeFactor,
takeFeeFromInput: takeFeeFromInput,
deadline: deadline });
( , amountOut) = swapTokens(exchange, strategyId, input, true);
// Not sure if it should be 0 or just minus something
if (isTakingOutputFeeInGasToken(input)) {
estimatedGasFundingCost = 0;
}
uint256 gasCost = (initialGas - gasleft() + estimatedGasFundingCost) * tx.gasprice;
bytes32 txHash;
_fundGasCost(strategyId, seller, txHash, gasCost);
}
/**
* @dev This function should ONLY be executed when algorithmic conditons are met
* function sellExactTokensForTokens
* @param exchange string name of a existing exchange in routersByName
* @param strategyId uint256 - strategy ID
* @param seller address
* @param tokenInAddress address
* @param tokenOutAddress address
* @param tokenInAmount uint256
* @param minTokenOutAmount uint256
* @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee
* @param takeFeeFromInput bool
* @param deadline uint256 - UNIX timestamp
*/
function sellExactTokensForTokens(
string calldata exchange,
uint256 strategyId,
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 tokenInAmount,
uint256 minTokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline
) override hasAdminRole public returns (uint256 amountOut) {
amountOut = sellExactTokensForTokens(exchange, strategyId, seller, tokenInAddress, tokenOutAddress, tokenInAmount, minTokenOutAmount, feeFactor, takeFeeFromInput, deadline, GAS_FUNDING_ESTIMATED_GAS);
}
/**
* @dev This function should ONLY be executed when algorithmic conditons are met
* function sellTokensForExactTokens
* @param exchange string name of a existing exchange in routersByName
* @param strategyId uint256 - strategy ID
* @param seller address
* @param tokenInAddress address
* @param tokenOutAddress address
* @param maxTokenInAmount uint256
* @param tokenOutAmount uint256
* @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee
* @param takeFeeFromInput bool
* @param deadline uint256 - UNIX timestamp
* @param estimatedGasFundingCost uint - estimated gas for gas funding transaction
*/
function sellTokensForExactTokens(
string calldata exchange,
uint256 strategyId,
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 maxTokenInAmount,
uint256 tokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline,
uint estimatedGasFundingCost) override hasAdminRole public returns (uint256 amountIn) {
uint256 initialGas = gasleft();
SwapInput memory input = SwapInput({
seller: seller, tokenInAddress: tokenInAddress,
tokenOutAddress: tokenOutAddress,
tokenInAmount: maxTokenInAmount,
tokenOutAmount: tokenOutAmount,
feeFactor: feeFactor,
takeFeeFromInput: takeFeeFromInput,
deadline: deadline });
(amountIn, ) = swapTokens(exchange, strategyId, input, false);
// Not sure if it should be 0 or just minus something
if (isTakingOutputFeeInGasToken(input)) {
estimatedGasFundingCost = 0;
}
uint256 gasCost = (initialGas - gasleft() + estimatedGasFundingCost) * tx.gasprice;
bytes32 txHash;
_fundGasCost(strategyId, seller, txHash, gasCost);
}
/**
* @dev This function should ONLY be executed when algorithmic conditons are met
* function sellTokensForExactTokens
* @param exchange string name of a existing exchange in routersByName
* @param strategyId uint256 - strategy ID
* @param seller address
* @param tokenInAddress address
* @param tokenOutAddress address
* @param maxTokenInAmount uint256
* @param tokenOutAmount uint256
* @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee
* @param takeFeeFromInput bool
* @param deadline uint256 - UNIX timestamp
*/
function sellTokensForExactTokens(
string calldata exchange,
uint256 strategyId,
address seller,
address tokenInAddress,
address tokenOutAddress,
uint256 maxTokenInAmount,
uint256 tokenOutAmount,
uint16 feeFactor,
bool takeFeeFromInput,
uint256 deadline) override hasAdminRole public returns (uint256 amountIn) {
amountIn = sellTokensForExactTokens(exchange, strategyId, seller, tokenInAddress, tokenOutAddress, maxTokenInAmount, tokenOutAmount, feeFactor, takeFeeFromInput, deadline, GAS_FUNDING_ESTIMATED_GAS);
}
function swapTokens(string calldata exchange, uint256 strategyId, SwapInput memory input, bool exactIn) private returns (uint256 amountIn, uint256 amountOut) {
uint256 amountInForSwap;
uint256 amountOutForSwap;
address swapTargetAddress;
(amountInForSwap, amountOutForSwap, swapTargetAddress)
= prepareSwap(exchange, input);
uint actualAmountOut;
// Execute the swap
(amountIn, actualAmountOut) = doSwap(exchange, input.tokenInAddress, input.tokenOutAddress, amountInForSwap, amountOutForSwap, swapTargetAddress, input.deadline, exactIn);
// Take the fee from the output if not taken from the input
if (!input.takeFeeFromInput) {
amountOut = takeOutputFee(actualAmountOut, input.feeFactor, input.tokenOutAddress, input.seller);
}
emit ValueSwapped(strategyId, input.seller, input.tokenInAddress, input.tokenOutAddress, input.tokenInAmount, amountOut);
}
function prepareSwap(string calldata exchange, SwapInput memory input) private returns (uint256 amountInForSwap, uint256 amountOurForSwap, address targetAddress) {
// Sanity checks
validateInput(input.seller, input.tokenInAddress, input.tokenOutAddress, input.tokenInAmount, input.tokenOutAmount, input.feeFactor, input.deadline);
// Be 100% sure there's available allowance in this token contract
Exception exception = doTransferIn(input.tokenInAddress, input.seller, input.tokenInAmount);
require(exception == Exception.NO_ERROR, 'VELOXSWAP: ALLOWANCE_TOO_LOW');
// Checking In/Out reserves
checkLiquidity(exchange, input.tokenInAddress, input.tokenOutAddress, input.tokenOutAmount);
// Fee
(amountInForSwap, amountOurForSwap, targetAddress) = adjustInputBasedOnFee(input.takeFeeFromInput, input.feeFactor, input.tokenInAmount, input.tokenOutAmount, input.seller);
}
function validateInput(address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, uint256 deadline) private view {
require(deadline >= block.timestamp, 'VELOXSWAP: EXPIRED');
require(feeFactor <= 30, 'VELOXSWAP: FEE_OVER_03_PERCENT');
require(gasFundingTokenAddress != address(0), 'VELOXSWAP: GAS_FUNDING_ADDRESS_NOT_FOUND');
require (seller != address(0) &&
tokenInAddress != address(0) &&
tokenOutAddress != address(0) &&
tokenInAmount > 0 &&
tokenOutAmount > 0,
'VELOXSWAP: ZERO_DETECTED');
}
/**
* @dev Adjust input values based on the fee strategy
* @param takeFeeFromInput bool
* @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee
* @param amountIn uint256
* @param amountOut uint256
* @param sellerAddress address
*/
function adjustInputBasedOnFee(bool takeFeeFromInput, uint16 feeFactor, uint256 amountIn, uint256 amountOut, address sellerAddress) private view
returns (uint256 amountInForSwap, uint256 amountOurForSwap, address targetAddress) {
// Take fee from input
if (takeFeeFromInput) {
// Use less tokens for swap so we can keep the difference and make one less transfer
amountInForSwap = deductFee(amountIn, feeFactor);
amountOurForSwap = deductFee(amountOut, feeFactor);
// If we took fee from the input, transfer the result directly to client,
// otherwise, transfer to contract address so we can take fee from output
targetAddress = sellerAddress;
} else {
amountInForSwap = amountIn;
amountOurForSwap = amountOut;
targetAddress = address(this);
}
}
function doSwap(string calldata exchange, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, address targetAddress, uint256 deadline, bool exactIn) private returns (uint amountIn, uint amountOut) {
// Safely Approve UNISWAP V2 Router for token amount
safeApproveExchangeRouter(exchange, tokenInAddress, tokenInAmount);
// Path
address[] memory path = new address[](2);
path[0] = tokenInAddress;
path[1] = tokenOutAddress;
uint[] memory amounts;
if (exactIn) {
amounts = swapExactTokensForTokens(
exchange,
tokenInAmount,
minTokenOutAmount,
path,
targetAddress,
deadline
);
} else {
amounts = swapTokensForExactTokens(
exchange,
tokenInAmount,
minTokenOutAmount,
path,
targetAddress,
deadline
);
}
amountIn = amounts[0];
amountOut = amounts[amounts.length - 1];
}
function checkLiquidity(string calldata exchange, address tokenInAddress, address tokenOutAddress, uint256 minTokenOutAmount) private view {
(uint reserveIn, uint reserveOut) = getLiquidityForPair(exchange, tokenInAddress, tokenOutAddress);
require(reserveIn > 0 && reserveOut > 0, 'VELOXSWAP: ZERO_RESERVE_DETECTED');
require(reserveOut > minTokenOutAmount, 'VELOXSWAP: NOT_ENOUGH_LIQUIDITY');
}
function takeOutputFee(uint256 amountOut, uint16 feeFactor, address tokenOutAddress,
address from) private returns (uint256 transferredAmount) {
// Transfer to client address the value of amountOut - fee and keep difference in contract address
transferredAmount = deductFee(amountOut, feeFactor);
Exception exception = doTransferOut(tokenOutAddress, from, transferredAmount);
require (exception == Exception.NO_ERROR, 'VELOXSWAP: ERROR_GETTING_OUTPUT_FEE');
}
function deductFee(uint256 amount, uint16 feeFactor) private pure returns (uint256 deductedAmount) {
deductedAmount = (amount * (FEE_SCALE - feeFactor)) / FEE_SCALE;
}
function isTakingOutputFeeInGasToken(SwapInput memory input) private view returns (bool) {
return !input.takeFeeFromInput && input.tokenOutAddress == gasFundingTokenAddress;
}
/**
ABSTRACT METHODS
*/
function _setKnownExchange(string calldata exchangeName, address routerAddress) internal virtual;
function safeApproveExchangeRouter(string calldata exchange, address tokenInAddress, uint256 tokenInAmount) internal virtual;
function getLiquidityForPair(string calldata exchange, address tokenInAddress, address tokenOutAddress) view internal virtual returns (uint reserveIn, uint reserveOut);
function swapExactTokensForTokens(
string calldata exchange,
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) internal virtual returns (uint[] memory amounts);
function swapTokensForExactTokens(
string calldata exchange,
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) internal virtual returns (uint[] memory amounts);
}
// File: contracts/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.8.0;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.8.0;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.8.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/interfaces/IUniswapV2Factory.sol
pragma solidity >=0.8.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/EthereumVeloxSwapV3.sol
pragma solidity 0.8.0;
/**
* @title VeloxSwap based on algorithmic conditional trading exeuctions
*/
contract EthereumVeloxSwapV3 is VeloxSwapV3 {
mapping (string=>IUniswapV2Router02) routersByName;
function _setKnownExchange(string calldata exchangeName, address uniswapLikeRouterAddress) onlyOwner override internal {
require(uniswapLikeRouterAddress != address(0), "VELOXSWAP: INVALID_ROUTER_ADDRESS");
// Check how to validate this
IUniswapV2Router02 newRouter = IUniswapV2Router02(uniswapLikeRouterAddress);
require(address(newRouter.factory()) != address(0), "VELOXSWAP: INVALID_ROUTER");
routersByName[exchangeName] = newRouter;
}
function safeApproveExchangeRouter(string calldata exchange, address tokenInAddress, uint256 tokenInAmount) override internal {
IUniswapV2Router02 router = getRouter(exchange);
VeloxTransferHelper.safeApprove(tokenInAddress, address(router), tokenInAmount);
}
function getLiquidityForPair(string calldata exchange, address tokenInAddress, address tokenOutAddress) view internal override returns (uint reserveIn, uint reserveOut) {
IUniswapV2Router02 router = getRouter(exchange);
IUniswapV2Factory factory = IUniswapV2Factory(router.factory());
IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(tokenInAddress, tokenOutAddress));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
if (pair.token0() == tokenOutAddress) {
reserveIn = reserve1;
reserveOut = reserve0;
} else {
reserveIn = reserve0;
reserveOut = reserve1;
}
}
function getRouter(string memory exchange) private view returns (IUniswapV2Router02 router) {
router = routersByName[exchange];
require(address(router) != address(0), "VELOXSWAP: UNKNOWN_EXCHANGE");
}
function swapExactTokensForTokens(
string calldata exchange,
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) override internal virtual returns (uint[] memory amounts) {
IUniswapV2Router02 router = getRouter(exchange);
amounts = router.swapExactTokensForTokens(
amountIn,
amountOutMin,
path,
to,
deadline
);
}
function swapTokensForExactTokens(
string calldata exchange,
uint amountIn,
uint amountOutMin,
address[] memory path,
address to,
uint deadline
) override internal virtual returns (uint[] memory amounts) {
IUniswapV2Router02 router = getRouter(exchange);
amounts = router.swapTokensForExactTokens(
amountIn,
amountOutMin,
path,
to,
deadline
);
}
}
|
bytes4(keccak256(bytes('approve(address,uint256)')));
|
function safeApprove(address token, address to, uint value) internal {
require(token != address(0), 'VeloxTransferHelper: ZERO_ADDRESS');
require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS');
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'VeloxTransferHelper: APPROVE_FAILED');
}
| 10,282,638
|
./full_match/5/0x0a643414b7392BA34a6D464d0704178eB1A2868d/sources/project_/contracts/Payant.sol
|
Allows the deposits of funds into the contract for a specified invoice. Get the invoice Update the status
|
function deposit(uint256 _invoiceId) public payable returns (Invoice memory) {
require(_invoiceId >= 0, "Invalid invoice id.");
require(_invoiceId < nextInvoiceId, "Invalid invoice id.");
Invoice storage _invoice = invoices[_invoiceId];
require(_invoice.amount + DEPOSIT_FEES <= msg.value, "Amount not enough. ");
_invoice.status = InvoiceStatus.Paid;
_invoice.timeUpdated = block.timestamp;
_invoice.client = msg.sender;
COLLECTED_FEES += DEPOSIT_FEES;
emit onInvoice(_invoice);
return _invoice;
}
| 1,893,577
|
./full_match/1/0xFb8F626AD693ad0AF769ddB265084E8973f63a3C/sources/contracts/lib/FactSigs.sol
|
Produce the fact signature data for an account's code hash blockNum the block number to look at codeHash the codeHash for the account/
|
function accountCodeHashFactSigData(uint256 blockNum, bytes32 codeHash)
internal
pure
returns (bytes memory)
{
return abi.encode("AccountCodeHash", blockNum, codeHash);
}
| 4,930,627
|
./full_match/1/0x6e0d0C6a2445F21157dF96B2b6119BF757C42a5F/sources/contracts/MyContract.sol
|
Parses a revert reason that should contain the numeric quote
|
function parseRevertReason(bytes memory reason) private pure returns (uint256) {
if (reason.length != 32) {
if (reason.length < 68) revert('Unexpected error');
assembly {
reason := add(reason, 0x04)
}
revert(abi.decode(reason, (string)));
}
return abi.decode(reason, (uint256));
if (reason.length != 32) {
if (reason.length < 68) revert('Unexpected error');
assembly {
reason := add(reason, 0x04)
}
revert(abi.decode(reason, (string)));
}
return abi.decode(reason, (uint256));
}
| 8,369,733
|
// SPDX-License-Identifier: MIT
// Developer: @Brougkr
pragma solidity 0.8.10;
import '@openzeppelin/contracts/interfaces/IERC721Receiver.sol';
import '@openzeppelin/contracts/interfaces/IERC721.sol';
import '@openzeppelin/contracts/interfaces/IERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/security/Pausable.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import './IArtBlocks.sol';
contract CryptoCitizenMintPackRedeemer is Ownable, Pausable, ReentrancyGuard
{
address private immutable _ERC20_BRT_TokenAddress = 0xe5FDf72aC93796500e3A96163597DAFCC1C41C52; // BRT Ropsten Contract Address
address private immutable _BRTMULTISIG = 0xB96E81f80b3AEEf65CB6d0E280b15FD5DBE71937; // Bright Moments Multisig Address
address private immutable _ArtBlocksMintingContractAddress = 0xDd06d8483868Cd0C5E69C24eEaA2A5F2bEaFd42b; // ArtBlocks Ropsten Minting Contract
address private immutable _ArtBlocksCoreContractAddress = 0xbDdE08BD57e5C9fD563eE7aC61618CB2ECdc0ce0; // Artblocks Ropsten NFT Collection Contract
address private immutable _GoldenTicketCity5 = 0xC2A3c3543701009d36C0357177a62E0F6459e8A9; // Golden Ticket City 5
address private immutable _GoldenTicketCity6 = 0xE0D1Fa3fBd72db2eD179F80C0459B7dA93Fe4FE8; // Golden Ticket City 6
address private immutable _GoldenTicketCity7 = 0x762F5C8137C445164c53e138da33032C21F44D65; // Golden Ticket City 7
address private immutable _GoldenTicketCity8 = 0x0205f9cEb478FC77E2cDB77efD27B414dD31bAE5; // Golden Ticket City 8
address private immutable _GoldenTicketCity9 = 0x1b02C7f98e62dDF1aC434C372A282E862b03acC6; // Golden Ticket City 9
address private immutable _GoldenTicketCity10 = 0xB8d1611bE514202b60AdfcC8910F5A963E4Eb38D; // Golden Ticket City 10
address private immutable _MintPack = 0x96952728f070927201c67672B5ca1A79CABC6E67; // Mint Pack
uint256 private immutable _ArtBlocksProjectID = 0; // Galactican Project ID
uint256 private _index = 0;
// Approves 500,000 for purchasing
constructor()
{
__approveBRT(500000);
_transferOwnership(_BRTMULTISIG);
}
// Redeems CryptoCitizen Mint Pass
function redeemMintPack(uint256 passportTokenID) public nonReentrant whenNotPaused
{
// === Ensures Message Sender Is Owner of Mint Pass & Redeems Mint Pass ===
require(IERC721(_MintPack).ownerOf(passportTokenID) == msg.sender, "Sender Does Not Own Mint Pass With The Input Token ID");
IERC721(_MintPack).transferFrom(msg.sender, _BRTMULTISIG, passportTokenID);
// === Mints Galactican ===
uint256 _ArtBlocksTokenID = _mintGalactican();
IERC721(_ArtBlocksCoreContractAddress).transferFrom(address(this), msg.sender, _ArtBlocksTokenID);
// === Redeems Cities 5-10 ===
IERC721(_GoldenTicketCity5).transferFrom(_BRTMULTISIG, msg.sender, _index);
IERC721(_GoldenTicketCity6).transferFrom(_BRTMULTISIG, msg.sender, _index);
IERC721(_GoldenTicketCity7).transferFrom(_BRTMULTISIG, msg.sender, _index);
IERC721(_GoldenTicketCity8).transferFrom(_BRTMULTISIG, msg.sender, _index);
IERC721(_GoldenTicketCity9).transferFrom(_BRTMULTISIG, msg.sender, _index);
IERC721(_GoldenTicketCity10).transferFrom(_BRTMULTISIG, msg.sender, _index);
// === Increments Index ===
_index += 1;
}
// Returns Amount Of Mint Passes Redeemed
function readIndex() public view returns(uint256) { return _index; }
// Mints Galactican From ArtBlocks Minting Contract
function _mintGalactican() private returns (uint tokenID) { return IArtBlocks(_ArtBlocksMintingContractAddress).purchase(_ArtBlocksProjectID); }
// Withdraws ERC20 Tokens to Multisig
function __withdrawERC20(address tokenAddress) public onlyOwner
{
IERC20 erc20Token = IERC20(tokenAddress);
require(erc20Token.balanceOf(address(this)) > 0, "Zero Token Balance");
erc20Token.transfer(_BRTMULTISIG, erc20Token.balanceOf(address(this)));
}
// Approves BRT for Galactican Purchasing
function __approveBRT(uint256 amount) public onlyOwner { IERC20(_ERC20_BRT_TokenAddress).approve(_ArtBlocksMintingContractAddress, amount); }
// Withdraws Ether to Multisig
function __withdrawEther() public onlyOwner { payable(_BRTMULTISIG).transfer(address(this).balance); }
// Withdraws NFT to Multisig
function __withdrawNFT(address contractAddress, uint256 tokenID) public onlyOwner { IERC721(contractAddress).safeTransferFrom(address(this), _BRTMULTISIG, tokenID); }
// Pauses Functionality
function __pause() public onlyOwner { _pause(); }
// Unpauses Functionality
function __unpause() public onlyOwner { _unpause(); }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721Receiver.sol";
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT
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 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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/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() {
_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.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() {
_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.8.9;
//Contract Address for ArtBlocks: { 0x47e312d99C09Ce61A866c83cBbbbED5A4b9d33E7 }
interface IArtBlocks
{
function purchase(uint256 _projectId) payable external returns (uint256 tokenID);
}
// SPDX-License-Identifier: MIT
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
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
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
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 `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.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;
}
}
|
Mints Galactican From ArtBlocks Minting Contract
|
function _mintGalactican() private returns (uint tokenID) { return IArtBlocks(_ArtBlocksMintingContractAddress).purchase(_ArtBlocksProjectID); }
| 567,746
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/ICroak.sol";
/// @title Swampverse: Staking
/// @author @ryeshrimp
contract SwampStaking is Initializable, ERC721Holder, ReentrancyGuardUpgradeable, OwnableUpgradeable, PausableUpgradeable {
uint32 public constant SECONDS_IN_DAY = 1 days;
ICroak public rewardsToken;
IERC721Enumerable public swamperToken;
IERC721Enumerable public creatureToken;
struct UserInfo {
uint256 stakedCreatureCount;
uint256 stakedSwamperCount;
uint256 pendingRewards;
uint256 lastUpdate;
}
mapping(address => bool) controllers;
mapping(address => UserInfo) public userInfo;
mapping(uint256 => address) public stakedCreatures;
mapping(uint256 => address) public stakedSwampers;
uint256 public swamperRewardPerDay;
uint256 public creatureRewardPerDay;
function initialize(
address _swamperToken,
address _creatureToken,
address _rewardsToken,
uint256 _swamperRewardPerDay,
uint256 _creatureRewardPerDay
) public initializer {
__Ownable_init();
__Pausable_init();
swamperToken = IERC721Enumerable(_swamperToken);
creatureToken = IERC721Enumerable(_creatureToken);
rewardsToken = ICroak(_rewardsToken);
swamperRewardPerDay = _swamperRewardPerDay;
creatureRewardPerDay = _creatureRewardPerDay;
controllers[msg.sender] = true;
}
/// @notice Calculates live pending rewards of owner
/// @param account the address of owner
function pending(address account) public view returns (uint256) {
return userInfo[account].pendingRewards + (((block.timestamp - userInfo[account].lastUpdate) / SECONDS_IN_DAY) * (userInfo[account].stakedCreatureCount*creatureRewardPerDay)) + (((block.timestamp - userInfo[account].lastUpdate) / SECONDS_IN_DAY) * (userInfo[account].stakedSwamperCount*swamperRewardPerDay));
}
/// @notice Returns IDs of staked swampers by owner
/// @param account the address of owner
function stakedSwampersByOwner(address account) public view returns (uint256[] memory) {
uint256 supply = swamperToken.totalSupply();
uint256[] memory tmp = new uint256[](supply);
uint256 index;
for(uint tokenId = 1; tokenId <= supply; tokenId++) {
if (stakedSwampers[tokenId] == account) {
tmp[index] = tokenId;
index++;
}
}
uint256[] memory tokens = new uint256[](index);
for(uint i; i < index; i++) {
tokens[i] = tmp[i];
}
return tokens;
}
/// @notice Returns IDs of staked creatures by owner
/// @param account the address of owner
function stakedCreaturesByOwner(address account) public view returns (uint256[] memory) {
uint256 supply = creatureToken.totalSupply();
uint256[] memory tmp = new uint256[](supply);
uint256 index;
for(uint tokenId = 1; tokenId <= supply; tokenId++) {
if (stakedCreatures[tokenId] == account) {
tmp[index] = tokenId;
index++;
}
}
uint256[] memory tokens = new uint256[](index);
for(uint i; i < index; i++) {
tokens[i] = tmp[i];
}
return tokens;
}
/// @notice Set swamper, creature, or rewards address
/// @param _mode A number corresponding to the token type
/// 1 - swamperToken
/// 2 - creatureToken
/// 3 - rewardsToken
function setAddresses(uint8 _mode, address _address) external onlyOwner {
if (_mode == 1) swamperToken = IERC721Enumerable(_address);
else if (_mode == 2) creatureToken = IERC721Enumerable(_address);
else if (_mode == 3) rewardsToken = ICroak(_address);
else revert("SwampStaking.setAddresses: WRONG_MODE");
}
/// @notice Set rewards amount for NFTs
/// @param _mode A number corresponding to the token type
/// 1 - swamperRewardPerDay
/// 2 - creatureRewardPerDay
function setRewards(uint8 _mode, uint256 _amount) external onlyOwner {
if (_mode == 1) swamperRewardPerDay = _amount;
else if (_mode == 2) creatureRewardPerDay = _amount;
else revert("SwampStaking.setAwards: WRONG_MODE");
}
/// @notice Stakes user's Swamper NFTs
/// @param tokenIds The tokenIds of the Swamper NFTs which will be staked
function stakeSwampers(uint256[] memory tokenIds) external nonReentrant whenNotPaused updateReward(msg.sender) {
require(tokenIds.length > 0, "SwampStaking: No tokenIds provided");
uint256 amount;
for (uint256 i; i < tokenIds.length;) {
// Transfer user's NFTs to the staking contract
swamperToken.safeTransferFrom(msg.sender, address(this), tokenIds[i]);
// Increment the amount which will be staked
unchecked { amount++; }
// Save who is the staker/depositor of the token
stakedSwampers[tokenIds[i]] = msg.sender;
unchecked { i++; }
}
unchecked { userInfo[msg.sender].stakedSwamperCount += amount; }
emit Staked(msg.sender, amount, tokenIds, 0);
}
/// @notice Stakes user's Creature NFTs
/// @param tokenIds The tokenIds of the Creature NFTs which will be staked
function stakeCreatures(uint256[] memory tokenIds) external nonReentrant whenNotPaused updateReward(msg.sender) {
require(tokenIds.length > 0, "SwampStaking: No tokenIds provided");
uint256 amount;
for (uint256 i; i < tokenIds.length;) {
// Transfer user's NFTs to the staking contract
creatureToken.safeTransferFrom(msg.sender, address(this), tokenIds[i]);
// Increment the amount which will be staked
unchecked { amount++; }
// Save who is the staker/depositor of the token
stakedCreatures[tokenIds[i]] = msg.sender;
unchecked { i++; }
}
unchecked { userInfo[msg.sender].stakedCreatureCount += amount; }
emit Staked(msg.sender, amount, tokenIds, 1);
}
/// @notice Withdraws staked swamper NFTs
/// @param tokenIds The tokenIds of the NFTs which will be withdrawn
function withdrawSwampers(uint256[] memory tokenIds) external nonReentrant updateReward(msg.sender) {
require(tokenIds.length > 0, "SwampStaking: No tokenIds provided");
uint256 amount;
for (uint256 i; i < tokenIds.length;) {
// Check if the user who withdraws is the owner
require(stakedSwampers[tokenIds[i]] == msg.sender, "SwampStaking: Not the staker of the token");
// Transfer NFTs back to the owner
swamperToken.safeTransferFrom(address(this), msg.sender, tokenIds[i]);
// Increment the amount which will be withdrawn
amount++;
// Cleanup stakedAssets and paused info for the current tokenId
stakedSwampers[tokenIds[i]] = address(0);
unchecked { i++; }
}
userInfo[msg.sender].stakedSwamperCount -= amount;
emit Withdrawn(msg.sender, amount, tokenIds, 0);
}
/// @notice Withdraws staked creature NFTs
/// @param tokenIds The tokenIds of the NFTs which will be withdrawn
function withdrawCreatures(uint256[] memory tokenIds) external nonReentrant updateReward(msg.sender) {
require(tokenIds.length > 0, "SwampStaking: No tokenIds provided");
uint256 amount;
for (uint256 i; i < tokenIds.length;) {
// Check if the user who withdraws is the owner
require(stakedCreatures[tokenIds[i]] == msg.sender, "SwampStaking: Not the staker of the token");
// Transfer NFTs back to the owner
creatureToken.safeTransferFrom(address(this), msg.sender, tokenIds[i]);
// Increment the amount which will be withdrawn
unchecked { amount++; }
// Cleanup stakedAssets for the current tokenId
stakedCreatures[tokenIds[i]] = address(0);
unchecked { i++; }
}
unchecked { userInfo[msg.sender].stakedCreatureCount -= amount; }
emit Withdrawn(msg.sender, amount, tokenIds, 1);
}
/// @notice When paused, staking will be disabled but withdraw won't be
function pause() external onlyOwner {
_pause();
}
/// @notice When unpaused, staking will be re-enabled
function unpause() external onlyOwner {
_unpause();
}
/// @notice enables an address to pause token
/// @param controller the address to enable
function addController(address controller) external onlyOwner {
controllers[controller] = true;
}
/// @notice disables an address to pause token
/// @param controller the address to disbale
function removeController(address controller) external onlyOwner {
controllers[controller] = false;
}
/// @notice Retrieves pending reward of sender
function getReward() public nonReentrant {
uint256 reward = pending(msg.sender) * 1e18;
if (reward > 0) {
userInfo[msg.sender].pendingRewards = 0;
userInfo[msg.sender].lastUpdate = block.timestamp;
rewardsToken.mint(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
modifier updateReward(address account) {
userInfo[account].pendingRewards = pending(account);
userInfo[account].lastUpdate = block.timestamp;
_;
}
event Staked(address indexed user, uint256 amount, uint256[] tokenIds, uint nftType);
event Withdrawn(address indexed user, uint256 amount, uint256[] tokenIds, uint nftType);
event RewardPaid(address indexed user, uint256 reward);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.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 proxied contracts do not make use of 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));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 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 {
__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());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 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 {
__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);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(
IERC20Upgradeable 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(IERC20Upgradeable 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");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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);
/**
* @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/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// 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);
}
}
// SPDX-License-Identifier: MIT
// 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 ICroak {
function mint(address to, uint256 amount) external;
/**
* burns $CROAK from a holder
* @param from the holder of the $CROAK
* @param amount the amount of $CROAK to burn
*/
function burn(address from, uint256 amount) external;
/**
* enables an address to mint / burn
* @param controller the address to enable
*/
function addController(address controller) external returns(bool);
/**
* disables an address from minting / burning
* @param controller the address to disbale
*/
function removeController(address controller) external returns(bool);
/**
* @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);
}
// SPDX-License-Identifier: MIT
// 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 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
* ====
*
* [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 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: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
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 onlyInitializing {
}
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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// 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 IERC20Upgradeable {
/**
* @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);
}
// 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 (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 (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 (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;
}
}
|
Returns IDs of staked swampers by owner account the address of owner
|
function stakedSwampersByOwner(address account) public view returns (uint256[] memory) {
uint256 supply = swamperToken.totalSupply();
uint256[] memory tmp = new uint256[](supply);
uint256 index;
for(uint tokenId = 1; tokenId <= supply; tokenId++) {
if (stakedSwampers[tokenId] == account) {
tmp[index] = tokenId;
index++;
}
}
uint256[] memory tokens = new uint256[](index);
for(uint i; i < index; i++) {
tokens[i] = tmp[i];
}
return tokens;
}
| 1,127,459
|
./full_match/11155111/0x9b024EB9087f307C7dc19dFB0eC7e9D8F51D2E71/sources/contracts/HoneyCastContract.sol
|
remove ERC2981 from here if no royalties
|
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC2981, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
| 3,829,617
|
./full_match/1/0x16A2E3704AE5A46311d76BCFa5E42541171964F2/sources/contracts/WatchParts.sol
|
See {IERC165-supportsInterface}./
|
function supportsInterface(
bytes4 interfaceId
) public view virtual override(ERC721A, IERC721A, ERC2981) returns (bool) {
return super.supportsInterface(interfaceId);
}
| 16,560,075
|
// Sources flattened with hardhat v2.3.3 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v3.4.1
// 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);
}
// File @openzeppelin/contracts/math/SafeMath.sol@v3.4.1
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;
}
}
// File @openzeppelin/contracts/utils/Address.sol@v3.4.1
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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/SafeERC20.sol@v3.4.1
pragma solidity >=0.6.0 <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 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");
}
}
}
// File @openzeppelin/contracts/utils/Context.sol@v3.4.1
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;
}
}
// File @openzeppelin/contracts/access/Ownable.sol@v3.4.1
pragma solidity >=0.6.0 <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 () 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;
}
}
// File contracts/GameMining.sol
pragma solidity ^0.7.6;
pragma abicoder v2;
contract GameMining is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address private bouncer; // Used for allowing users to claim rewards by signing a message
IERC20 internal immutable mainToken;
bool public active;
uint256 public stakedFunds; // Amount of tokens staked by the users
uint256 public rewardsFunds; // Amount of tokens available for rewards
struct userInfo {
uint256 amountStaked;
uint256 totalRewards;
uint256 stakingStartTimestamp;
}
mapping(address => userInfo) public users;
constructor(IERC20 _tokenContract) {
mainToken = _tokenContract;
bouncer = msg.sender;
}
/************************/
/* MANAGEMENT FUNCTIONS */
/************************/
// The bouncer will be a hot wallet in our backend that will allow a user to withdraw a given amount of
// tokens based on the some logic related to the platform. It will take into account the in-game bets and
// the amount of tokens the user is staking in this contract.
function setBouncer(address _bouncer) external onlyOwner {
require(_bouncer != address(0), "Bouncer can't be the zero address");
bouncer = _bouncer;
}
event GameMiningStatusChange(bool newStatus);
// Enable or disable this contract's functionality. It does not include the staked funds, which always
// belong to the user.
function toggleGameMining() external onlyOwner {
bool newStatus = !active;
active = newStatus;
emit GameMiningStatusChange(newStatus);
}
// Deposit funds to be given to users as rewards.
function depositRewardsFunds(uint256 _amount) external onlyOwner {
require(_amount > 0, "Deposit amount must be positive");
rewardsFunds = rewardsFunds.add(_amount);
mainToken.safeTransferFrom(msg.sender, address(this), _amount);
}
// Collect any funds of the main token that are in the contract, including those that are sent
// accidentally to it. This does not include user funds that were deposited through staking.
function withdrawRewardsFunds() external onlyOwner {
uint256 amountToTransfer = rewardsFunds;
require(amountToTransfer > 0, "There are no funds to withdraw");
rewardsFunds = 0;
mainToken.safeTransfer(owner(), amountToTransfer);
}
/******************/
/* USER FUNCTIONS */
/******************/
event Stake(address indexed userAddress, uint256 amount);
// Deposit staking funds.
function stake(uint256 _amount) external {
require(active, "Game mining is not active");
require(_amount > 0, "Stake amount must be positive");
stakedFunds = stakedFunds.add(_amount);
uint256 userStakedAmount = users[msg.sender].amountStaked;
if (userStakedAmount == 0) {
users[msg.sender].stakingStartTimestamp = block.timestamp;
}
users[msg.sender].amountStaked = userStakedAmount.add(_amount);
mainToken.safeTransferFrom(msg.sender, address(this), _amount);
emit Stake(msg.sender, _amount);
}
event Unstake(address indexed userAddress, uint256 amount);
// Withdraw staking funds.
function unstake() external {
uint256 userStakedAmount = users[msg.sender].amountStaked;
require(userStakedAmount > 0, "There are no funds to unstake");
stakedFunds = stakedFunds.sub(userStakedAmount);
delete users[msg.sender];
mainToken.safeTransfer(msg.sender, userStakedAmount);
emit Unstake(msg.sender, userStakedAmount);
}
event ClaimRewards(address indexed userAddress, uint256 amount);
// Claim the rewards as stated by the backend. The received value is the total rewards accumulated since
// the first deposit. So, the amount to be awarded must be calculated from the new value and the one
// stored in the contract.
function claimRewards(
uint256 _newTotalRewards,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
require(active, "Game mining is not active");
uint256 stakingStartTimestamp = users[msg.sender].stakingStartTimestamp;
require(
stakingStartTimestamp != 0,
"Rewards are only for users that are staking"
);
require(
block.timestamp >= stakingStartTimestamp + 30 days,
"Rewards can only be claimed after 30 days"
);
bytes32 messageHash = keccak256(
abi.encodePacked(
address(this),
msg.sender,
stakingStartTimestamp,
_newTotalRewards
)
);
require(
bouncer ==
ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
messageHash
)
),
_v,
_r,
_s
),
"Why are you trying to steal our money? Just stop. You can't do it"
);
uint256 userTotalRewards = users[msg.sender].totalRewards;
require(
_newTotalRewards > userTotalRewards,
"There are no new rewards to claim"
);
uint256 amountToTransfer = _newTotalRewards.sub(userTotalRewards);
uint256 availableRewardsFunds = rewardsFunds; // Gas optimization
require(
availableRewardsFunds >= amountToTransfer,
"There are not enough funds for rewards. Please reach out to us"
);
users[msg.sender].totalRewards = _newTotalRewards;
rewardsFunds = availableRewardsFunds.sub(amountToTransfer);
mainToken.safeTransfer(msg.sender, amountToTransfer);
emit ClaimRewards(msg.sender, amountToTransfer);
}
}
|
Deposit staking funds.
|
function stake(uint256 _amount) external {
require(active, "Game mining is not active");
require(_amount > 0, "Stake amount must be positive");
stakedFunds = stakedFunds.add(_amount);
uint256 userStakedAmount = users[msg.sender].amountStaked;
if (userStakedAmount == 0) {
users[msg.sender].stakingStartTimestamp = block.timestamp;
}
users[msg.sender].amountStaked = userStakedAmount.add(_amount);
mainToken.safeTransferFrom(msg.sender, address(this), _amount);
emit Stake(msg.sender, _amount);
}
event Unstake(address indexed userAddress, uint256 amount);
| 9,914,660
|
./full_match/80001/0xA49F7B751e63aff042a69f868d2Ff9ECD9B372Ea/sources/contracts/contract.sol
|
basic info of a shop for the shop owner
|
function returnONEShop(address _add) public view returns (Shop memory) {
Shop memory shopp = shops[getShopId(_add)];
require(msg.sender==shopp.identity,"");
return shopp;
}
| 854,515
|
./partial_match/56/0xAb03a46A0e5cd32abF2071349B99Ba66cffCCc78/sources/MarketOracle.sol
|
Calculates the latest volatility. If any update to the price after the last calculation of volatility, recalculates and returns the new value./ recalculate the whole of intermediate values no need to recalculate reuse some of intermediate values and recalculate others for gas cost reduce. `_exTo` is same as `to` on the last volatility updated. Whenever volatility is updated, `to` is equal to or more than 25, so `_exTo` never goes below 25.
|
function getVolatility()
external
override
recoveryPhaseCheck
returns (uint256)
{
uint256 to;
uint256 from;
uint256 _exTo;
uint256 exFrom;
uint256 squareReturnSum;
PriceOracleInterface oracle = _activeOracle();
to = oracle.latestId();
from = to.sub(VOLATILITY_DATA_NUM, "data is too few").add(1);
_exTo = exTo;
if (needToRecalculateAll) {
squareReturnSum = _sumOfSquareReturn(oracle, from, to);
return lastCalculatedVolatility;
exFrom = _exTo.add(1).sub(VOLATILITY_DATA_NUM);
squareReturnSum = exSquareReturnSum
.add(_sumOfSquareReturn(oracle, _exTo, to))
.sub(_sumOfSquareReturn(oracle, exFrom, from));
}
uint256 time = oracle.getTimestamp(to).sub(oracle.getTimestamp(from));
uint256 s = squareReturnSum.mul(SECONDS_IN_YEAR).div(time);
uint256 v = _sqrt(s);
lastCalculatedVolatility = v;
exTo = to;
exVolatilityOracle = oracle;
exSquareReturnSum = squareReturnSum;
emit VolatilityCalculated(v);
return v;
}
| 11,078,861
|
pragma solidity 0.4.19;
import "./PayrollInterface.sol";
import "../node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol";
import "../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol";
contract Payroll is PayrollInterface {
using SafeMath for uint256;
struct Token {
address id;
uint256 exchangeRate;
}
struct Distribution {
uint256 amount;
uint lastAllocationTime;
}
struct Payment {
uint lastPaymentTime;
}
struct Employee {
address id;
uint256 yearlyEURSalary;
uint256 totalReceivedEUR;
uint256 totalDistributed;
mapping(address => uint256) allowedTokensMap;
mapping(address => Distribution) distributions;
mapping(address => Payment) payments;
mapping(address => Token) selectedTokens;
}
/* PAYROLL STATE */
enum State {
Allowed, Blocked
}
/* STATE VARIABLES */
State public paymentsState;
address public owner;
address public oracle;
uint256 public employeeCount;
mapping(address => Token) private supportedTokensMap;
mapping(address => Employee) private employeesMap;
mapping(address => address[]) private employeeTokenMap;
uint256 private totalYearlyEURSalary;
/* CONSTRUCTOR */
function Payroll(address _defaultOracle, address _tokenEURAddress, uint256 _EURExchangeRate)
public
{
owner = msg.sender;
paymentsState = State.Allowed;
oracle = _defaultOracle;
addSupportedToken(_tokenEURAddress, _EURExchangeRate);
}
/* EVENTS */
event LogSupportedTokenAdded(uint _time, address _newToken, uint256 _exchangeRate);
event LogEmployeeRemoved(address _employeeAddress);
event LogEmployeeAdded(address _employeeAddress, uint256 _yearlyEURSalary, uint256 _totalYearlyEURSalary);
event LogEmployeeSalaryUpdated(address indexed _employeeAddress, uint256 _oldYearlyEURSalary, uint256 _newYearlyEURSalary, uint256 _totalYearlyEURSalary);
event LogTokenAllowed(uint _time, address _employeeAddress, address _token, uint256 _exchangeRate);
event LogPaymentsAllowed(uint _time);
event LogPaymentsBlocked(uint _time);
event LogPaymentReceived(uint _time, address _employeeAddress, address _tokenAddress, uint256 _tokenPayment);
event LogExchangeRateUpdated(uint _time, address indexed _token, uint256 _oldRate, uint256 _newRate);
event LogOracleUpdated(uint _time, address _oldOracle, address _newOracle);
event LogTokenFundsAdded(uint _time, address _token, uint256 _value);
event LogPaymentDistributionUpdated(uint _time, address _employeeAddress, address _token, uint256 _totalDistributed);
/* ACCESS RULES */
modifier onlyByOwner() {
require(msg.sender == owner);
_;
}
modifier onlyByEmployee() {
require(exists(msg.sender));
_;
}
modifier onlyByOracle() {
require(msg.sender == oracle);
_;
}
modifier onlyIfSupported(address _token) {
require(supports(_token));
_;
}
modifier onlyIfAllowed(address _token) {
require(employeesMap[msg.sender].allowedTokensMap[_token] > 0);
_;
}
modifier onlyPositive(uint256 _value) {
require(_value > 0);
_;
}
modifier onlyRegistered(address _employeeAddress) {
require(exists(_employeeAddress));
_;
}
modifier onlyNotRegistered(address _employeeAddress) {
require(!exists(_employeeAddress));
_;
}
modifier onlyIfPayments(State _state) {
require(paymentsState == _state);
_;
}
/** FALLBACK ONLY **/
/* @dev default fallback function to prevent from sending ether to the contract
* @dev the contract works only with allowed tokens
*/
function() external payable {revert();}
/* @dev ERC223 token fallback function, rejects if token not supported */
function tokenFallback(address _from, uint256 _value, bytes _data)
public
onlyIfSupported(_from)
{
LogTokenFundsAdded(getTime(), _from, _value);
}
/* OWNER ONLY */
/* @dev Adds a supported token and exchange rates into the payroll */
function addSupportedToken(address _token, uint256 _exchangeRate)
public
onlyByOwner
{
require(tokenNotExists(_token) && _exchangeRate > 0);
supportedTokensMap[_token] = Token(_token, _exchangeRate);
LogSupportedTokenAdded(getTime(), supportedTokensMap[_token].id, supportedTokensMap[_token].exchangeRate);
}
/* @dev returns ERC20 tokens to contract owner */
function claimTokenFunds(address tokenAddress)
external
onlyByOwner {
ERC20Basic token = ERC20Basic(tokenAddress);
require(token.transfer(owner, token.balanceOf(this)));
}
/* @dev Calculates the monthly EUR amount spent in salaries */
function calculatePayrollBurnrate()
public
constant
onlyByOwner
returns (uint256)
{
return totalYearlyEURSalary.div(12);
}
/* @dev Calculates the days until the contract can run out of funds for the provided token */
function calculatePayrollRunway(address _token)
external
constant
onlyByOwner
onlyIfSupported(_token)
returns (uint256)
{
return (ERC20Basic(_token).balanceOf(this).div(supportedTokensMap[_token].exchangeRate)).div(totalYearlyEURSalary.div(365));
}
/* @dev Changes the contract state to Blocked, so employees won't able to receive payments */
function blockPayments()
external
onlyByOwner
{
paymentsState = State.Blocked;
LogPaymentsBlocked(getTime());
}
/* @dev Changes the contract state to Allowed, so employees are able to receive payments */
function allowPayments()
external
onlyByOwner
{
paymentsState = State.Allowed;
LogPaymentsAllowed(getTime());
}
function setOracle(address _newOracleAddress)
external
onlyByOwner
{
require(oracle != _newOracleAddress);
address oldOracle = oracle;
oracle = _newOracleAddress;
LogOracleUpdated(getTime(), oldOracle, oracle);
}
/* @dev Destroys the current contract with selfdestruct call and
* @dev sends remaining funds to the contract owner */
function destroy()
external
onlyByOwner
{
selfdestruct(owner);
//sends remaining funds back to owner of the contract
}
/* @dev Adds an employee into the payroll if it is not already registered and has valid tokens and salary */
function addEmployee(address _employeeAddress, uint256 _initialYearlyEURSalary)
external
onlyByOwner
onlyNotRegistered(_employeeAddress)
onlyPositive(_initialYearlyEURSalary)
{
employeeCount++;
totalYearlyEURSalary = totalYearlyEURSalary.add(_initialYearlyEURSalary);
employeesMap[_employeeAddress] = Employee(_employeeAddress, _initialYearlyEURSalary, 0, 0);
LogEmployeeAdded(_employeeAddress, _initialYearlyEURSalary, totalYearlyEURSalary);
}
/* @dev Gets the employee data if the employee is registered in the payroll */
function getEmployee(address _employeeAddress)
external constant
onlyByOwner
onlyRegistered(_employeeAddress)
returns (
uint256 _yearlyEURSalary,
uint256 _totalReceivedEUR,
address[] _allowedTokens)
{
Employee memory employee = employeesMap[_employeeAddress];
return (employee.yearlyEURSalary,
employee.totalReceivedEUR,
employeeTokenMap[_employeeAddress]);
}
/* @dev Removes the employee from the payroll if it is registered in the payroll */
function removeEmployee(address _employeeAddress)
external
onlyByOwner
onlyRegistered(_employeeAddress)
{
employeeCount = employeeCount - 1;
totalYearlyEURSalary = totalYearlyEURSalary.sub(employeesMap[_employeeAddress].yearlyEURSalary);
delete employeesMap[_employeeAddress];
delete employeeTokenMap[_employeeAddress];
LogEmployeeRemoved(_employeeAddress);
}
/* @dev Updated the employee annual salary if it is registered in the payroll */
function setEmployeeSalary(address _employeeAddress, uint256 _newYearlyEURSalary)
external
onlyByOwner
onlyRegistered(_employeeAddress)
onlyPositive(_newYearlyEURSalary)
{
uint256 oldSalary = employeesMap[_employeeAddress].yearlyEURSalary;
totalYearlyEURSalary = totalYearlyEURSalary.sub(oldSalary).add(_newYearlyEURSalary);
employeesMap[_employeeAddress].yearlyEURSalary = _newYearlyEURSalary;
LogEmployeeSalaryUpdated(_employeeAddress, oldSalary, _newYearlyEURSalary, totalYearlyEURSalary);
}
/* @dev Gets the total number of employees registered in the payroll */
function getEmployeeCount()
external constant
onlyByOwner
returns (uint256)
{
return employeeCount;
}
/* @dev Gets the employee payment details based on allowed token */
function getEmployeePayment(address _employeeAddress, address _token)
external
constant
onlyByOwner
onlyRegistered(_employeeAddress)
onlyIfSupported(_token)
onlyIfAllowed(_token)
returns (
uint256 _exchangeRate,
uint _lastAllocationTime,
uint _lastPaymentTime,
uint256 _distributedAmount)
{
Token memory token = employeesMap[_employeeAddress].selectedTokens[_token];
Payment memory payment = employeesMap[_employeeAddress].payments[_token];
Distribution memory distribution = employeesMap[_employeeAddress].distributions[_token];
return (token.exchangeRate,
distribution.lastAllocationTime,
payment.lastPaymentTime,
distribution.amount);
}
/* @dev Allows a given token for a given employee */
function allowToken(address _employeeAddress, address _token, uint256 _exchangeRate)
external
onlyByOwner
onlyRegistered(_employeeAddress)
onlyIfSupported(_token)
onlyPositive(_exchangeRate)
{
Employee storage employee = employeesMap[_employeeAddress];
supportedTokensMap[_token] = Token(_token, _exchangeRate);
employee.selectedTokens[_token] = supportedTokensMap[_token];
employeeTokenMap[_employeeAddress].push(_token);
employee.allowedTokensMap[_token] = 1;
LogTokenAllowed(getTime(), _employeeAddress, _token, _exchangeRate);
}
/* EMPLOYEE ONLY */
/* @dev Allows employees to set their tokens distribution for payments */
function determineAllocation(address _token, uint256 _newDistributionAmount)
external
onlyByEmployee
onlyIfPayments(State.Allowed)
onlyIfAllowed(_token)
{
require(_newDistributionAmount >= 0 && _newDistributionAmount <= employee.yearlyEURSalary.div(12));
Employee storage employee = employeesMap[msg.sender];
Distribution storage distribution = employee.distributions[_token];
require(getTime() - 6 * 4 weeks > distribution.lastAllocationTime);
uint256 oldAmount = distribution.amount;
distribution.amount = _newDistributionAmount;
distribution.lastAllocationTime = getTime();
employee.totalDistributed.sub(oldAmount);
employee.totalDistributed.add(_newDistributionAmount);
assert(employee.totalDistributed <= employee.yearlyEURSalary.div(12));
LogPaymentDistributionUpdated(getTime(), employee.id, _token, distribution.amount);
}
/* @dev Allows the employee to release the funds once a month*/
function payday(address _token)
external
onlyByEmployee
onlyIfPayments(State.Allowed)
onlyIfSupported(_token)
onlyIfAllowed(_token)
{
Employee storage employee = employeesMap[msg.sender];
Payment storage payment = employee.payments[_token];
require(getTime() - 1 * 4 weeks > payment.lastPaymentTime);
Distribution memory distribution = employee.distributions[_token];
uint256 monthlySalary = employee.yearlyEURSalary.div(12);
require(distribution.amount > 0 && distribution.amount <= monthlySalary);
uint256 tokenSalary = distribution.amount.div(supportedTokensMap[_token].exchangeRate);
uint256 tokenFunds = ERC20Basic(_token).balanceOf(this);
assert(monthlySalary.sub(distribution.amount) >= 0 && tokenSalary < tokenFunds);
payment.lastPaymentTime = getTime();
LogPaymentReceived(getTime(), msg.sender, _token, tokenSalary);
assert(ERC20Basic(_token).transfer(msg.sender, tokenSalary));
}
/* ORACLE ONLY */
/* @dev Updates the token exchange rates if supported and assumes we can trust 100% in the Oracle exchange rates */
function setExchangeRate(address _token, uint256 _newExchangeRate)
external
onlyByOracle
onlyIfSupported(_token)
{
//Updates the token in the supported tokens map
Token storage token = supportedTokensMap[_token];
uint256 oldRate = token.exchangeRate;
token.exchangeRate = _newExchangeRate;
LogExchangeRateUpdated(getTime(), _token, oldRate, token.exchangeRate);
}
/* HELPERS */
/* @dev Checks if the employee is registered in the payroll */
function exists(address _employeeAddress)
internal
constant
returns (bool)
{
return employeesMap[_employeeAddress].id != address(0x0);
}
/* @dev Checks if the token is accepted according to the payroll available tokens */
function supports(address _token)
internal
constant
returns (bool)
{
return supportedTokensMap[_token].id != address(0x0);
}
function tokenNotExists(address _token)
internal
constant
returns (bool)
{
return supportedTokensMap[_token].id == address(0x0);
}
function getTime()
internal
constant
returns (uint)
{
return now;
}
}
|
Adds an employee into the payroll if it is not already registered and has valid tokens and salary /
|
function addEmployee(address _employeeAddress, uint256 _initialYearlyEURSalary)
external
onlyByOwner
onlyNotRegistered(_employeeAddress)
onlyPositive(_initialYearlyEURSalary)
{
employeeCount++;
totalYearlyEURSalary = totalYearlyEURSalary.add(_initialYearlyEURSalary);
employeesMap[_employeeAddress] = Employee(_employeeAddress, _initialYearlyEURSalary, 0, 0);
LogEmployeeAdded(_employeeAddress, _initialYearlyEURSalary, totalYearlyEURSalary);
}
| 6,484,486
|
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title iOVM_CrossDomainMessenger
*/
interface iOVM_CrossDomainMessenger {
/**********
* Events *
**********/
event SentMessage(bytes message);
event RelayedMessage(bytes32 msgHash);
event FailedRelayedMessage(bytes32 msgHash);
/*************
* Variables *
*************/
function xDomainMessageSender() external view returns (address);
/********************
* Public Functions *
********************/
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes calldata _message,
uint32 _gasLimit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_CrossDomainMessenger } from
"../../iOVM/bridge/messaging/iOVM_CrossDomainMessenger.sol";
/**
* @title OVM_CrossDomainEnabled
* @dev Helper contract for contracts performing cross-domain communications
*
* Compiler used: defined by inheriting contract
* Runtime target: defined by inheriting contract
*/
contract OVM_CrossDomainEnabled {
/*************
* Variables *
*************/
// Messenger contract used to send and recieve messages from the other domain.
address public messenger;
/***************
* Constructor *
***************/
/**
* @param _messenger Address of the CrossDomainMessenger on the current layer.
*/
constructor(
address _messenger
) {
messenger = _messenger;
}
/**********************
* Function Modifiers *
**********************/
/**
* Enforces that the modified function is only callable by a specific cross-domain account.
* @param _sourceDomainAccount The only account on the originating domain which is
* authenticated to call this function.
*/
modifier onlyFromCrossDomainAccount(
address _sourceDomainAccount
) {
require(
msg.sender == address(getCrossDomainMessenger()),
"OVM_XCHAIN: messenger contract unauthenticated"
);
require(
getCrossDomainMessenger().xDomainMessageSender() == _sourceDomainAccount,
"OVM_XCHAIN: wrong sender of cross-domain message"
);
_;
}
/**********************
* Internal Functions *
**********************/
/**
* Gets the messenger, usually from storage. This function is exposed in case a child contract
* needs to override.
* @return The address of the cross-domain messenger contract which should be used.
*/
function getCrossDomainMessenger()
internal
virtual
returns (
iOVM_CrossDomainMessenger
)
{
return iOVM_CrossDomainMessenger(messenger);
}
/**
* Sends a message to an account on another domain
* @param _crossDomainTarget The intended recipient on the destination domain
* @param _message The data to send to the target (usually calldata to a function with
* `onlyFromCrossDomainAccount()`)
* @param _gasLimit The gasLimit for the receipt of the message on the target domain.
*/
function sendCrossDomainMessage(
address _crossDomainTarget,
uint32 _gasLimit,
bytes memory _message
)
internal
{
getCrossDomainMessenger().sendMessage(_crossDomainTarget, _message, _gasLimit);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol";
import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol";
import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol";
/* Library Imports */
import { ERC165Checker } from "@openzeppelin/contracts/introspection/ERC165Checker.sol";
import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol";
import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */
import { IL2StandardERC20 } from "../../../libraries/standards/IL2StandardERC20.sol";
/**
* @title OVM_L2StandardBridge
* @dev The L2 Standard bridge is a contract which works together with the L1 Standard bridge to
* enable ETH and ERC20 transitions between L1 and L2.
* This contract acts as a minter for new tokens when it hears about deposits into the L1 Standard
* bridge.
* This contract also acts as a burner of the tokens intended for withdrawal, informing the L1
* bridge to release L1 funds.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_L2StandardBridge is iOVM_L2ERC20Bridge, OVM_CrossDomainEnabled {
/********************************
* External Contract References *
********************************/
address public l1TokenBridge;
/***************
* Constructor *
***************/
/**
* @param _l2CrossDomainMessenger Cross-domain messenger used by this contract.
* @param _l1TokenBridge Address of the L1 bridge deployed to the main chain.
*/
constructor(
address _l2CrossDomainMessenger,
address _l1TokenBridge
)
OVM_CrossDomainEnabled(_l2CrossDomainMessenger)
{
l1TokenBridge = _l1TokenBridge;
}
/***************
* Withdrawing *
***************/
/**
* @inheritdoc iOVM_L2ERC20Bridge
*/
function withdraw(
address _l2Token,
uint256 _amount,
uint32 _l1Gas,
bytes calldata _data
)
external
override
virtual
{
_initiateWithdrawal(
_l2Token,
msg.sender,
msg.sender,
_amount,
_l1Gas,
_data
);
}
/**
* @inheritdoc iOVM_L2ERC20Bridge
*/
function withdrawTo(
address _l2Token,
address _to,
uint256 _amount,
uint32 _l1Gas,
bytes calldata _data
)
external
override
virtual
{
_initiateWithdrawal(
_l2Token,
msg.sender,
_to,
_amount,
_l1Gas,
_data
);
}
/**
* @dev Performs the logic for deposits by storing the token and informing the L2 token Gateway
* of the deposit.
* @param _l2Token Address of L2 token where withdrawal was initiated.
* @param _from Account to pull the deposit from on L2.
* @param _to Account to give the withdrawal to on L1.
* @param _amount Amount of the token to withdraw.
* param _l1Gas Unused, but included for potential forward compatibility considerations.
* @param _data Optional data to forward to L1. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function _initiateWithdrawal(
address _l2Token,
address _from,
address _to,
uint256 _amount,
uint32 _l1Gas,
bytes calldata _data
)
internal
{
// When a withdrawal is initiated, we burn the withdrawer's funds to prevent subsequent L2
// usage
IL2StandardERC20(_l2Token).burn(msg.sender, _amount);
// Construct calldata for l1TokenBridge.finalizeERC20Withdrawal(_to, _amount)
address l1Token = IL2StandardERC20(_l2Token).l1Token();
bytes memory message;
if (_l2Token == Lib_PredeployAddresses.OVM_ETH) {
message = abi.encodeWithSelector(
iOVM_L1StandardBridge.finalizeETHWithdrawal.selector,
_from,
_to,
_amount,
_data
);
} else {
message = abi.encodeWithSelector(
iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector,
l1Token,
_l2Token,
_from,
_to,
_amount,
_data
);
}
// Send message up to L1 bridge
sendCrossDomainMessage(
l1TokenBridge,
_l1Gas,
message
);
emit WithdrawalInitiated(l1Token, _l2Token, msg.sender, _to, _amount, _data);
}
/************************************
* Cross-chain Function: Depositing *
************************************/
/**
* @inheritdoc iOVM_L2ERC20Bridge
*/
function finalizeDeposit(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
)
external
override
virtual
onlyFromCrossDomainAccount(l1TokenBridge)
{
// Check the target token is compliant and
// verify the deposited token on L1 matches the L2 deposited token representation here
if (
ERC165Checker.supportsInterface(_l2Token, 0x1d1d8b63) &&
_l1Token == IL2StandardERC20(_l2Token).l1Token()
) {
// When a deposit is finalized, we credit the account on L2 with the same amount of
// tokens.
IL2StandardERC20(_l2Token).mint(_to, _amount);
emit DepositFinalized(_l1Token, _l2Token, _from, _to, _amount, _data);
} else {
// Either the L2 token which is being deposited-into disagrees about the correct address
// of its L1 token, or does not support the correct interface.
// This should only happen if there is a malicious L2 token, or if a user somehow
// specified the wrong L2 token address to deposit into.
// In either case, we stop the process here and construct a withdrawal
// message so that users can get their funds out in some cases.
// There is no way to prevent malicious token contracts altogether, but this does limit
// user error and mitigate some forms of malicious contract behavior.
bytes memory message = abi.encodeWithSelector(
iOVM_L1ERC20Bridge.finalizeERC20Withdrawal.selector,
_l1Token,
_l2Token,
_to, // switched the _to and _from here to bounce back the deposit to the sender
_from,
_amount,
_data
);
// Send message up to L1 bridge
sendCrossDomainMessage(
l1TokenBridge,
0,
message
);
emit DepositFailed(_l1Token, _l2Token, _from, _to, _amount, _data);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0;
pragma experimental ABIEncoderV2;
import "./iOVM_L1ERC20Bridge.sol";
/**
* @title iOVM_L1StandardBridge
*/
interface iOVM_L1StandardBridge is iOVM_L1ERC20Bridge {
/**********
* Events *
**********/
event ETHDepositInitiated (
address indexed _from,
address indexed _to,
uint256 _amount,
bytes _data
);
event ETHWithdrawalFinalized (
address indexed _from,
address indexed _to,
uint256 _amount,
bytes _data
);
/********************
* Public Functions *
********************/
/**
* @dev Deposit an amount of the ETH to the caller's balance on L2.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function depositETH (
uint32 _l2Gas,
bytes calldata _data
)
external
payable;
/**
* @dev Deposit an amount of ETH to a recipient's balance on L2.
* @param _to L2 address to credit the withdrawal to.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function depositETHTo (
address _to,
uint32 _l2Gas,
bytes calldata _data
)
external
payable;
/*************************
* Cross-chain Functions *
*************************/
/**
* @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the
* L1 ETH token. Since only the xDomainMessenger can call this function, it will never be called
* before the withdrawal is finalized.
* @param _from L2 address initiating the transfer.
* @param _to L1 address to credit the withdrawal to.
* @param _amount Amount of the ERC20 to deposit.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function finalizeETHWithdrawal (
address _from,
address _to,
uint _amount,
bytes calldata _data
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0;
pragma experimental ABIEncoderV2;
/**
* @title iOVM_L1ERC20Bridge
*/
interface iOVM_L1ERC20Bridge {
/**********
* Events *
**********/
event ERC20DepositInitiated (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event ERC20WithdrawalFinalized (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
/********************
* Public Functions *
********************/
/**
* @dev deposit an amount of the ERC20 to the caller's balance on L2.
* @param _l1Token Address of the L1 ERC20 we are depositing
* @param _l2Token Address of the L1 respective L2 ERC20
* @param _amount Amount of the ERC20 to deposit
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function depositERC20 (
address _l1Token,
address _l2Token,
uint _amount,
uint32 _l2Gas,
bytes calldata _data
)
external;
/**
* @dev deposit an amount of ERC20 to a recipient's balance on L2.
* @param _l1Token Address of the L1 ERC20 we are depositing
* @param _l2Token Address of the L1 respective L2 ERC20
* @param _to L2 address to credit the withdrawal to.
* @param _amount Amount of the ERC20 to deposit.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function depositERC20To (
address _l1Token,
address _l2Token,
address _to,
uint _amount,
uint32 _l2Gas,
bytes calldata _data
)
external;
/*************************
* Cross-chain Functions *
*************************/
/**
* @dev Complete a withdrawal from L2 to L1, and credit funds to the recipient's balance of the
* L1 ERC20 token.
* This call will fail if the initialized withdrawal from L2 has not been finalized.
*
* @param _l1Token Address of L1 token to finalizeWithdrawal for.
* @param _l2Token Address of L2 token where withdrawal was initiated.
* @param _from L2 address initiating the transfer.
* @param _to L1 address to credit the withdrawal to.
* @param _amount Amount of the ERC20 to deposit.
* @param _data Data provided by the sender on L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function finalizeERC20Withdrawal (
address _l1Token,
address _l2Token,
address _from,
address _to,
uint _amount,
bytes calldata _data
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0;
pragma experimental ABIEncoderV2;
/**
* @title iOVM_L2ERC20Bridge
*/
interface iOVM_L2ERC20Bridge {
/**********
* Events *
**********/
event WithdrawalInitiated (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event DepositFinalized (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event DepositFailed (
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
/********************
* Public Functions *
********************/
/**
* @dev initiate a withdraw of some tokens to the caller's account on L1
* @param _l2Token Address of L2 token where withdrawal was initiated.
* @param _amount Amount of the token to withdraw.
* param _l1Gas Unused, but included for potential forward compatibility considerations.
* @param _data Optional data to forward to L1. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function withdraw (
address _l2Token,
uint _amount,
uint32 _l1Gas,
bytes calldata _data
)
external;
/**
* @dev initiate a withdraw of some token to a recipient's account on L1.
* @param _l2Token Address of L2 token where withdrawal is initiated.
* @param _to L1 adress to credit the withdrawal to.
* @param _amount Amount of the token to withdraw.
* param _l1Gas Unused, but included for potential forward compatibility considerations.
* @param _data Optional data to forward to L1. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function withdrawTo (
address _l2Token,
address _to,
uint _amount,
uint32 _l1Gas,
bytes calldata _data
)
external;
/*************************
* Cross-chain Functions *
*************************/
/**
* @dev Complete a deposit from L1 to L2, and credits funds to the recipient's balance of this
* L2 token. This call will fail if it did not originate from a corresponding deposit in
* OVM_l1TokenGateway.
* @param _l1Token Address for the l1 token this is called with
* @param _l2Token Address for the l2 token this is called with
* @param _from Account to pull the deposit from on L2.
* @param _to Address to receive the withdrawal at
* @param _amount Amount of the token to withdraw
* @param _data Data provider by the sender on L1. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function finalizeDeposit (
address _l1Token,
address _l2Token,
address _from,
address _to,
uint _amount,
bytes calldata _data
)
external;
}
// 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.5.0 <0.8.0;
/**
* @title Lib_PredeployAddresses
*/
library Lib_PredeployAddresses {
address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000;
address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001;
address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002;
address internal constant ECDSA_CONTRACT_ACCOUNT = 0x4200000000000000000000000000000000000003;
address internal constant SEQUENCER_ENTRYPOINT = 0x4200000000000000000000000000000000000005;
address payable internal constant OVM_ETH = 0x4200000000000000000000000000000000000006;
// solhint-disable-next-line max-line-length
address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007;
address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008;
address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009;
// solhint-disable-next-line max-line-length
address internal constant EXECUTION_MANAGER_WRAPPER = 0x420000000000000000000000000000000000000B;
address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011;
address internal constant ERC1820_REGISTRY = 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24;
address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16 <0.8.0;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol";
interface IL2StandardERC20 is IERC20, IERC165 {
function l1Token() external returns (address);
function mint(address _to, uint256 _amount) external;
function burn(address _from, uint256 _amount) external;
event Mint(address indexed _account, uint256 _amount);
event Burn(address indexed _account, uint256 _amount);
}
// 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;
/**
* @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.5.0 <0.8.0;
/* Library Imports */
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */
import { OVM_ETH } from "../predeploys/OVM_ETH.sol";
import { OVM_L2StandardBridge } from "../bridge/tokens/OVM_L2StandardBridge.sol";
/**
* @title OVM_SequencerFeeVault
* @dev Simple holding contract for fees paid to the Sequencer. Likely to be replaced in the future
* but "good enough for now".
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_SequencerFeeVault {
/*************
* Constants *
*************/
// Minimum ETH balance that can be withdrawn in a single withdrawal.
uint256 public constant MIN_WITHDRAWAL_AMOUNT = 15 ether;
/*************
* Variables *
*************/
// Address on L1 that will hold the fees once withdrawn. Dynamically initialized within l2geth.
address public l1FeeWallet;
/***************
* Constructor *
***************/
/**
* @param _l1FeeWallet Initial address for the L1 wallet that will hold fees once withdrawn.
* Currently HAS NO EFFECT in production because l2geth will mutate this storage slot during
* the genesis block. This is ONLY for testing purposes.
*/
constructor(
address _l1FeeWallet
) {
l1FeeWallet = _l1FeeWallet;
}
/********************
* Public Functions *
********************/
function withdraw()
public
{
uint256 balance = OVM_ETH(Lib_PredeployAddresses.OVM_ETH).balanceOf(address(this));
require(
balance >= MIN_WITHDRAWAL_AMOUNT,
// solhint-disable-next-line max-line-length
"OVM_SequencerFeeVault: withdrawal amount must be greater than minimum withdrawal amount"
);
OVM_L2StandardBridge(Lib_PredeployAddresses.L2_STANDARD_BRIDGE).withdrawTo(
Lib_PredeployAddresses.OVM_ETH,
l1FeeWallet,
balance,
0,
bytes("")
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */
import { L2StandardERC20 } from "../../libraries/standards/L2StandardERC20.sol";
import { IWETH9 } from "../../libraries/standards/IWETH9.sol";
/**
* @title OVM_ETH
* @dev The ETH predeploy provides an ERC20 interface for ETH deposited to Layer 2. Note that
* unlike on Layer 1, Layer 2 accounts do not have a balance field.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_ETH is L2StandardERC20, IWETH9 {
/***************
* Constructor *
***************/
constructor()
L2StandardERC20(
Lib_PredeployAddresses.L2_STANDARD_BRIDGE,
address(0),
"Ether",
"ETH"
)
{}
/******************************
* Custom WETH9 Functionality *
******************************/
fallback() external payable {
deposit();
}
/**
* Implements the WETH9 deposit() function as a no-op.
* WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant
* deposit and withdraw functions for that use case can be found at L2StandardBridge.sol.
* This function allows developers to treat OVM_ETH as WETH without any modifications to their
* code.
*/
function deposit()
public
payable
override
{
// Calling deposit() with nonzero value will send the ETH to this contract address.
// Once received here, we transfer it back by sending to the msg.sender.
_transfer(address(this), msg.sender, msg.value);
emit Deposit(msg.sender, msg.value);
}
/**
* Implements the WETH9 withdraw() function as a no-op.
* WARNING: this function does NOT have to do with cross-chain asset bridging. The relevant
* deposit and withdraw functions for that use case can be found at L2StandardBridge.sol.
* This function allows developers to treat OVM_ETH as WETH without any modifications to their
* code.
* @param _wad Amount being withdrawn
*/
function withdraw(
uint256 _wad
)
external
override
{
// Calling withdraw() with value exceeding the withdrawer's ovmBALANCE should revert,
// as in WETH9.
require(balanceOf(msg.sender) >= _wad);
// Other than emitting an event, OVM_ETH already is native ETH, so we don't need to do
// anything else.
emit Withdrawal(msg.sender, _wad);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16 <0.8.0;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./IL2StandardERC20.sol";
contract L2StandardERC20 is IL2StandardERC20, ERC20 {
address public override l1Token;
address public l2Bridge;
/**
* @param _l2Bridge Address of the L2 standard bridge.
* @param _l1Token Address of the corresponding L1 token.
* @param _name ERC20 name.
* @param _symbol ERC20 symbol.
*/
constructor(
address _l2Bridge,
address _l1Token,
string memory _name,
string memory _symbol
)
ERC20(_name, _symbol) {
l1Token = _l1Token;
l2Bridge = _l2Bridge;
}
modifier onlyL2Bridge {
require(msg.sender == l2Bridge, "Only L2 Bridge can mint and burn");
_;
}
function supportsInterface(bytes4 _interfaceId) public override pure returns (bool) {
bytes4 firstSupportedInterface = bytes4(keccak256("supportsInterface(bytes4)")); // ERC165
bytes4 secondSupportedInterface = IL2StandardERC20.l1Token.selector
^ IL2StandardERC20.mint.selector
^ IL2StandardERC20.burn.selector;
return _interfaceId == firstSupportedInterface || _interfaceId == secondSupportedInterface;
}
function mint(address _to, uint256 _amount) public virtual override onlyL2Bridge {
_mint(_to, _amount);
emit Mint(_to, _amount);
}
function burn(address _from, uint256 _amount) public virtual override onlyL2Bridge {
_burn(_from, _amount);
emit Burn(_from, _amount);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Interface for WETH9. Also contains the non-ERC20 events
/// normally present in the WETH9 implementation.
interface IWETH9 is IERC20 {
event Deposit(address indexed dst, uint256 wad);
event Withdrawal(address indexed src, uint256 wad);
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
// 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 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;
/**
* @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 "./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
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1StandardBridge } from "../../../iOVM/bridge/tokens/iOVM_L1StandardBridge.sol";
import { iOVM_L1ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L1ERC20Bridge.sol";
import { iOVM_L2ERC20Bridge } from "../../../iOVM/bridge/tokens/iOVM_L2ERC20Bridge.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/* Library Imports */
import { OVM_CrossDomainEnabled } from "../../../libraries/bridge/OVM_CrossDomainEnabled.sol";
import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @title OVM_L1StandardBridge
* @dev The L1 ETH and ERC20 Bridge is a contract which stores deposited L1 funds and standard
* 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 OVM_L1StandardBridge is iOVM_L1StandardBridge, OVM_CrossDomainEnabled {
using SafeMath for uint;
using SafeERC20 for IERC20;
/********************************
* External Contract References *
********************************/
address public l2TokenBridge;
// Maps L1 token to L2 token to balance of the L1 token deposited
mapping(address => mapping (address => uint256)) public deposits;
/***************
* Constructor *
***************/
// This contract lives behind a proxy, so the constructor parameters will go unused.
constructor()
OVM_CrossDomainEnabled(address(0))
{}
/******************
* Initialization *
******************/
/**
* @param _l1messenger L1 Messenger address being used for cross-chain communications.
* @param _l2TokenBridge L2 standard bridge address.
*/
function initialize(
address _l1messenger,
address _l2TokenBridge
)
public
{
require(messenger == address(0), "Contract has already been initialized.");
messenger = _l1messenger;
l2TokenBridge = _l2TokenBridge;
}
/**************
* Depositing *
**************/
/** @dev Modifier requiring sender to be EOA. This check could be bypassed by a malicious
* contract via initcode, but it takes care of the user error we want to avoid.
*/
modifier onlyEOA() {
// Used to stop deposits from contracts (avoid accidentally lost tokens)
require(!Address.isContract(msg.sender), "Account not EOA");
_;
}
/**
* @dev This function can be called with no data
* to deposit an amount of ETH to the caller's balance on L2.
* Since the receive function doesn't take data, a conservative
* default amount is forwarded to L2.
*/
receive()
external
payable
onlyEOA()
{
_initiateETHDeposit(
msg.sender,
msg.sender,
1_300_000,
bytes("")
);
}
/**
* @inheritdoc iOVM_L1StandardBridge
*/
function depositETH(
uint32 _l2Gas,
bytes calldata _data
)
external
override
payable
onlyEOA()
{
_initiateETHDeposit(
msg.sender,
msg.sender,
_l2Gas,
_data
);
}
/**
* @inheritdoc iOVM_L1StandardBridge
*/
function depositETHTo(
address _to,
uint32 _l2Gas,
bytes calldata _data
)
external
override
payable
{
_initiateETHDeposit(
msg.sender,
_to,
_l2Gas,
_data
);
}
/**
* @dev Performs the logic for deposits by storing the ETH and informing the L2 ETH Gateway of
* the deposit.
* @param _from Account to pull the deposit from on L1.
* @param _to Account to give the deposit to on L2.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function _initiateETHDeposit(
address _from,
address _to,
uint32 _l2Gas,
bytes memory _data
)
internal
{
// Construct calldata for finalizeDeposit call
bytes memory message =
abi.encodeWithSelector(
iOVM_L2ERC20Bridge.finalizeDeposit.selector,
address(0),
Lib_PredeployAddresses.OVM_ETH,
_from,
_to,
msg.value,
_data
);
// Send calldata into L2
sendCrossDomainMessage(
l2TokenBridge,
_l2Gas,
message
);
emit ETHDepositInitiated(_from, _to, msg.value, _data);
}
/**
* @inheritdoc iOVM_L1ERC20Bridge
*/
function depositERC20(
address _l1Token,
address _l2Token,
uint256 _amount,
uint32 _l2Gas,
bytes calldata _data
)
external
override
virtual
onlyEOA()
{
_initiateERC20Deposit(_l1Token, _l2Token, msg.sender, msg.sender, _amount, _l2Gas, _data);
}
/**
* @inheritdoc iOVM_L1ERC20Bridge
*/
function depositERC20To(
address _l1Token,
address _l2Token,
address _to,
uint256 _amount,
uint32 _l2Gas,
bytes calldata _data
)
external
override
virtual
{
_initiateERC20Deposit(_l1Token, _l2Token, msg.sender, _to, _amount, _l2Gas, _data);
}
/**
* @dev Performs the logic for deposits by informing the L2 Deposited Token
* contract of the deposit and calling a handler to lock the L1 funds. (e.g. transferFrom)
*
* @param _l1Token Address of the L1 ERC20 we are depositing
* @param _l2Token Address of the L1 respective L2 ERC20
* @param _from Account to pull the deposit from on L1
* @param _to Account to give the deposit to on L2
* @param _amount Amount of the ERC20 to deposit.
* @param _l2Gas Gas limit required to complete the deposit on L2.
* @param _data Optional data to forward to L2. This data is provided
* solely as a convenience for external contracts. Aside from enforcing a maximum
* length, these contracts provide no guarantees about its content.
*/
function _initiateERC20Deposit(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
uint32 _l2Gas,
bytes calldata _data
)
internal
{
// 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).
IERC20(_l1Token).safeTransferFrom(
_from,
address(this),
_amount
);
// Construct calldata for _l2Token.finalizeDeposit(_to, _amount)
bytes memory message = abi.encodeWithSelector(
iOVM_L2ERC20Bridge.finalizeDeposit.selector,
_l1Token,
_l2Token,
_from,
_to,
_amount,
_data
);
// Send calldata into L2
sendCrossDomainMessage(
l2TokenBridge,
_l2Gas,
message
);
deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].add(_amount);
emit ERC20DepositInitiated(_l1Token, _l2Token, _from, _to, _amount, _data);
}
/*************************
* Cross-chain Functions *
*************************/
/**
* @inheritdoc iOVM_L1StandardBridge
*/
function finalizeETHWithdrawal(
address _from,
address _to,
uint256 _amount,
bytes calldata _data
)
external
override
onlyFromCrossDomainAccount(l2TokenBridge)
{
(bool success, ) = _to.call{value: _amount}(new bytes(0));
require(success, "TransferHelper::safeTransferETH: ETH transfer failed");
emit ETHWithdrawalFinalized(_from, _to, _amount, _data);
}
/**
* @inheritdoc iOVM_L1ERC20Bridge
*/
function finalizeERC20Withdrawal(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
)
external
override
onlyFromCrossDomainAccount(l2TokenBridge)
{
deposits[_l1Token][_l2Token] = deposits[_l1Token][_l2Token].sub(_amount);
// When a withdrawal is finalized on L1, the L1 Bridge transfers the funds to the withdrawer
IERC20(_l1Token).safeTransfer(_to, _amount);
emit ERC20WithdrawalFinalized(_l1Token, _l2Token, _from, _to, _amount, _data);
}
/*****************************
* Temporary - Migrating ETH *
*****************************/
/**
* @dev Adds ETH balance to the account. This is meant to allow for ETH
* to be migrated from an old gateway to a new gateway.
* NOTE: This is left for one upgrade only so we are able to receive the migrated ETH from the
* old contract
*/
function donateETH() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol";
/* Library Imports */
import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol";
import { Lib_ExecutionManagerWrapper } from
"../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Contract Imports */
import { OVM_ETH } from "../predeploys/OVM_ETH.sol";
/* External Imports */
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { ECDSA } from "@openzeppelin/contracts/cryptography/ECDSA.sol";
/**
* @title OVM_ECDSAContractAccount
* @dev The ECDSA Contract Account can be used as the implementation for a ProxyEOA deployed by the
* ovmCREATEEOA operation. It enables backwards compatibility with Ethereum's Layer 1, by
* providing EIP155 formatted transaction encodings.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_ECDSAContractAccount is iOVM_ECDSAContractAccount {
/*************
* Libraries *
*************/
using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx;
/*************
* Constants *
*************/
// TODO: should be the amount sufficient to cover the gas costs of all of the transactions up
// to and including the CALL/CREATE which forms the entrypoint of the transaction.
uint256 constant EXECUTION_VALIDATION_GAS_OVERHEAD = 25000;
/********************
* Public Functions *
********************/
/**
* No-op fallback mirrors behavior of calling an EOA on L1.
*/
fallback()
external
payable
{
return;
}
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(
bytes32 hash,
bytes memory signature
)
public
view
returns (
bytes4 magicValue
)
{
return ECDSA.recover(hash, signature) == address(this) ?
this.isValidSignature.selector :
bytes4(0);
}
/**
* Executes a signed transaction.
* @param _transaction Signed EIP155 transaction.
* @return Whether or not the call returned (rather than reverted).
* @return Data returned by the call.
*/
function execute(
Lib_EIP155Tx.EIP155Tx memory _transaction
)
override
public
returns (
bool,
bytes memory
)
{
// Address of this contract within the ovm (ovmADDRESS) should be the same as the
// recovered address of the user who signed this message. This is how we manage to shim
// account abstraction even though the user isn't a contract.
require(
_transaction.sender() == Lib_ExecutionManagerWrapper.ovmADDRESS(),
"Signature provided for EOA transaction execution is invalid."
);
require(
_transaction.chainId == Lib_ExecutionManagerWrapper.ovmCHAINID(),
"Transaction signed with wrong chain ID"
);
// Need to make sure that the transaction nonce is right.
require(
_transaction.nonce == Lib_ExecutionManagerWrapper.ovmGETNONCE(),
"Transaction nonce does not match the expected nonce."
);
// TEMPORARY: Disable gas checks for mainnet.
// // Need to make sure that the gas is sufficient to execute the transaction.
// require(
// gasleft() >= SafeMath.add(transaction.gasLimit, EXECUTION_VALIDATION_GAS_OVERHEAD),
// "Gas is not sufficient to execute the transaction."
// );
// Transfer fee to relayer.
require(
OVM_ETH(Lib_PredeployAddresses.OVM_ETH).transfer(
Lib_PredeployAddresses.SEQUENCER_FEE_WALLET,
SafeMath.mul(_transaction.gasLimit, _transaction.gasPrice)
),
"Fee was not transferred to relayer."
);
if (_transaction.isCreate) {
// TEMPORARY: Disable value transfer for contract creations.
require(
_transaction.value == 0,
"Value transfer in contract creation not supported."
);
(address created, bytes memory revertdata) = Lib_ExecutionManagerWrapper.ovmCREATE(
_transaction.data
);
// Return true if the contract creation succeeded, false w/ revertdata otherwise.
if (created != address(0)) {
return (true, abi.encode(created));
} else {
return (false, revertdata);
}
} else {
// We only want to bump the nonce for `ovmCALL` because `ovmCREATE` automatically bumps
// the nonce of the calling account. Normally an EOA would bump the nonce for both
// cases, but since this is a contract we'd end up bumping the nonce twice.
Lib_ExecutionManagerWrapper.ovmINCREMENTNONCE();
// NOTE: Upgrades are temporarily disabled because users can, in theory, modify their
// EOA so that they don't have to pay any fees to the sequencer. Function will remain
// disabled until a robust solution is in place.
require(
_transaction.to != Lib_ExecutionManagerWrapper.ovmADDRESS(),
"Calls to self are disabled until upgradability is re-enabled."
);
return _transaction.to.call{value: _transaction.value}(_transaction.data);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol";
/**
* @title iOVM_ECDSAContractAccount
*/
interface iOVM_ECDSAContractAccount {
/********************
* Public Functions *
********************/
function execute(
Lib_EIP155Tx.EIP155Tx memory _transaction
)
external
returns (
bool,
bytes memory
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
/**
* @title Lib_EIP155Tx
* @dev A simple library for dealing with the transaction type defined by EIP155:
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
*/
library Lib_EIP155Tx {
/***********
* Structs *
***********/
// Struct representing an EIP155 transaction. See EIP link above for more information.
struct EIP155Tx {
// These fields correspond to the actual RLP-encoded fields specified by EIP155.
uint256 nonce;
uint256 gasPrice;
uint256 gasLimit;
address to;
uint256 value;
bytes data;
uint8 v;
bytes32 r;
bytes32 s;
// Chain ID to associate this transaction with. Used all over the place, seemed easier to
// set this once when we create the transaction rather than providing it as an input to
// each function. I don't see a strong need to have a transaction with a mutable chain ID.
uint256 chainId;
// The ECDSA "recovery parameter," should always be 0 or 1. EIP155 specifies that:
// `v = {0,1} + CHAIN_ID * 2 + 35`
// Where `{0,1}` is a stand in for our `recovery_parameter`. Now computing our formula for
// the recovery parameter:
// 1. `v = {0,1} + CHAIN_ID * 2 + 35`
// 2. `v = recovery_parameter + CHAIN_ID * 2 + 35`
// 3. `v - CHAIN_ID * 2 - 35 = recovery_parameter`
// So we're left with the final formula:
// `recovery_parameter = v - CHAIN_ID * 2 - 35`
// NOTE: This variable is a uint8 because `v` is inherently limited to a uint8. If we
// didn't use a uint8, then recovery_parameter would always be a negative number for chain
// IDs greater than 110 (`255 - 110 * 2 - 35 = 0`). So we need to wrap around to support
// anything larger.
uint8 recoveryParam;
// Whether or not the transaction is a creation. Necessary because we can't make an address
// "nil". Using the zero address creates a potential conflict if the user did actually
// intend to send a transaction to the zero address.
bool isCreate;
}
// Lets us use nicer syntax.
using Lib_EIP155Tx for EIP155Tx;
/**********************
* Internal Functions *
**********************/
/**
* Decodes an EIP155 transaction and attaches a given Chain ID.
* Transaction *must* be RLP-encoded.
* @param _encoded RLP-encoded EIP155 transaction.
* @param _chainId Chain ID to assocaite with this transaction.
* @return Parsed transaction.
*/
function decode(
bytes memory _encoded,
uint256 _chainId
)
internal
pure
returns (
EIP155Tx memory
)
{
Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_encoded);
// Note formula above about how recoveryParam is computed.
uint8 v = uint8(Lib_RLPReader.readUint256(decoded[6]));
uint8 recoveryParam = uint8(v - 2 * _chainId - 35);
// Recovery param being anything other than 0 or 1 indicates that we have the wrong chain
// ID.
require(
recoveryParam < 2,
"Lib_EIP155Tx: Transaction signed with wrong chain ID"
);
// Creations can be detected by looking at the byte length here.
bool isCreate = Lib_RLPReader.readBytes(decoded[3]).length == 0;
return EIP155Tx({
nonce: Lib_RLPReader.readUint256(decoded[0]),
gasPrice: Lib_RLPReader.readUint256(decoded[1]),
gasLimit: Lib_RLPReader.readUint256(decoded[2]),
to: Lib_RLPReader.readAddress(decoded[3]),
value: Lib_RLPReader.readUint256(decoded[4]),
data: Lib_RLPReader.readBytes(decoded[5]),
v: v,
r: Lib_RLPReader.readBytes32(decoded[7]),
s: Lib_RLPReader.readBytes32(decoded[8]),
chainId: _chainId,
recoveryParam: recoveryParam,
isCreate: isCreate
});
}
/**
* Encodes an EIP155 transaction into RLP.
* @param _transaction EIP155 transaction to encode.
* @param _includeSignature Whether or not to encode the signature.
* @return RLP-encoded transaction.
*/
function encode(
EIP155Tx memory _transaction,
bool _includeSignature
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](9);
raw[0] = Lib_RLPWriter.writeUint(_transaction.nonce);
raw[1] = Lib_RLPWriter.writeUint(_transaction.gasPrice);
raw[2] = Lib_RLPWriter.writeUint(_transaction.gasLimit);
// We write the encoding of empty bytes when the transaction is a creation, *not* the zero
// address as one might assume.
if (_transaction.isCreate) {
raw[3] = Lib_RLPWriter.writeBytes("");
} else {
raw[3] = Lib_RLPWriter.writeAddress(_transaction.to);
}
raw[4] = Lib_RLPWriter.writeUint(_transaction.value);
raw[5] = Lib_RLPWriter.writeBytes(_transaction.data);
if (_includeSignature) {
raw[6] = Lib_RLPWriter.writeUint(_transaction.v);
raw[7] = Lib_RLPWriter.writeBytes32(_transaction.r);
raw[8] = Lib_RLPWriter.writeBytes32(_transaction.s);
} else {
// Chain ID *is* included in the unsigned transaction.
raw[6] = Lib_RLPWriter.writeUint(_transaction.chainId);
raw[7] = Lib_RLPWriter.writeBytes("");
raw[8] = Lib_RLPWriter.writeBytes("");
}
return Lib_RLPWriter.writeList(raw);
}
/**
* Computes the hash of an EIP155 transaction. Assumes that you don't want to include the
* signature in this hash because that's a very uncommon usecase. If you really want to include
* the signature, just encode with the signature and take the hash yourself.
*/
function hash(
EIP155Tx memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(
_transaction.encode(false)
);
}
/**
* Computes the sender of an EIP155 transaction.
* @param _transaction EIP155 transaction to get a sender for.
* @return Address corresponding to the private key that signed this transaction.
*/
function sender(
EIP155Tx memory _transaction
)
internal
pure
returns (
address
)
{
return ecrecover(
_transaction.hash(),
_transaction.recoveryParam + 27,
_transaction.r,
_transaction.s
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_ErrorUtils } from "../utils/Lib_ErrorUtils.sol";
import { Lib_PredeployAddresses } from "../constants/Lib_PredeployAddresses.sol";
/**
* @title Lib_ExecutionManagerWrapper
* @dev This library acts as a utility for easily calling the OVM_ExecutionManagerWrapper, the
* predeployed contract which exposes the `kall` builtin. Effectively, this contract allows the
* user to trigger OVM opcodes by directly calling the OVM_ExecutionManger.
*
* Compiler used: solc
* Runtime target: OVM
*/
library Lib_ExecutionManagerWrapper {
/**********************
* Internal Functions *
**********************/
/**
* Performs a safe ovmCREATE call.
* @param _bytecode Code for the new contract.
* @return Address of the created contract.
*/
function ovmCREATE(
bytes memory _bytecode
)
internal
returns (
address,
bytes memory
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmCREATE(bytes)",
_bytecode
)
);
return abi.decode(returndata, (address, bytes));
}
/**
* Performs a safe ovmGETNONCE call.
* @return Result of calling ovmGETNONCE.
*/
function ovmGETNONCE()
internal
returns (
uint256
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmGETNONCE()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmINCREMENTNONCE call.
*/
function ovmINCREMENTNONCE()
internal
{
_callWrapperContract(
abi.encodeWithSignature(
"ovmINCREMENTNONCE()"
)
);
}
/**
* Performs a safe ovmCREATEEOA call.
* @param _messageHash Message hash which was signed by EOA
* @param _v v value of signature (0 or 1)
* @param _r r value of signature
* @param _s s value of signature
*/
function ovmCREATEEOA(
bytes32 _messageHash,
uint8 _v,
bytes32 _r,
bytes32 _s
)
internal
{
_callWrapperContract(
abi.encodeWithSignature(
"ovmCREATEEOA(bytes32,uint8,bytes32,bytes32)",
_messageHash,
_v,
_r,
_s
)
);
}
/**
* Calls the ovmL1TXORIGIN opcode.
* @return Address that sent this message from L1.
*/
function ovmL1TXORIGIN()
internal
returns (
address
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmL1TXORIGIN()"
)
);
return abi.decode(returndata, (address));
}
/**
* Calls the ovmCHAINID opcode.
* @return Chain ID of the current network.
*/
function ovmCHAINID()
internal
returns (
uint256
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmCHAINID()"
)
);
return abi.decode(returndata, (uint256));
}
/**
* Performs a safe ovmADDRESS call.
* @return Result of calling ovmADDRESS.
*/
function ovmADDRESS()
internal
returns (
address
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmADDRESS()"
)
);
return abi.decode(returndata, (address));
}
/**
* Calls the value-enabled ovmCALL opcode.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _value ETH value to pass with the call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmCALL(
uint256 _gasLimit,
address _address,
uint256 _value,
bytes memory _calldata
)
internal
returns (
bool,
bytes memory
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmCALL(uint256,address,uint256,bytes)",
_gasLimit,
_address,
_value,
_calldata
)
);
return abi.decode(returndata, (bool, bytes));
}
/**
* Calls the ovmBALANCE opcode.
* @param _address OVM account to query the balance of.
* @return Balance of the account.
*/
function ovmBALANCE(
address _address
)
internal
returns (
uint256
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmBALANCE(address)",
_address
)
);
return abi.decode(returndata, (uint256));
}
/**
* Calls the ovmCALLVALUE opcode.
* @return Value of the current call frame.
*/
function ovmCALLVALUE()
internal
returns (
uint256
)
{
bytes memory returndata = _callWrapperContract(
abi.encodeWithSignature(
"ovmCALLVALUE()"
)
);
return abi.decode(returndata, (uint256));
}
/*********************
* Private Functions *
*********************/
/**
* Performs an ovm interaction and the necessary safety checks.
* @param _calldata Data to send to the OVM_ExecutionManager (encoded with sighash).
* @return Data sent back by the OVM_ExecutionManager.
*/
function _callWrapperContract(
bytes memory _calldata
)
private
returns (
bytes memory
)
{
(bool success, bytes memory returndata) =
Lib_PredeployAddresses.EXECUTION_MANAGER_WRAPPER.delegatecall(_calldata);
if (success == true) {
return returndata;
} else {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
}
// 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.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a bytes32 value.
* @param _in The bytes32 to encode.
* @return _out The RLP encoded bytes32 in bytes.
*/
function writeBytes32(
bytes32 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_ErrorUtils
*/
library Lib_ErrorUtils {
/**********************
* Internal Functions *
**********************/
/**
* Encodes an error string into raw solidity-style revert data.
* (i.e. ascii bytes, prefixed with bytes4(keccak("Error(string))"))
* Ref: https://docs.soliditylang.org/en/v0.8.2/control-structures.html?highlight=Error(string)
* #panic-via-assert-and-error-via-require
* @param _reason Reason for the reversion.
* @return Standard solidity revert data for the given reason.
*/
function encodeRevertString(
string memory _reason
)
internal
pure
returns (
bytes memory
)
{
return abi.encodeWithSignature(
"Error(string)",
_reason
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
import { Lib_ExecutionManagerWrapper } from
"../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol";
/**
* @title OVM_ProxyEOA
* @dev The Proxy EOA contract uses a delegate call to execute the logic in an implementation
* contract. In combination with the logic implemented in the ECDSA Contract Account, this enables
* a form of upgradable 'account abstraction' on layer 2.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_ProxyEOA {
/**********
* Events *
**********/
event Upgraded(
address indexed implementation
);
/*************
* Constants *
*************/
// solhint-disable-next-line max-line-length
bytes32 constant IMPLEMENTATION_KEY = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; //bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1);
/*********************
* Fallback Function *
*********************/
fallback()
external
payable
{
(bool success, bytes memory returndata) = getImplementation().delegatecall(msg.data);
if (success) {
assembly {
return(add(returndata, 0x20), mload(returndata))
}
} else {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
// WARNING: We use the deployed bytecode of this contract as a template to create ProxyEOA
// contracts. As a result, we must *not* perform any constructor logic. Use initialization
// functions if necessary.
/********************
* Public Functions *
********************/
/**
* Changes the implementation address.
* @param _implementation New implementation address.
*/
function upgrade(
address _implementation
)
external
{
require(
msg.sender == Lib_ExecutionManagerWrapper.ovmADDRESS(),
"EOAs can only upgrade their own EOA implementation."
);
_setImplementation(_implementation);
emit Upgraded(_implementation);
}
/**
* Gets the address of the current implementation.
* @return Current implementation address.
*/
function getImplementation()
public
view
returns (
address
)
{
bytes32 addr32;
assembly {
addr32 := sload(IMPLEMENTATION_KEY)
}
address implementation = Lib_Bytes32Utils.toAddress(addr32);
if (implementation == address(0)) {
return Lib_PredeployAddresses.ECDSA_CONTRACT_ACCOUNT;
} else {
return implementation;
}
}
/**********************
* Internal Functions *
**********************/
function _setImplementation(
address _implementation
)
internal
{
bytes32 addr32 = Lib_Bytes32Utils.fromAddress(_implementation);
assembly {
sstore(IMPLEMENTATION_KEY, addr32)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_EIP155Tx } from "../../libraries/codec/Lib_EIP155Tx.sol";
import { Lib_ExecutionManagerWrapper } from
"../../libraries/wrappers/Lib_ExecutionManagerWrapper.sol";
import { iOVM_ECDSAContractAccount } from "../../iOVM/predeploys/iOVM_ECDSAContractAccount.sol";
/**
* @title OVM_SequencerEntrypoint
* @dev The Sequencer Entrypoint is a predeploy which, despite its name, can in fact be called by
* any account. It accepts a more efficient compressed calldata format, which it decompresses and
* encodes to the standard EIP155 transaction format.
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_SequencerEntrypoint {
/*************
* Libraries *
*************/
using Lib_EIP155Tx for Lib_EIP155Tx.EIP155Tx;
/*********************
* Fallback Function *
*********************/
/**
* Expects an RLP-encoded EIP155 transaction as input. See the EIP for a more detailed
* description of this transaction format:
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-155.md
*/
fallback()
external
{
// We use this twice, so it's more gas efficient to store a copy of it (barely).
bytes memory encodedTx = msg.data;
// Decode the tx with the correct chain ID.
Lib_EIP155Tx.EIP155Tx memory transaction = Lib_EIP155Tx.decode(
encodedTx,
Lib_ExecutionManagerWrapper.ovmCHAINID()
);
// Value is computed on the fly. Keep it in the stack to save some gas.
address target = transaction.sender();
bool isEmptyContract;
assembly {
isEmptyContract := iszero(extcodesize(target))
}
// If the account is empty, deploy the default EOA to that address.
if (isEmptyContract) {
Lib_ExecutionManagerWrapper.ovmCREATEEOA(
transaction.hash(),
transaction.recoveryParam,
transaction.r,
transaction.s
);
}
// Forward the transaction over to the EOA.
(bool success, bytes memory returndata) = target.call(
abi.encodeWithSelector(iOVM_ECDSAContractAccount.execute.selector, transaction)
);
if (success) {
assembly {
return(add(returndata, 0x20), mload(returndata))
}
} else {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_EIP155Tx } from "../../optimistic-ethereum/libraries/codec/Lib_EIP155Tx.sol";
/**
* @title TestLib_EIP155Tx
*/
contract TestLib_EIP155Tx {
function decode(
bytes memory _encoded,
uint256 _chainId
)
public
pure
returns (
Lib_EIP155Tx.EIP155Tx memory
)
{
return Lib_EIP155Tx.decode(
_encoded,
_chainId
);
}
function encode(
Lib_EIP155Tx.EIP155Tx memory _transaction,
bool _includeSignature
)
public
pure
returns (
bytes memory
)
{
return Lib_EIP155Tx.encode(
_transaction,
_includeSignature
);
}
function hash(
Lib_EIP155Tx.EIP155Tx memory _transaction
)
public
pure
returns (
bytes32
)
{
return Lib_EIP155Tx.hash(
_transaction
);
}
function sender(
Lib_EIP155Tx.EIP155Tx memory _transaction
)
public
pure
returns (
address
)
{
return Lib_EIP155Tx.sender(
_transaction
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPWriter } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPWriter.sol";
import { TestERC20 } from "../../test-helpers/TestERC20.sol";
/**
* @title TestLib_RLPWriter
*/
contract TestLib_RLPWriter {
function writeBytes(
bytes memory _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeBytes(_in);
}
function writeList(
bytes[] memory _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeList(_in);
}
function writeString(
string memory _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeString(_in);
}
function writeAddress(
address _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeAddress(_in);
}
function writeUint(
uint256 _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeUint(_in);
}
function writeBool(
bool _in
)
public
pure
returns (
bytes memory _out
)
{
return Lib_RLPWriter.writeBool(_in);
}
function writeAddressWithTaintedMemory(
address _in
)
public
returns (
bytes memory _out
)
{
new TestERC20();
return Lib_RLPWriter.writeAddress(_in);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
// a test ERC20 token with an open mint function
contract TestERC20 {
using SafeMath for uint;
string public constant name = 'Test';
string public constant symbol = 'TST';
uint8 public constant decimals = 18;
uint256 public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
constructor() {}
function mint(address to, uint256 value) public {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _approve(address owner, address spender, uint256 value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint256 value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint256 value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint256 value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
library SafeMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_BytesUtils } from "../../optimistic-ethereum/libraries/utils/Lib_BytesUtils.sol";
import { TestERC20 } from "../../test-helpers/TestERC20.sol";
/**
* @title TestLib_BytesUtils
*/
contract TestLib_BytesUtils {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
public
pure
returns (bytes memory)
{
return abi.encodePacked(
_preBytes,
_postBytes
);
}
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
public
pure
returns (bytes memory)
{
return Lib_BytesUtils.slice(
_bytes,
_start,
_length
);
}
function toBytes32(
bytes memory _bytes
)
public
pure
returns (bytes32)
{
return Lib_BytesUtils.toBytes32(
_bytes
);
}
function toUint256(
bytes memory _bytes
)
public
pure
returns (uint256)
{
return Lib_BytesUtils.toUint256(
_bytes
);
}
function toNibbles(
bytes memory _bytes
)
public
pure
returns (bytes memory)
{
return Lib_BytesUtils.toNibbles(
_bytes
);
}
function fromNibbles(
bytes memory _bytes
)
public
pure
returns (bytes memory)
{
return Lib_BytesUtils.fromNibbles(
_bytes
);
}
function equal(
bytes memory _bytes,
bytes memory _other
)
public
pure
returns (bool)
{
return Lib_BytesUtils.equal(
_bytes,
_other
);
}
function sliceWithTaintedMemory(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
public
returns (bytes memory)
{
new TestERC20();
return Lib_BytesUtils.slice(
_bytes,
_start,
_length
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (
bytes memory
)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
bytes memory
)
{
if (_start >= _bytes.length) {
return bytes("");
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (
uint256
)
{
return uint256(toBytes32(_bytes));
}
function toUint24(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint24
)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint8
)
{
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
address
)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (
bool
)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol";
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol";
import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol";
import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol";
import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol";
/* Contract Imports */
import { Abs_FraudContributor } from "./Abs_FraudContributor.sol";
/**
* @title OVM_StateTransitioner
* @dev The State Transitioner coordinates the execution of a state transition during the evaluation
* of a fraud proof. It feeds verified input to the Execution Manager's run(), and controls a
* State Manager (which is uniquely created for each fraud proof).
* Once a fraud proof has been initialized, this contract is provided with the pre-state root and
* verifies that the OVM storage slots committed to the State Mangager are contained in that state
* This contract controls the State Manager and Execution Manager, and uses them to calculate the
* post-state root by applying the transaction. The Fraud Verifier can then check for fraud by
* comparing the calculated post-state root with the proposed post-state root.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner
{
/*******************
* Data Structures *
*******************/
enum TransitionPhase {
PRE_EXECUTION,
POST_EXECUTION,
COMPLETE
}
/*******************************************
* Contract Variables: Contract References *
*******************************************/
iOVM_StateManager public ovmStateManager;
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
bytes32 internal preStateRoot;
bytes32 internal postStateRoot;
TransitionPhase public phase;
uint256 internal stateTransitionIndex;
bytes32 internal transactionHash;
/*************
* Constants *
*************/
// solhint-disable-next-line max-line-length
bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line max-line-length
bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
*/
constructor(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
Lib_AddressResolver(_libAddressManager)
{
stateTransitionIndex = _stateTransitionIndex;
preStateRoot = _preStateRoot;
postStateRoot = _preStateRoot;
transactionHash = _transactionHash;
ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory"))
.create(address(this));
}
/**********************
* Function Modifiers *
**********************/
/**
* Checks that a function is only run during a specific phase.
* @param _phase Phase the function must run within.
*/
modifier onlyDuringPhase(
TransitionPhase _phase
) {
require(
phase == _phase,
"Function must be called during the correct phase."
);
_;
}
/**********************************
* Public Functions: State Access *
**********************************/
/**
* Retrieves the state root before execution.
* @return _preStateRoot State root before execution.
*/
function getPreStateRoot()
override
external
view
returns (
bytes32 _preStateRoot
)
{
return preStateRoot;
}
/**
* Retrieves the state root after execution.
* @return _postStateRoot State root after execution.
*/
function getPostStateRoot()
override
external
view
returns (
bytes32 _postStateRoot
)
{
return postStateRoot;
}
/**
* Checks whether the transitioner is complete.
* @return _complete Whether or not the transition process is finished.
*/
function isComplete()
override
external
view
returns (
bool _complete
)
{
return phase == TransitionPhase.COMPLETE;
}
/***********************************
* Public Functions: Pre-Execution *
***********************************/
/**
* Allows a user to prove the initial state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _ethContractAddress Address of the corresponding contract on L1.
* @param _stateTrieWitness Proof of the account state.
*/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
(
ovmStateManager.hasAccount(_ovmContractAddress) == false
&& ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false
),
"Account state has already been proven."
);
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedAccount
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_ovmContractAddress),
_stateTrieWitness,
preStateRoot
);
if (exists == true) {
// Account exists, this was an inclusion proof.
Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(
encodedAccount
);
address ethContractAddress = _ethContractAddress;
if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) {
// Use a known empty contract to prevent an attack in which a user provides a
// contract address here and then later deploys code to it.
ethContractAddress = 0x0000000000000000000000000000000000000000;
} else {
// Otherwise, make sure that the code at the provided eth address matches the hash
// of the code stored on L2.
require(
Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash,
// solhint-disable-next-line max-line-length
"OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash."
);
}
ovmStateManager.putAccount(
_ovmContractAddress,
Lib_OVMCodec.Account({
nonce: account.nonce,
balance: account.balance,
storageRoot: account.storageRoot,
codeHash: account.codeHash,
ethAddress: ethContractAddress,
isFresh: false
})
);
} else {
// Account does not exist, this was an exclusion proof.
ovmStateManager.putEmptyAccount(_ovmContractAddress);
}
}
/**
* Allows a user to prove the initial state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false,
"Storage slot has already been proven."
);
require(
ovmStateManager.hasAccount(_ovmContractAddress) == true,
"Contract must be verified before proving a storage slot."
);
bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress);
bytes32 value;
if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) {
// Storage trie was empty, so the user is always allowed to insert zero-byte values.
value = bytes32(0);
} else {
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedValue
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_key),
_storageTrieWitness,
storageRoot
);
if (exists == true) {
// Inclusion proof.
// Stored values are RLP encoded, with leading zeros removed.
value = Lib_BytesUtils.toBytes32PadLeft(
Lib_RLPReader.readBytes(encodedValue)
);
} else {
// Exclusion proof, can only be zero bytes.
value = bytes32(0);
}
}
ovmStateManager.putContractStorage(
_ovmContractAddress,
_key,
value
);
}
/*******************************
* Public Functions: Execution *
*******************************/
/**
* Executes the state transition.
* @param _transaction OVM transaction to execute.
*/
function applyTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
Lib_OVMCodec.hashTransaction(_transaction) == transactionHash,
"Invalid transaction provided."
);
// We require gas to complete the logic here in run() before/after execution,
// But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism)
// This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first
// going into EM, then going into the code contract).
require(
// 1032/1000 = 1.032 = (64/63)^2 rounded up
gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000,
"Not enough gas to execute transaction deterministically."
);
iOVM_ExecutionManager ovmExecutionManager =
iOVM_ExecutionManager(resolve("OVM_ExecutionManager"));
// We call `setExecutionManager` right before `run` (and not earlier) just in case the
// OVM_ExecutionManager address was updated between the time when this contract was created
// and when `applyTransaction` was called.
ovmStateManager.setExecutionManager(address(ovmExecutionManager));
// `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction`
// or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line
// if that's the case.
ovmExecutionManager.run(_transaction, address(ovmStateManager));
// Prevent the Execution Manager from calling this SM again.
ovmStateManager.setExecutionManager(address(0));
phase = TransitionPhase.POST_EXECUTION;
}
/************************************
* Public Functions: Post-Execution *
************************************/
/**
* Allows a user to commit the final state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _stateTrieWitness Proof of the account state.
*/
function commitContractState(
address _ovmContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before committing account states."
);
require (
ovmStateManager.commitAccount(_ovmContractAddress) == true,
"Account state wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
postStateRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_ovmContractAddress),
Lib_OVMCodec.encodeEVMAccount(
Lib_OVMCodec.toEVMAccount(account)
),
_stateTrieWitness,
postStateRoot
);
// Emit an event to help clients figure out the proof ordering.
emit AccountCommitted(
_ovmContractAddress
);
}
/**
* Allows a user to commit the final state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true,
"Storage slot value wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key);
account.storageRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_key),
Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(value)
),
_storageTrieWitness,
account.storageRoot
);
ovmStateManager.putAccount(_ovmContractAddress, account);
// Emit an event to help clients figure out the proof ordering.
emit ContractStorageCommitted(
_ovmContractAddress,
_key
);
}
/**********************************
* Public Functions: Finalization *
**********************************/
/**
* Finalizes the transition process.
*/
function completeTransition()
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
{
require(
ovmStateManager.getTotalUncommittedAccounts() == 0,
"All accounts must be committed before completing a transition."
);
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before completing a transition."
);
phase = TransitionPhase.COMPLETE;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(
string memory _name
)
public
view
returns (
address
)
{
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol";
/**
* @title Lib_EthUtils
*/
library Lib_EthUtils {
/**********************
* Internal Functions *
**********************/
/**
* Gets the code for a given address.
* @param _address Address to get code for.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Code read from the contract.
*/
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
internal
view
returns (
bytes memory
)
{
bytes memory code;
assembly {
code := mload(0x40)
mstore(0x40, add(code, add(_length, 0x20)))
mstore(code, _length)
extcodecopy(_address, add(code, 0x20), _offset, _length)
}
return code;
}
/**
* Gets the full code for a given address.
* @param _address Address to get code for.
* @return Full code of the contract.
*/
function getCode(
address _address
)
internal
view
returns (
bytes memory
)
{
return getCode(
_address,
0,
getCodeSize(_address)
);
}
/**
* Gets the size of a contract's code in bytes.
* @param _address Address to get code size for.
* @return Size of the contract's code in bytes.
*/
function getCodeSize(
address _address
)
internal
view
returns (
uint256
)
{
uint256 codeSize;
assembly {
codeSize := extcodesize(_address)
}
return codeSize;
}
/**
* Gets the hash of a contract's code.
* @param _address Address to get a code hash for.
* @return Hash of the contract's code.
*/
function getCodeHash(
address _address
)
internal
view
returns (
bytes32
)
{
bytes32 codeHash;
assembly {
codeHash := extcodehash(_address)
}
return codeHash;
}
/**
* Creates a contract with some given initialization code.
* @param _code Contract initialization code.
* @return Address of the created contract.
*/
function createContract(
bytes memory _code
)
internal
returns (
address
)
{
address created;
assembly {
created := create(
0,
add(_code, 0x20),
mload(_code)
)
}
return created;
}
/**
* Computes the address that would be generated by CREATE.
* @param _creator Address creating the contract.
* @param _nonce Creator's nonce.
* @return Address to be generated by CREATE.
*/
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
internal
pure
returns (
address
)
{
bytes[] memory encoded = new bytes[](2);
encoded[0] = Lib_RLPWriter.writeAddress(_creator);
encoded[1] = Lib_RLPWriter.writeUint(_nonce);
bytes memory encodedList = Lib_RLPWriter.writeList(encoded);
return Lib_Bytes32Utils.toAddress(keccak256(encodedList));
}
/**
* Computes the address that would be generated by CREATE2.
* @param _creator Address creating the contract.
* @param _bytecode Bytecode of the contract to be created.
* @param _salt 32 byte salt value mixed into the hash.
* @return Address to be generated by CREATE2.
*/
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
internal
pure
returns (
address
)
{
bytes32 hashedData = keccak256(abi.encodePacked(
byte(0xff),
_creator,
_salt,
keccak256(_bytecode)
));
return Lib_Bytes32Utils.toAddress(hashedData);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol";
/**
* @title Lib_SecureMerkleTrie
*/
library Lib_SecureMerkleTrie {
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.update(key, _value, _proof, _root);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.get(key, _proof, _root);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.getSingleNodeRootHash(key, _value);
}
/*********************
* Private Functions *
*********************/
/**
* Computes the secure counterpart to a key.
* @param _key Key to get a secure key from.
* @return _secureKey Secure version of the key.
*/
function _getSecureKey(
bytes memory _key
)
private
pure
returns (
bytes memory _secureKey
)
{
return abi.encodePacked(keccak256(_key));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateTransitioner
*/
interface iOVM_StateTransitioner {
/**********
* Events *
**********/
event AccountCommitted(
address _address
);
event ContractStorageCommitted(
address _address,
bytes32 _key
);
/**********************************
* Public Functions: State Access *
**********************************/
function getPreStateRoot() external view returns (bytes32 _preStateRoot);
function getPostStateRoot() external view returns (bytes32 _postStateRoot);
function isComplete() external view returns (bool _complete);
/***********************************
* Public Functions: Pre-Execution *
***********************************/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes calldata _stateTrieWitness
) external;
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/*******************************
* Public Functions: Execution *
*******************************/
function applyTransaction(
Lib_OVMCodec.Transaction calldata _transaction
) external;
/************************************
* Public Functions: Post-Execution *
************************************/
function commitContractState(
address _ovmContractAddress,
bytes calldata _stateTrieWitness
) external;
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/**********************************
* Public Functions: Finalization *
**********************************/
function completeTransition() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
interface ERC20 {
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
/// All the errors which may be encountered on the bond manager
library Errors {
string constant ERC20_ERR = "BondManager: Could not post bond";
// solhint-disable-next-line max-line-length
string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized";
string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed";
string constant WRONG_STATE = "BondManager: Wrong bond state for proposer";
string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first";
string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending";
string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal";
// solhint-disable-next-line max-line-length
string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function";
// solhint-disable-next-line max-line-length
string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function";
// solhint-disable-next-line max-line-length
string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function";
string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes";
}
/**
* @title iOVM_BondManager
*/
interface iOVM_BondManager {
/*******************
* Data Structures *
*******************/
/// The lifecycle of a proposer's bond
enum State {
// Before depositing or after getting slashed, a user is uncollateralized
NOT_COLLATERALIZED,
// After depositing, a user is collateralized
COLLATERALIZED,
// After a user has initiated a withdrawal
WITHDRAWING
}
/// A bond posted by a proposer
struct Bond {
// The user's state
State state;
// The timestamp at which a proposer issued their withdrawal request
uint32 withdrawalTimestamp;
// The time when the first disputed was initiated for this bond
uint256 firstDisputeAt;
// The earliest observed state root for this bond which has had fraud
bytes32 earliestDisputedStateRoot;
// The state root's timestamp
uint256 earliestTimestamp;
}
// Per pre-state root, store the number of state provisions that were made
// and how many of these calls were made by each user. Payouts will then be
// claimed by users proportionally for that dispute.
struct Rewards {
// Flag to check if rewards for a fraud proof are claimable
bool canClaim;
// Total number of `recordGasSpent` calls made
uint256 total;
// The gas spent by each user to provide witness data. The sum of all
// values inside this map MUST be equal to the value of `total`
mapping(address => uint256) gasSpent;
}
/********************
* Public Functions *
********************/
function recordGasSpent(
bytes32 _preStateRoot,
bytes32 _txHash,
address _who,
uint256 _gasSpent
) external;
function finalize(
bytes32 _preStateRoot,
address _publisher,
uint256 _timestamp
) external;
function deposit() external;
function startWithdrawal() external;
function finalizeWithdrawal() external;
function claim(
address _who
) external;
function isCollateralized(
address _who
) external view returns (bool);
function getGasSpent(
bytes32 _preStateRoot,
address _who
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
interface iOVM_ExecutionManager {
/**********
* Enums *
*********/
enum RevertFlag {
OUT_OF_GAS,
INTENTIONAL_REVERT,
EXCEEDS_NUISANCE_GAS,
INVALID_STATE_ACCESS,
UNSAFE_BYTECODE,
CREATE_COLLISION,
STATIC_VIOLATION,
CREATOR_NOT_ALLOWED
}
enum GasMetadataKey {
CURRENT_EPOCH_START_TIMESTAMP,
CUMULATIVE_SEQUENCER_QUEUE_GAS,
CUMULATIVE_L1TOL2_QUEUE_GAS,
PREV_EPOCH_SEQUENCER_QUEUE_GAS,
PREV_EPOCH_L1TOL2_QUEUE_GAS
}
enum MessageType {
ovmCALL,
ovmSTATICCALL,
ovmDELEGATECALL,
ovmCREATE,
ovmCREATE2
}
/***********
* Structs *
***********/
struct GasMeterConfig {
uint256 minTransactionGasLimit;
uint256 maxTransactionGasLimit;
uint256 maxGasPerQueuePerEpoch;
uint256 secondsPerEpoch;
}
struct GlobalContext {
uint256 ovmCHAINID;
}
struct TransactionContext {
Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN;
uint256 ovmTIMESTAMP;
uint256 ovmNUMBER;
uint256 ovmGASLIMIT;
uint256 ovmTXGASLIMIT;
address ovmL1TXORIGIN;
}
struct TransactionRecord {
uint256 ovmGasRefund;
}
struct MessageContext {
address ovmCALLER;
address ovmADDRESS;
uint256 ovmCALLVALUE;
bool isStatic;
}
struct MessageRecord {
uint256 nuisanceGasLeft;
}
/************************************
* Transaction Execution Entrypoint *
************************************/
function run(
Lib_OVMCodec.Transaction calldata _transaction,
address _txStateManager
) external returns (bytes memory);
/*******************
* Context Opcodes *
*******************/
function ovmCALLER() external view returns (address _caller);
function ovmADDRESS() external view returns (address _address);
function ovmCALLVALUE() external view returns (uint _callValue);
function ovmTIMESTAMP() external view returns (uint256 _timestamp);
function ovmNUMBER() external view returns (uint256 _number);
function ovmGASLIMIT() external view returns (uint256 _gasLimit);
function ovmCHAINID() external view returns (uint256 _chainId);
/**********************
* L2 Context Opcodes *
**********************/
function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin);
function ovmL1TXORIGIN() external view returns (address _l1TxOrigin);
/*******************
* Halting Opcodes *
*******************/
function ovmREVERT(bytes memory _data) external;
/*****************************
* Contract Creation Opcodes *
*****************************/
function ovmCREATE(bytes memory _bytecode) external
returns (address _contract, bytes memory _revertdata);
function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external
returns (address _contract, bytes memory _revertdata);
/*******************************
* Account Abstraction Opcodes *
******************************/
function ovmGETNONCE() external returns (uint256 _nonce);
function ovmINCREMENTNONCE() external;
function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external;
/****************************
* Contract Calling Opcodes *
****************************/
// Valueless ovmCALL for maintaining backwards compatibility with legacy OVM bytecode.
function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external
returns (bool _success, bytes memory _returndata);
function ovmCALL(uint256 _gasLimit, address _address, uint256 _value, bytes memory _calldata)
external returns (bool _success, bytes memory _returndata);
function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external
returns (bool _success, bytes memory _returndata);
function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external
returns (bool _success, bytes memory _returndata);
/****************************
* Contract Storage Opcodes *
****************************/
function ovmSLOAD(bytes32 _key) external returns (bytes32 _value);
function ovmSSTORE(bytes32 _key, bytes32 _value) external;
/*************************
* Contract Code Opcodes *
*************************/
function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external
returns (bytes memory _code);
function ovmEXTCODESIZE(address _contract) external returns (uint256 _size);
function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash);
/*********************
* ETH Value Opcodes *
*********************/
function ovmBALANCE(address _contract) external returns (uint256 _balance);
function ovmSELFBALANCE() external returns (uint256 _balance);
/***************************************
* Public Functions: Execution Context *
***************************************/
function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateManager
*/
interface iOVM_StateManager {
/*******************
* Data Structures *
*******************/
enum ItemState {
ITEM_UNTOUCHED,
ITEM_LOADED,
ITEM_CHANGED,
ITEM_COMMITTED
}
/***************************
* Public Functions: Misc *
***************************/
function isAuthenticated(address _address) external view returns (bool);
/***************************
* Public Functions: Setup *
***************************/
function owner() external view returns (address _owner);
function ovmExecutionManager() external view returns (address _ovmExecutionManager);
function setExecutionManager(address _ovmExecutionManager) external;
/************************************
* Public Functions: Account Access *
************************************/
function putAccount(address _address, Lib_OVMCodec.Account memory _account) external;
function putEmptyAccount(address _address) external;
function getAccount(address _address) external view
returns (Lib_OVMCodec.Account memory _account);
function hasAccount(address _address) external view returns (bool _exists);
function hasEmptyAccount(address _address) external view returns (bool _exists);
function setAccountNonce(address _address, uint256 _nonce) external;
function getAccountNonce(address _address) external view returns (uint256 _nonce);
function getAccountEthAddress(address _address) external view returns (address _ethAddress);
function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot);
function initPendingAccount(address _address) external;
function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash)
external;
function testAndSetAccountLoaded(address _address) external
returns (bool _wasAccountAlreadyLoaded);
function testAndSetAccountChanged(address _address) external
returns (bool _wasAccountAlreadyChanged);
function commitAccount(address _address) external returns (bool _wasAccountCommitted);
function incrementTotalUncommittedAccounts() external;
function getTotalUncommittedAccounts() external view returns (uint256 _total);
function wasAccountChanged(address _address) external view returns (bool);
function wasAccountCommitted(address _address) external view returns (bool);
/************************************
* Public Functions: Storage Access *
************************************/
function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external;
function getContractStorage(address _contract, bytes32 _key) external view
returns (bytes32 _value);
function hasContractStorage(address _contract, bytes32 _key) external view
returns (bool _exists);
function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external
returns (bool _wasContractStorageAlreadyLoaded);
function testAndSetContractStorageChanged(address _contract, bytes32 _key) external
returns (bool _wasContractStorageAlreadyChanged);
function commitContractStorage(address _contract, bytes32 _key) external
returns (bool _wasContractStorageCommitted);
function incrementTotalUncommittedContractStorage() external;
function getTotalUncommittedContractStorage() external view returns (uint256 _total);
function wasContractStorageChanged(address _contract, bytes32 _key) external view
returns (bool);
function wasContractStorageCommitted(address _contract, bytes32 _key) external view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateManager } from "./iOVM_StateManager.sol";
/**
* @title iOVM_StateManagerFactory
*/
interface iOVM_StateManagerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _owner
)
external
returns (
iOVM_StateManager _ovmStateManager
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/// Minimal contract to be inherited by contracts consumed by users that provide
/// data for fraud proofs
abstract contract Abs_FraudContributor is Lib_AddressResolver {
/// Decorate your functions with this modifier to store how much total gas was
/// consumed by the sender, to reward users fairly
modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) {
uint256 startGas = gasleft();
_;
uint256 gasSpent = startGas - gasleft();
iOVM_BondManager(resolve("OVM_BondManager"))
.recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string indexed _name,
address _newAddress,
address _oldAddress
);
/*************
* Variables *
*************/
mapping (bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(
string memory _name,
address _address
)
external
onlyOwner
{
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(
_name,
_address,
oldAddress
);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(
string memory _name
)
external
view
returns (
address
)
{
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(
string memory _name
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_name));
}
}
// 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.5.0 <0.8.0;
/* Library Imports */
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
/**
* @title Lib_MerkleTrie
*/
library Lib_MerkleTrie {
/*******************
* Data Structures *
*******************/
enum NodeType {
BranchNode,
ExtensionNode,
LeafNode
}
struct TrieNode {
bytes encoded;
Lib_RLPReader.RLPItem[] decoded;
}
/**********************
* Contract Constants *
**********************/
// TREE_RADIX determines the number of elements per branch node.
uint256 constant TREE_RADIX = 16;
// Branch nodes have TREE_RADIX elements plus an additional `value` slot.
uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;
// Leaf nodes and extension nodes always have two elements, a `path` and a `value`.
uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
// Prefixes are prepended to the `path` within a leaf or extension node and
// allow us to differentiate between the two node types. `ODD` or `EVEN` is
// determined by the number of nibbles within the unprefixed `path`. If the
// number of nibbles if even, we need to insert an extra padding nibble so
// the resulting prefixed `path` has an even number of nibbles.
uint8 constant PREFIX_EXTENSION_EVEN = 0;
uint8 constant PREFIX_EXTENSION_ODD = 1;
uint8 constant PREFIX_LEAF_EVEN = 2;
uint8 constant PREFIX_LEAF_ODD = 3;
// Just a utility constant. RLP represents `NULL` as 0x80.
bytes1 constant RLP_NULL = bytes1(0x80);
bytes constant RLP_NULL_BYTES = hex'80';
bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES);
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
(
bool exists,
bytes memory value
) = get(_key, _proof, _root);
return (
exists && Lib_BytesUtils.equal(_value, value)
);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
// Special case when inserting the very first node.
if (_root == KECCAK256_RLP_NULL_BYTES) {
return getSingleNodeRootHash(_key, _value);
}
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root);
TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value);
return _getUpdatedTrieRoot(newPath, _key);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) =
_walkNodePath(proof, _key, _root);
bool exists = keyRemainder.length == 0;
require(
exists || isFinalNode,
"Provided proof is invalid."
);
bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes("");
return (
exists,
value
);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
return keccak256(_makeLeafNode(
Lib_BytesUtils.toNibbles(_key),
_value
).encoded);
}
/*********************
* Private Functions *
*********************/
/**
* @notice Walks through a proof using a provided key.
* @param _proof Inclusion proof to walk through.
* @param _key Key to use for the walk.
* @param _root Known root of the trie.
* @return _pathLength Length of the final path
* @return _keyRemainder Portion of the key remaining after the walk.
* @return _isFinalNode Whether or not we've hit a dead end.
*/
function _walkNodePath(
TrieNode[] memory _proof,
bytes memory _key,
bytes32 _root
)
private
pure
returns (
uint256 _pathLength,
bytes memory _keyRemainder,
bool _isFinalNode
)
{
uint256 pathLength = 0;
bytes memory key = Lib_BytesUtils.toNibbles(_key);
bytes32 currentNodeID = _root;
uint256 currentKeyIndex = 0;
uint256 currentKeyIncrement = 0;
TrieNode memory currentNode;
// Proof is top-down, so we start at the first element (root).
for (uint256 i = 0; i < _proof.length; i++) {
currentNode = _proof[i];
currentKeyIndex += currentKeyIncrement;
// Keep track of the proof elements we actually need.
// It's expensive to resize arrays, so this simply reduces gas costs.
pathLength += 1;
if (currentKeyIndex == 0) {
// First proof element is always the root node.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid root hash"
);
} else if (currentNode.encoded.length >= 32) {
// Nodes 32 bytes or larger are hashed inside branch nodes.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid large internal hash"
);
} else {
// Nodes smaller than 31 bytes aren't hashed.
require(
Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID,
"Invalid internal node hash"
);
}
if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {
if (currentKeyIndex == key.length) {
// We've hit the end of the key
// meaning the value should be within this branch node.
break;
} else {
// We're not at the end of the key yet.
// Figure out what the next node ID should be and continue.
uint8 branchKey = uint8(key[currentKeyIndex]);
Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];
currentNodeID = _getNodeID(nextNode);
currentKeyIncrement = 1;
continue;
}
} else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(currentNode);
uint8 prefix = uint8(path[0]);
uint8 offset = 2 - prefix % 2;
bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset);
bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex);
uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
if (
pathRemainder.length == sharedNibbleLength &&
keyRemainder.length == sharedNibbleLength
) {
// The key within this leaf matches our key exactly.
// Increment the key index to reflect that we have no remainder.
currentKeyIndex += sharedNibbleLength;
}
// We've hit a leaf node, so our next node should be NULL.
currentNodeID = bytes32(RLP_NULL);
break;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
if (sharedNibbleLength != pathRemainder.length) {
// Our extension node is not identical to the remainder.
// We've hit the end of this path
// updates will need to modify this extension.
currentNodeID = bytes32(RLP_NULL);
break;
} else {
// Our extension shares some nibbles.
// Carry on to the next node.
currentNodeID = _getNodeID(currentNode.decoded[1]);
currentKeyIncrement = sharedNibbleLength;
continue;
}
} else {
revert("Received a node with an unknown prefix");
}
} else {
revert("Received an unparseable node.");
}
}
// If our node ID is NULL, then we're at a dead end.
bool isFinalNode = currentNodeID == bytes32(RLP_NULL);
return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode);
}
/**
* @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path.
* @param _path Path to the node nearest the k/v pair.
* @param _pathLength Length of the path. Necessary because the provided path may include
* additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory
* arrays without costly duplication.
* @param _key Full original key.
* @param _keyRemainder Portion of the initial key that must be inserted into the trie.
* @param _value Value to insert at the given key.
* @return _newPath A new path with the inserted k/v pair and extra supporting nodes.
*/
function _getNewPath(
TrieNode[] memory _path,
uint256 _pathLength,
bytes memory _key,
bytes memory _keyRemainder,
bytes memory _value
)
private
pure
returns (
TrieNode[] memory _newPath
)
{
bytes memory keyRemainder = _keyRemainder;
// Most of our logic depends on the status of the last node in the path.
TrieNode memory lastNode = _path[_pathLength - 1];
NodeType lastNodeType = _getNodeType(lastNode);
// Create an array for newly created nodes.
// We need up to three new nodes, depending on the contents of the last node.
// Since array resizing is expensive, we'll keep track of the size manually.
// We're using an explicit `totalNewNodes += 1` after insertions for clarity.
TrieNode[] memory newNodes = new TrieNode[](3);
uint256 totalNewNodes = 0;
// solhint-disable-next-line max-line-length
// Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313
bool matchLeaf = false;
if (lastNodeType == NodeType.LeafNode) {
uint256 l = 0;
if (_path.length > 0) {
for (uint256 i = 0; i < _path.length - 1; i++) {
if (_getNodeType(_path[i]) == NodeType.BranchNode) {
l++;
} else {
l += _getNodeKey(_path[i]).length;
}
}
}
if (
_getSharedNibbleLength(
_getNodeKey(lastNode),
Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l)
) == _getNodeKey(lastNode).length
&& keyRemainder.length == 0
) {
matchLeaf = true;
}
}
if (matchLeaf) {
// We've found a leaf node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value);
totalNewNodes += 1;
} else if (lastNodeType == NodeType.BranchNode) {
if (keyRemainder.length == 0) {
// We've found a branch node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _editBranchValue(lastNode, _value);
totalNewNodes += 1;
} else {
// We've found a branch node, but it doesn't contain our key.
// Reinsert the old branch for now.
newNodes[totalNewNodes] = lastNode;
totalNewNodes += 1;
// Create a new leaf node, slicing our remainder since the first byte points
// to our branch node.
newNodes[totalNewNodes] =
_makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value);
totalNewNodes += 1;
}
} else {
// Our last node is either an extension node or a leaf node with a different key.
bytes memory lastNodeKey = _getNodeKey(lastNode);
uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder);
if (sharedNibbleLength != 0) {
// We've got some shared nibbles between the last node and our key remainder.
// We'll need to insert an extension node that covers these shared nibbles.
bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength);
newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value));
totalNewNodes += 1;
// Cut down the keys since we've just covered these shared nibbles.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength);
keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength);
}
// Create an empty branch to fill in.
TrieNode memory newBranch = _makeEmptyBranchNode();
if (lastNodeKey.length == 0) {
// Key remainder was larger than the key for our last node.
// The value within our last node is therefore going to be shifted into
// a branch value slot.
newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode));
} else {
// Last node key was larger than the key remainder.
// We're going to modify some index of our branch.
uint8 branchKey = uint8(lastNodeKey[0]);
// Move on to the next nibble.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1);
if (lastNodeType == NodeType.LeafNode) {
// We're dealing with a leaf node.
// We'll modify the key and insert the old leaf node into the branch index.
TrieNode memory modifiedLastNode =
_makeLeafNode(lastNodeKey, _getNodeValue(lastNode));
newBranch =
_editBranchIndex(
newBranch,
branchKey,
_getNodeHash(modifiedLastNode.encoded));
} else if (lastNodeKey.length != 0) {
// We're dealing with a shrinking extension node.
// We need to modify the node to decrease the size of the key.
TrieNode memory modifiedLastNode =
_makeExtensionNode(lastNodeKey, _getNodeValue(lastNode));
newBranch =
_editBranchIndex(
newBranch,
branchKey,
_getNodeHash(modifiedLastNode.encoded));
} else {
// We're dealing with an unnecessary extension node.
// We're going to delete the node entirely.
// Simply insert its current value into the branch index.
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode));
}
}
if (keyRemainder.length == 0) {
// We've got nothing left in the key remainder.
// Simply insert the value into the branch value slot.
newBranch = _editBranchValue(newBranch, _value);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
} else {
// We've got some key remainder to work with.
// We'll be inserting a leaf node into the trie.
// First, move on to the next nibble.
keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
// Push a new leaf node for our k/v pair.
newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value);
totalNewNodes += 1;
}
}
// Finally, join the old path with our newly created nodes.
// Since we're overwriting the last node in the path, we use `_pathLength - 1`.
return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes);
}
/**
* @notice Computes the trie root from a given path.
* @param _nodes Path to some k/v pair.
* @param _key Key for the k/v pair.
* @return _updatedRoot Root hash for the updated trie.
*/
function _getUpdatedTrieRoot(
TrieNode[] memory _nodes,
bytes memory _key
)
private
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = Lib_BytesUtils.toNibbles(_key);
// Some variables to keep track of during iteration.
TrieNode memory currentNode;
NodeType currentNodeType;
bytes memory previousNodeHash;
// Run through the path backwards to rebuild our root hash.
for (uint256 i = _nodes.length; i > 0; i--) {
// Pick out the current node.
currentNode = _nodes[i - 1];
currentNodeType = _getNodeType(currentNode);
if (currentNodeType == NodeType.LeafNode) {
// Leaf nodes are already correctly encoded.
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
} else if (currentNodeType == NodeType.ExtensionNode) {
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
currentNode = _editExtensionNodeValue(currentNode, previousNodeHash);
}
} else if (currentNodeType == NodeType.BranchNode) {
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
uint8 branchKey = uint8(key[key.length - 1]);
key = Lib_BytesUtils.slice(key, 0, key.length - 1);
currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash);
}
}
// Compute the node hash for the next iteration.
previousNodeHash = _getNodeHash(currentNode.encoded);
}
// Current node should be the root at this point.
// Simply return the hash of its encoding.
return keccak256(currentNode.encoded);
}
/**
* @notice Parses an RLP-encoded proof into something more useful.
* @param _proof RLP-encoded proof to parse.
* @return _parsed Proof parsed into easily accessible structs.
*/
function _parseProof(
bytes memory _proof
)
private
pure
returns (
TrieNode[] memory _parsed
)
{
Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof);
TrieNode[] memory proof = new TrieNode[](nodes.length);
for (uint256 i = 0; i < nodes.length; i++) {
bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]);
proof[i] = TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
return proof;
}
/**
* @notice Picks out the ID for a node. Node ID is referred to as the
* "hash" within the specification, but nodes < 32 bytes are not actually
* hashed.
* @param _node Node to pull an ID for.
* @return _nodeID ID for the node, depending on the size of its contents.
*/
function _getNodeID(
Lib_RLPReader.RLPItem memory _node
)
private
pure
returns (
bytes32 _nodeID
)
{
bytes memory nodeID;
if (_node.length < 32) {
// Nodes smaller than 32 bytes are RLP encoded.
nodeID = Lib_RLPReader.readRawBytes(_node);
} else {
// Nodes 32 bytes or larger are hashed.
nodeID = Lib_RLPReader.readBytes(_node);
}
return Lib_BytesUtils.toBytes32(nodeID);
}
/**
* @notice Gets the path for a leaf or extension node.
* @param _node Node to get a path for.
* @return _path Node path, converted to an array of nibbles.
*/
function _getNodePath(
TrieNode memory _node
)
private
pure
returns (
bytes memory _path
)
{
return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0]));
}
/**
* @notice Gets the key for a leaf or extension node. Keys are essentially
* just paths without any prefix.
* @param _node Node to get a key for.
* @return _key Node key, converted to an array of nibbles.
*/
function _getNodeKey(
TrieNode memory _node
)
private
pure
returns (
bytes memory _key
)
{
return _removeHexPrefix(_getNodePath(_node));
}
/**
* @notice Gets the path for a node.
* @param _node Node to get a value for.
* @return _value Node value, as hex bytes.
*/
function _getNodeValue(
TrieNode memory _node
)
private
pure
returns (
bytes memory _value
)
{
return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]);
}
/**
* @notice Computes the node hash for an encoded node. Nodes < 32 bytes
* are not hashed, all others are keccak256 hashed.
* @param _encoded Encoded node to hash.
* @return _hash Hash of the encoded node. Simply the input if < 32 bytes.
*/
function _getNodeHash(
bytes memory _encoded
)
private
pure
returns (
bytes memory _hash
)
{
if (_encoded.length < 32) {
return _encoded;
} else {
return abi.encodePacked(keccak256(_encoded));
}
}
/**
* @notice Determines the type for a given node.
* @param _node Node to determine a type for.
* @return _type Type of the node; BranchNode/ExtensionNode/LeafNode.
*/
function _getNodeType(
TrieNode memory _node
)
private
pure
returns (
NodeType _type
)
{
if (_node.decoded.length == BRANCH_NODE_LENGTH) {
return NodeType.BranchNode;
} else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(_node);
uint8 prefix = uint8(path[0]);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
return NodeType.LeafNode;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
return NodeType.ExtensionNode;
}
}
revert("Invalid node type");
}
/**
* @notice Utility; determines the number of nibbles shared between two
* nibble arrays.
* @param _a First nibble array.
* @param _b Second nibble array.
* @return _shared Number of shared nibbles.
*/
function _getSharedNibbleLength(
bytes memory _a,
bytes memory _b
)
private
pure
returns (
uint256 _shared
)
{
uint256 i = 0;
while (_a.length > i && _b.length > i && _a[i] == _b[i]) {
i++;
}
return i;
}
/**
* @notice Utility; converts an RLP-encoded node into our nice struct.
* @param _raw RLP-encoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
bytes[] memory _raw
)
private
pure
returns (
TrieNode memory _node
)
{
bytes memory encoded = Lib_RLPWriter.writeList(_raw);
return TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
/**
* @notice Utility; converts an RLP-decoded node into our nice struct.
* @param _items RLP-decoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
Lib_RLPReader.RLPItem[] memory _items
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](_items.length);
for (uint256 i = 0; i < _items.length; i++) {
raw[i] = Lib_RLPReader.readRawBytes(_items[i]);
}
return _makeNode(raw);
}
/**
* @notice Creates a new extension node.
* @param _key Key for the extension node, unprefixed.
* @param _value Value for the extension node.
* @return _node New extension node with the given k/v pair.
*/
function _makeExtensionNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* Creates a new extension node with the same key but a different value.
* @param _node Extension node to copy and modify.
* @param _value New value for the extension node.
* @return New node with the same key and different value.
*/
function _editExtensionNodeValue(
TrieNode memory _node,
bytes memory _value
)
private
pure
returns (
TrieNode memory
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_getNodeKey(_node), false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
if (_value.length < 32) {
raw[1] = _value;
} else {
raw[1] = Lib_RLPWriter.writeBytes(_value);
}
return _makeNode(raw);
}
/**
* @notice Creates a new leaf node.
* @dev This function is essentially identical to `_makeExtensionNode`.
* Although we could route both to a single method with a flag, it's
* more gas efficient to keep them separate and duplicate the logic.
* @param _key Key for the leaf node, unprefixed.
* @param _value Value for the leaf node.
* @return _node New leaf node with the given k/v pair.
*/
function _makeLeafNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, true);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* @notice Creates an empty branch node.
* @return _node Empty branch node as a TrieNode struct.
*/
function _makeEmptyBranchNode()
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH);
for (uint256 i = 0; i < raw.length; i++) {
raw[i] = RLP_NULL_BYTES;
}
return _makeNode(raw);
}
/**
* @notice Modifies the value slot for a given branch.
* @param _branch Branch node to modify.
* @param _value Value to insert into the branch.
* @return _updatedNode Modified branch node.
*/
function _editBranchValue(
TrieNode memory _branch,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Modifies a slot at an index for a given branch.
* @param _branch Branch node to modify.
* @param _index Slot index to modify.
* @param _value Value to insert into the slot.
* @return _updatedNode Modified branch node.
*/
function _editBranchIndex(
TrieNode memory _branch,
uint8 _index,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Utility; adds a prefix to a key.
* @param _key Key to prefix.
* @param _isLeaf Whether or not the key belongs to a leaf.
* @return _prefixedKey Prefixed key.
*/
function _addHexPrefix(
bytes memory _key,
bool _isLeaf
)
private
pure
returns (
bytes memory _prefixedKey
)
{
uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00);
uint8 offset = uint8(_key.length % 2);
bytes memory prefixed = new bytes(2 - offset);
prefixed[0] = bytes1(prefix + offset);
return abi.encodePacked(prefixed, _key);
}
/**
* @notice Utility; removes a prefix from a path.
* @param _path Path to remove the prefix from.
* @return _unprefixedKey Unprefixed key.
*/
function _removeHexPrefix(
bytes memory _path
)
private
pure
returns (
bytes memory _unprefixedKey
)
{
if (uint8(_path[0]) % 2 == 0) {
return Lib_BytesUtils.slice(_path, 2);
} else {
return Lib_BytesUtils.slice(_path, 1);
}
}
/**
* @notice Utility; combines two node arrays. Array lengths are required
* because the actual lengths may be longer than the filled lengths.
* Array resizing is extremely costly and should be avoided.
* @param _a First array to join.
* @param _aLength Length of the first array.
* @param _b Second array to join.
* @param _bLength Length of the second array.
* @return _joined Combined node array.
*/
function _joinNodeArrays(
TrieNode[] memory _a,
uint256 _aLength,
TrieNode[] memory _b,
uint256 _bLength
)
private
pure
returns (
TrieNode[] memory _joined
)
{
TrieNode[] memory ret = new TrieNode[](_aLength + _bLength);
// Copy elements from the first array.
for (uint256 i = 0; i < _aLength; i++) {
ret[i] = _a[i];
}
// Copy elements from the second array.
for (uint256 i = 0; i < _bLength; i++) {
ret[i + _aLength] = _b[i];
}
return ret;
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_StateTransitionerFactory } from
"../../iOVM/verification/iOVM_StateTransitionerFactory.sol";
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
/* Contract Imports */
import { OVM_StateTransitioner } from "./OVM_StateTransitioner.sol";
/**
* @title OVM_StateTransitionerFactory
* @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State
* Transitioner during the initialization of a fraud proof.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver {
/***************
* Constructor *
***************/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/********************
* Public Functions *
********************/
/**
* Creates a new OVM_StateTransitioner
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
* @return New OVM_StateTransitioner instance.
*/
function create(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
override
public
returns (
iOVM_StateTransitioner
)
{
require(
msg.sender == resolve("OVM_FraudVerifier"),
"Create can only be done by the OVM_FraudVerifier."
);
return new OVM_StateTransitioner(
_libAddressManager,
_stateTransitionIndex,
_preStateRoot,
_transactionHash
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_StateTransitionerFactory
*/
interface iOVM_StateTransitionerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _proxyManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
external
returns (
iOVM_StateTransitioner _ovmStateTransitioner
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_FraudVerifier
*/
interface iOVM_FraudVerifier {
/**********
* Events *
**********/
event FraudProofInitialized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
event FraudProofFinalized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
/***************************************
* Public Functions: Transition Status *
***************************************/
function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view
returns (iOVM_StateTransitioner _transitioner);
/****************************************
* Public Functions: Fraud Verification *
****************************************/
function initializeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
Lib_OVMCodec.Transaction calldata _transaction,
Lib_OVMCodec.TransactionChainElement calldata _txChainElement,
Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _transactionProof
) external;
function finalizeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
bytes32 _txHash,
bytes32 _postStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_StateTransitionerFactory } from
"../../iOVM/verification/iOVM_StateTransitionerFactory.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol";
import { iOVM_CanonicalTransactionChain } from
"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
/* Contract Imports */
import { Abs_FraudContributor } from "./Abs_FraudContributor.sol";
/**
* @title OVM_FraudVerifier
* @dev The Fraud Verifier contract coordinates the entire fraud proof verification process.
* If the fraud proof was successful it prunes any state batches from State Commitment Chain
* which were published after the fraudulent state root.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_FraudVerifier is Lib_AddressResolver, Abs_FraudContributor, iOVM_FraudVerifier {
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
mapping (bytes32 => iOVM_StateTransitioner) internal transitioners;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/***************************************
* Public Functions: Transition Status *
***************************************/
/**
* Retrieves the state transitioner for a given root.
* @param _preStateRoot State root to query a transitioner for.
* @return _transitioner Corresponding state transitioner contract.
*/
function getStateTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash
)
override
public
view
returns (
iOVM_StateTransitioner _transitioner
)
{
return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))];
}
/****************************************
* Public Functions: Fraud Verification *
****************************************/
/**
* Begins the fraud verification process.
* @param _preStateRoot State root before the fraudulent transaction.
* @param _preStateRootBatchHeader Batch header for the provided pre-state root.
* @param _preStateRootProof Inclusion proof for the provided pre-state root.
* @param _transaction OVM transaction claimed to be fraudulent.
* @param _txChainElement OVM transaction chain element.
* @param _transactionBatchHeader Batch header for the provided transaction.
* @param _transactionProof Inclusion proof for the provided transaction.
*/
function initializeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof,
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _transactionBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _transactionProof
)
override
public
contributesToFraudProof(_preStateRoot, Lib_OVMCodec.hashTransaction(_transaction))
{
bytes32 _txHash = Lib_OVMCodec.hashTransaction(_transaction);
if (_hasStateTransitioner(_preStateRoot, _txHash)) {
return;
}
iOVM_StateCommitmentChain ovmStateCommitmentChain =
iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain"));
iOVM_CanonicalTransactionChain ovmCanonicalTransactionChain =
iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain"));
require(
ovmStateCommitmentChain.verifyStateCommitment(
_preStateRoot,
_preStateRootBatchHeader,
_preStateRootProof
),
"Invalid pre-state root inclusion proof."
);
require(
ovmCanonicalTransactionChain.verifyTransaction(
_transaction,
_txChainElement,
_transactionBatchHeader,
_transactionProof
),
"Invalid transaction inclusion proof."
);
require (
// solhint-disable-next-line max-line-length
_preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1 == _transactionBatchHeader.prevTotalElements + _transactionProof.index,
"Pre-state root global index must equal to the transaction root global index."
);
_deployTransitioner(_preStateRoot, _txHash, _preStateRootProof.index);
emit FraudProofInitialized(
_preStateRoot,
_preStateRootProof.index,
_txHash,
msg.sender
);
}
/**
* Finalizes the fraud verification process.
* @param _preStateRoot State root before the fraudulent transaction.
* @param _preStateRootBatchHeader Batch header for the provided pre-state root.
* @param _preStateRootProof Inclusion proof for the provided pre-state root.
* @param _txHash The transaction for the state root
* @param _postStateRoot State root after the fraudulent transaction.
* @param _postStateRootBatchHeader Batch header for the provided post-state root.
* @param _postStateRootProof Inclusion proof for the provided post-state root.
*/
function finalizeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader memory _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _preStateRootProof,
bytes32 _txHash,
bytes32 _postStateRoot,
Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof memory _postStateRootProof
)
override
public
contributesToFraudProof(_preStateRoot, _txHash)
{
iOVM_StateTransitioner transitioner = getStateTransitioner(_preStateRoot, _txHash);
iOVM_StateCommitmentChain ovmStateCommitmentChain =
iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain"));
require(
transitioner.isComplete() == true,
"State transition process must be completed prior to finalization."
);
require (
// solhint-disable-next-line max-line-length
_postStateRootBatchHeader.prevTotalElements + _postStateRootProof.index == _preStateRootBatchHeader.prevTotalElements + _preStateRootProof.index + 1,
"Post-state root global index must equal to the pre state root global index plus one."
);
require(
ovmStateCommitmentChain.verifyStateCommitment(
_preStateRoot,
_preStateRootBatchHeader,
_preStateRootProof
),
"Invalid pre-state root inclusion proof."
);
require(
ovmStateCommitmentChain.verifyStateCommitment(
_postStateRoot,
_postStateRootBatchHeader,
_postStateRootProof
),
"Invalid post-state root inclusion proof."
);
// If the post state root did not match, then there was fraud and we should delete the batch
require(
_postStateRoot != transitioner.getPostStateRoot(),
"State transition has not been proven fraudulent."
);
_cancelStateTransition(_postStateRootBatchHeader, _preStateRoot);
// TEMPORARY: Remove the transitioner; for minnet.
transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] =
iOVM_StateTransitioner(0x0000000000000000000000000000000000000000);
emit FraudProofFinalized(
_preStateRoot,
_preStateRootProof.index,
_txHash,
msg.sender
);
}
/************************************
* Internal Functions: Verification *
************************************/
/**
* Checks whether a transitioner already exists for a given pre-state root.
* @param _preStateRoot Pre-state root to check.
* @return _exists Whether or not we already have a transitioner for the root.
*/
function _hasStateTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash
)
internal
view
returns (
bool _exists
)
{
return address(getStateTransitioner(_preStateRoot, _txHash)) != address(0);
}
/**
* Deploys a new state transitioner.
* @param _preStateRoot Pre-state root to initialize the transitioner with.
* @param _txHash Hash of the transaction this transitioner will execute.
* @param _stateTransitionIndex Index of the transaction in the chain.
*/
function _deployTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash,
uint256 _stateTransitionIndex
)
internal
{
transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))] =
iOVM_StateTransitionerFactory(
resolve("OVM_StateTransitionerFactory")
).create(
address(libAddressManager),
_stateTransitionIndex,
_preStateRoot,
_txHash
);
}
/**
* Removes a state transition from the state commitment chain.
* @param _postStateRootBatchHeader Header for the post-state root.
* @param _preStateRoot Pre-state root hash.
*/
function _cancelStateTransition(
Lib_OVMCodec.ChainBatchHeader memory _postStateRootBatchHeader,
bytes32 _preStateRoot
)
internal
{
iOVM_StateCommitmentChain ovmStateCommitmentChain =
iOVM_StateCommitmentChain(resolve("OVM_StateCommitmentChain"));
iOVM_BondManager ovmBondManager = iOVM_BondManager(resolve("OVM_BondManager"));
// Delete the state batch.
ovmStateCommitmentChain.deleteStateBatch(
_postStateRootBatchHeader
);
// Get the timestamp and publisher for that block.
(uint256 timestamp, address publisher) =
abi.decode(_postStateRootBatchHeader.extraData, (uint256, address));
// Slash the bonds at the bond manager.
ovmBondManager.finalize(
_preStateRoot,
publisher,
timestamp
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateCommitmentChain
*/
interface iOVM_StateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp()
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(
bytes32[] calldata _batch,
uint256 _shouldStartAtElement
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_ChainStorageContainer } from "./iOVM_ChainStorageContainer.sol";
/**
* @title iOVM_CanonicalTransactionChain
*/
interface iOVM_CanonicalTransactionChain {
/**********
* Events *
**********/
event TransactionEnqueued(
address _l1TxOrigin,
address _target,
uint256 _gasLimit,
bytes _data,
uint256 _queueIndex,
uint256 _timestamp
);
event QueueBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event SequencerBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event TransactionBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
/***********
* Structs *
***********/
struct BatchContext {
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 timestamp;
uint256 blockNumber;
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches()
external
view
returns (
iOVM_ChainStorageContainer
);
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue()
external
view
returns (
iOVM_ChainStorageContainer
);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
external
view
returns (
uint256 _totalBatches
);
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex()
external
view
returns (
uint40
);
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(
uint256 _index
)
external
view
returns (
Lib_OVMCodec.QueueElement memory _element
);
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp()
external
view
returns (
uint40
);
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber()
external
view
returns (
uint40
);
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements()
external
view
returns (
uint40
);
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength()
external
view
returns (
uint40
);
/**
* Adds a transaction to the queue.
* @param _target Target contract to send the transaction to.
* @param _gasLimit Gas limit for the given transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
external;
/**
* Appends a given number of queued transactions as a single batch.
* @param _numQueuedTransactions Number of transactions to append.
*/
function appendQueueBatch(
uint256 _numQueuedTransactions
)
external;
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch(
// uint40 _shouldStartAtElement,
// uint24 _totalElementsToAppend,
// BatchContext[] _contexts,
// bytes[] _transactionDataFields
)
external;
/**
* Verifies whether a transaction is included in the chain.
* @param _transaction Transaction to verify.
* @param _txChainElement Transaction chain element corresponding to the transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof Inclusion proof for the provided transaction chain element.
* @return True if the transaction exists in the CTC, false if not.
*/
function verifyTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
external
view
returns (
bool
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_ChainStorageContainer
*/
interface iOVM_ChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata()
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length()
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_BondManager, Errors, ERC20 } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
/**
* @title OVM_BondManager
* @dev The Bond Manager contract handles deposits in the form of an ERC20 token from bonded
* Proposers. It also handles the accounting of gas costs spent by a Verifier during the course of a
* fraud proof. In the event of a successful fraud proof, the fraudulent Proposer's bond is slashed,
* and the Verifier's gas costs are refunded.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_BondManager is iOVM_BondManager, Lib_AddressResolver {
/****************************
* Constants and Parameters *
****************************/
/// The period to find the earliest fraud proof for a publisher
uint256 public constant multiFraudProofPeriod = 7 days;
/// The dispute period
uint256 public constant disputePeriodSeconds = 7 days;
/// The minimum collateral a sequencer must post
uint256 public constant requiredCollateral = 1 ether;
/*******************************************
* Contract Variables: Contract References *
*******************************************/
/// The bond token
ERC20 immutable public token;
/********************************************
* Contract Variables: Internal Accounting *
*******************************************/
/// The bonds posted by each proposer
mapping(address => Bond) public bonds;
/// For each pre-state root, there's an array of witnessProviders that must be rewarded
/// for posting witnesses
mapping(bytes32 => Rewards) public witnessProviders;
/***************
* Constructor *
***************/
/// Initializes with a ERC20 token to be used for the fidelity bonds
/// and with the Address Manager
constructor(
ERC20 _token,
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{
token = _token;
}
/********************
* Public Functions *
********************/
/// Adds `who` to the list of witnessProviders for the provided `preStateRoot`.
function recordGasSpent(bytes32 _preStateRoot, bytes32 _txHash, address who, uint256 gasSpent)
override public {
// The sender must be the transitioner that corresponds to the claimed pre-state root
address transitioner =
address(iOVM_FraudVerifier(resolve("OVM_FraudVerifier"))
.getStateTransitioner(_preStateRoot, _txHash));
require(transitioner == msg.sender, Errors.ONLY_TRANSITIONER);
witnessProviders[_preStateRoot].total += gasSpent;
witnessProviders[_preStateRoot].gasSpent[who] += gasSpent;
}
/// Slashes + distributes rewards or frees up the sequencer's bond, only called by
/// `FraudVerifier.finalizeFraudVerification`
function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) override public {
require(msg.sender == resolve("OVM_FraudVerifier"), Errors.ONLY_FRAUD_VERIFIER);
require(witnessProviders[_preStateRoot].canClaim == false, Errors.ALREADY_FINALIZED);
// allow users to claim from that state root's
// pool of collateral (effectively slashing the sequencer)
witnessProviders[_preStateRoot].canClaim = true;
Bond storage bond = bonds[publisher];
if (bond.firstDisputeAt == 0) {
bond.firstDisputeAt = block.timestamp;
bond.earliestDisputedStateRoot = _preStateRoot;
bond.earliestTimestamp = timestamp;
} else if (
// only update the disputed state root for the publisher if it's within
// the dispute period _and_ if it's before the previous one
block.timestamp < bond.firstDisputeAt + multiFraudProofPeriod &&
timestamp < bond.earliestTimestamp
) {
bond.earliestDisputedStateRoot = _preStateRoot;
bond.earliestTimestamp = timestamp;
}
// if the fraud proof's dispute period does not intersect with the
// withdrawal's timestamp, then the user should not be slashed
// e.g if a user at day 10 submits a withdrawal, and a fraud proof
// from day 1 gets published, the user won't be slashed since day 8 (1d + 7d)
// is before the user started their withdrawal. on the contrary, if the user
// had started their withdrawal at, say, day 6, they would be slashed
if (
bond.withdrawalTimestamp != 0 &&
uint256(bond.withdrawalTimestamp) > timestamp + disputePeriodSeconds &&
bond.state == State.WITHDRAWING
) {
return;
}
// slash!
bond.state = State.NOT_COLLATERALIZED;
}
/// Sequencers call this function to post collateral which will be used for
/// the `appendBatch` call
function deposit() override public {
require(
token.transferFrom(msg.sender, address(this), requiredCollateral),
Errors.ERC20_ERR
);
// This cannot overflow
bonds[msg.sender].state = State.COLLATERALIZED;
}
/// Starts the withdrawal for a publisher
function startWithdrawal() override public {
Bond storage bond = bonds[msg.sender];
require(bond.withdrawalTimestamp == 0, Errors.WITHDRAWAL_PENDING);
require(bond.state == State.COLLATERALIZED, Errors.WRONG_STATE);
bond.state = State.WITHDRAWING;
bond.withdrawalTimestamp = uint32(block.timestamp);
}
/// Finalizes a pending withdrawal from a publisher
function finalizeWithdrawal() override public {
Bond storage bond = bonds[msg.sender];
require(
block.timestamp >= uint256(bond.withdrawalTimestamp) + disputePeriodSeconds,
Errors.TOO_EARLY
);
require(bond.state == State.WITHDRAWING, Errors.SLASHED);
// refunds!
bond.state = State.NOT_COLLATERALIZED;
bond.withdrawalTimestamp = 0;
require(
token.transfer(msg.sender, requiredCollateral),
Errors.ERC20_ERR
);
}
/// Claims the user's reward for the witnesses they provided for the earliest
/// disputed state root of the designated publisher
function claim(address who) override public {
Bond storage bond = bonds[who];
require(
block.timestamp >= bond.firstDisputeAt + multiFraudProofPeriod,
Errors.WAIT_FOR_DISPUTES
);
// reward the earliest state root for this publisher
bytes32 _preStateRoot = bond.earliestDisputedStateRoot;
Rewards storage rewards = witnessProviders[_preStateRoot];
// only allow claiming if fraud was proven in `finalize`
require(rewards.canClaim, Errors.CANNOT_CLAIM);
// proportional allocation - only reward 50% (rest gets locked in the
// contract forever
uint256 amount = (requiredCollateral * rewards.gasSpent[msg.sender]) / (2 * rewards.total);
// reset the user's spent gas so they cannot double claim
rewards.gasSpent[msg.sender] = 0;
// transfer
require(token.transfer(msg.sender, amount), Errors.ERC20_ERR);
}
/// Checks if the user is collateralized
function isCollateralized(address who) override public view returns (bool) {
return bonds[who].state == State.COLLATERALIZED;
}
/// Gets how many witnesses the user has provided for the state root
function getGasSpent(bytes32 preStateRoot, address who) override public view returns (uint256) {
return witnessProviders[preStateRoot].gasSpent[who];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
import { OVM_BondManager } from "./../optimistic-ethereum/OVM/verification/OVM_BondManager.sol";
contract Mock_FraudVerifier {
OVM_BondManager bondManager;
mapping (bytes32 => address) transitioners;
function setBondManager(OVM_BondManager _bondManager) public {
bondManager = _bondManager;
}
function setStateTransitioner(bytes32 preStateRoot, bytes32 txHash, address addr) public {
transitioners[keccak256(abi.encodePacked(preStateRoot, txHash))] = addr;
}
function getStateTransitioner(
bytes32 _preStateRoot,
bytes32 _txHash
)
public
view
returns (
address
)
{
return transitioners[keccak256(abi.encodePacked(_preStateRoot, _txHash))];
}
function finalize(bytes32 _preStateRoot, address publisher, uint256 timestamp) public {
bondManager.finalize(_preStateRoot, publisher, timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol";
/* Interface Imports */
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
import { iOVM_StateCommitmentChain } from "../../iOVM/chain/iOVM_StateCommitmentChain.sol";
import { iOVM_CanonicalTransactionChain } from
"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol";
/* External Imports */
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title OVM_StateCommitmentChain
* @dev The State Commitment Chain (SCC) contract contains a list of proposed state roots which
* Proposers assert to be a result of each transaction in the Canonical Transaction Chain (CTC).
* Elements here have a 1:1 correspondence with transactions in the CTC, and should be the unique
* state root calculated off-chain by applying the canonical transactions one by one.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateCommitmentChain is iOVM_StateCommitmentChain, Lib_AddressResolver {
/*************
* Constants *
*************/
uint256 public FRAUD_PROOF_WINDOW;
uint256 public SEQUENCER_PUBLISH_WINDOW;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager,
uint256 _fraudProofWindow,
uint256 _sequencerPublishWindow
)
Lib_AddressResolver(_libAddressManager)
{
FRAUD_PROOF_WINDOW = _fraudProofWindow;
SEQUENCER_PUBLISH_WINDOW = _sequencerPublishWindow;
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches()
public
view
returns (
iOVM_ChainStorageContainer
)
{
return iOVM_ChainStorageContainer(
resolve("OVM_ChainStorageContainer-SCC-batches")
);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function getTotalElements()
override
public
view
returns (
uint256 _totalElements
)
{
(uint40 totalElements, ) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function getTotalBatches()
override
public
view
returns (
uint256 _totalBatches
)
{
return batches().length();
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function getLastSequencerTimestamp()
override
public
view
returns (
uint256 _lastSequencerTimestamp
)
{
(, uint40 lastSequencerTimestamp) = _getBatchExtraData();
return uint256(lastSequencerTimestamp);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function appendStateBatch(
bytes32[] memory _batch,
uint256 _shouldStartAtElement
)
override
public
{
// Fail fast in to make sure our batch roots aren't accidentally made fraudulent by the
// publication of batches by some other user.
require(
_shouldStartAtElement == getTotalElements(),
"Actual batch start index does not match expected start index."
);
// Proposers must have previously staked at the BondManager
require(
iOVM_BondManager(resolve("OVM_BondManager")).isCollateralized(msg.sender),
"Proposer does not have enough collateral posted"
);
require(
_batch.length > 0,
"Cannot submit an empty state batch."
);
require(
getTotalElements() + _batch.length <=
iOVM_CanonicalTransactionChain(resolve("OVM_CanonicalTransactionChain"))
.getTotalElements(),
"Number of state roots cannot exceed the number of canonical transactions."
);
// Pass the block's timestamp and the publisher of the data
// to be used in the fraud proofs
_appendBatch(
_batch,
abi.encode(block.timestamp, msg.sender)
);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function deleteStateBatch(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
override
public
{
require(
msg.sender == resolve("OVM_FraudVerifier"),
"State batches can only be deleted by the OVM_FraudVerifier."
);
require(
_isValidBatchHeader(_batchHeader),
"Invalid batch header."
);
require(
insideFraudProofWindow(_batchHeader),
"State batches can only be deleted within the fraud proof window."
);
_deleteBatch(_batchHeader);
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
override
public
view
returns (
bool
)
{
require(
_isValidBatchHeader(_batchHeader),
"Invalid batch header."
);
require(
Lib_MerkleTree.verify(
_batchHeader.batchRoot,
_element,
_proof.index,
_proof.siblings,
_batchHeader.batchSize
),
"Invalid inclusion proof."
);
return true;
}
/**
* @inheritdoc iOVM_StateCommitmentChain
*/
function insideFraudProofWindow(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
override
public
view
returns (
bool _inside
)
{
(uint256 timestamp,) = abi.decode(
_batchHeader.extraData,
(uint256, address)
);
require(
timestamp != 0,
"Batch header timestamp cannot be zero"
);
return SafeMath.add(timestamp, FRAUD_PROOF_WINDOW) > block.timestamp;
}
/**********************
* Internal Functions *
**********************/
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Timestamp of the last batch submitted by the sequencer.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
// solhint-disable max-line-length
uint40 totalElements;
uint40 lastSequencerTimestamp;
assembly {
extraData := shr(40, extraData)
totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
lastSequencerTimestamp := shr(40, and(extraData, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))
}
// solhint-enable max-line-length
return (
totalElements,
lastSequencerTimestamp
);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _lastSequencerTimestamp Timestamp of the last batch submitted by the sequencer.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _lastSequencerTimestamp
)
internal
pure
returns (
bytes27
)
{
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _lastSequencerTimestamp))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Appends a batch to the chain.
* @param _batch Elements within the batch.
* @param _extraData Any extra data to append to the batch.
*/
function _appendBatch(
bytes32[] memory _batch,
bytes memory _extraData
)
internal
{
address sequencer = resolve("OVM_Proposer");
(uint40 totalElements, uint40 lastSequencerTimestamp) = _getBatchExtraData();
if (msg.sender == sequencer) {
lastSequencerTimestamp = uint40(block.timestamp);
} else {
// We keep track of the last batch submitted by the sequencer so there's a window in
// which only the sequencer can publish state roots. A window like this just reduces
// the chance of "system breaking" state roots being published while we're still in
// testing mode. This window should be removed or significantly reduced in the future.
require(
lastSequencerTimestamp + SEQUENCER_PUBLISH_WINDOW < block.timestamp,
"Cannot publish state roots within the sequencer publication window."
);
}
// For efficiency reasons getMerkleRoot modifies the `_batch` argument in place
// while calculating the root hash therefore any arguments passed to it must not
// be used again afterwards
Lib_OVMCodec.ChainBatchHeader memory batchHeader = Lib_OVMCodec.ChainBatchHeader({
batchIndex: getTotalBatches(),
batchRoot: Lib_MerkleTree.getMerkleRoot(_batch),
batchSize: _batch.length,
prevTotalElements: totalElements,
extraData: _extraData
});
emit StateBatchAppended(
batchHeader.batchIndex,
batchHeader.batchRoot,
batchHeader.batchSize,
batchHeader.prevTotalElements,
batchHeader.extraData
);
batches().push(
Lib_OVMCodec.hashBatchHeader(batchHeader),
_makeBatchExtraData(
uint40(batchHeader.prevTotalElements + batchHeader.batchSize),
lastSequencerTimestamp
)
);
}
/**
* Removes a batch and all subsequent batches from the chain.
* @param _batchHeader Header of the batch to remove.
*/
function _deleteBatch(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
{
require(
_batchHeader.batchIndex < batches().length(),
"Invalid batch index."
);
require(
_isValidBatchHeader(_batchHeader),
"Invalid batch header."
);
batches().deleteElementsAfterInclusive(
_batchHeader.batchIndex,
_makeBatchExtraData(
uint40(_batchHeader.prevTotalElements),
0
)
);
emit StateBatchDeleted(
_batchHeader.batchIndex,
_batchHeader.batchRoot
);
}
/**
* Checks that a batch header matches the stored hash for the given index.
* @param _batchHeader Batch header to validate.
* @return Whether or not the header matches the stored one.
*/
function _isValidBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
view
returns (
bool
)
{
return Lib_OVMCodec.hashBatchHeader(_batchHeader) == batches().get(_batchHeader.batchIndex);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_MerkleTree
* @author River Keefer
*/
library Lib_MerkleTree {
/**********************
* Internal Functions *
**********************/
/**
* Calculates a merkle root for a list of 32-byte leaf hashes. WARNING: If the number
* of leaves passed in is not a power of two, it pads out the tree with zero hashes.
* If you do not know the original length of elements for the tree you are verifying, then
* this may allow empty leaves past _elements.length to pass a verification check down the line.
* Note that the _elements argument is modified, therefore it must not be used again afterwards
* @param _elements Array of hashes from which to generate a merkle root.
* @return Merkle root of the leaves, with zero hashes for non-powers-of-two (see above).
*/
function getMerkleRoot(
bytes32[] memory _elements
)
internal
pure
returns (
bytes32
)
{
require(
_elements.length > 0,
"Lib_MerkleTree: Must provide at least one leaf hash."
);
if (_elements.length == 1) {
return _elements[0];
}
uint256[16] memory defaults = [
0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563,
0x633dc4d7da7256660a892f8f1604a44b5432649cc8ec5cb3ced4c4e6ac94dd1d,
0x890740a8eb06ce9be422cb8da5cdafc2b58c0a5e24036c578de2a433c828ff7d,
0x3b8ec09e026fdc305365dfc94e189a81b38c7597b3d941c279f042e8206e0bd8,
0xecd50eee38e386bd62be9bedb990706951b65fe053bd9d8a521af753d139e2da,
0xdefff6d330bb5403f63b14f33b578274160de3a50df4efecf0e0db73bcdd3da5,
0x617bdd11f7c0a11f49db22f629387a12da7596f9d1704d7465177c63d88ec7d7,
0x292c23a9aa1d8bea7e2435e555a4a60e379a5a35f3f452bae60121073fb6eead,
0xe1cea92ed99acdcb045a6726b2f87107e8a61620a232cf4d7d5b5766b3952e10,
0x7ad66c0a68c72cb89e4fb4303841966e4062a76ab97451e3b9fb526a5ceb7f82,
0xe026cc5a4aed3c22a58cbd3d2ac754c9352c5436f638042dca99034e83636516,
0x3d04cffd8b46a874edf5cfae63077de85f849a660426697b06a829c70dd1409c,
0xad676aa337a485e4728a0b240d92b3ef7b3c372d06d189322bfd5f61f1e7203e,
0xa2fca4a49658f9fab7aa63289c91b7c7b6c832a6d0e69334ff5b0a3483d09dab,
0x4ebfd9cd7bca2505f7bef59cc1c12ecc708fff26ae4af19abe852afe9e20c862,
0x2def10d13dd169f550f578bda343d9717a138562e0093b380a1120789d53cf10
];
// Reserve memory space for our hashes.
bytes memory buf = new bytes(64);
// We'll need to keep track of left and right siblings.
bytes32 leftSibling;
bytes32 rightSibling;
// Number of non-empty nodes at the current depth.
uint256 rowSize = _elements.length;
// Current depth, counting from 0 at the leaves
uint256 depth = 0;
// Common sub-expressions
uint256 halfRowSize; // rowSize / 2
bool rowSizeIsOdd; // rowSize % 2 == 1
while (rowSize > 1) {
halfRowSize = rowSize / 2;
rowSizeIsOdd = rowSize % 2 == 1;
for (uint256 i = 0; i < halfRowSize; i++) {
leftSibling = _elements[(2 * i) ];
rightSibling = _elements[(2 * i) + 1];
assembly {
mstore(add(buf, 32), leftSibling )
mstore(add(buf, 64), rightSibling)
}
_elements[i] = keccak256(buf);
}
if (rowSizeIsOdd) {
leftSibling = _elements[rowSize - 1];
rightSibling = bytes32(defaults[depth]);
assembly {
mstore(add(buf, 32), leftSibling)
mstore(add(buf, 64), rightSibling)
}
_elements[halfRowSize] = keccak256(buf);
}
rowSize = halfRowSize + (rowSizeIsOdd ? 1 : 0);
depth++;
}
return _elements[0];
}
/**
* Verifies a merkle branch for the given leaf hash. Assumes the original length
* of leaves generated is a known, correct input, and does not return true for indices
* extending past that index (even if _siblings would be otherwise valid.)
* @param _root The Merkle root to verify against.
* @param _leaf The leaf hash to verify inclusion of.
* @param _index The index in the tree of this leaf.
* @param _siblings Array of sibline nodes in the inclusion proof, starting from depth 0
* (bottom of the tree).
* @param _totalLeaves The total number of leaves originally passed into.
* @return Whether or not the merkle branch and leaf passes verification.
*/
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
)
internal
pure
returns (
bool
)
{
require(
_totalLeaves > 0,
"Lib_MerkleTree: Total leaves must be greater than zero."
);
require(
_index < _totalLeaves,
"Lib_MerkleTree: Index out of bounds."
);
require(
_siblings.length == _ceilLog2(_totalLeaves),
"Lib_MerkleTree: Total siblings does not correctly correspond to total leaves."
);
bytes32 computedRoot = _leaf;
for (uint256 i = 0; i < _siblings.length; i++) {
if ((_index & 1) == 1) {
computedRoot = keccak256(
abi.encodePacked(
_siblings[i],
computedRoot
)
);
} else {
computedRoot = keccak256(
abi.encodePacked(
computedRoot,
_siblings[i]
)
);
}
_index >>= 1;
}
return _root == computedRoot;
}
/*********************
* Private Functions *
*********************/
/**
* Calculates the integer ceiling of the log base 2 of an input.
* @param _in Unsigned input to calculate the log.
* @return ceil(log_base_2(_in))
*/
function _ceilLog2(
uint256 _in
)
private
pure
returns (
uint256
)
{
require(
_in > 0,
"Lib_MerkleTree: Cannot compute ceil(log_2) of 0."
);
if (_in == 1) {
return 0;
}
// Find the highest set bit (will be floor(log_2)).
// Borrowed with <3 from https://github.com/ethereum/solidity-examples
uint256 val = _in;
uint256 highest = 0;
for (uint256 i = 128; i >= 1; i >>= 1) {
if (val & (uint(1) << i) - 1 << i != 0) {
highest += i;
val >>= i;
}
}
// Increment by one if this is not a perfect logarithm.
if ((uint(1) << highest) != _in) {
highest += 1;
}
return highest;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_Buffer } from "../../libraries/utils/Lib_Buffer.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol";
/**
* @title OVM_ChainStorageContainer
* @dev The Chain Storage Container provides its owner contract with read, write and delete
* functionality. This provides gas efficiency gains by enabling it to overwrite storage slots which
* can no longer be used in a fraud proof due to the fraud window having passed, and the associated
* chain state or transactions being finalized.
* Three distinct Chain Storage Containers will be deployed on Layer 1:
* 1. Stores transaction batches for the Canonical Transaction Chain
* 2. Stores queued transactions for the Canonical Transaction Chain
* 3. Stores chain state batches for the State Commitment Chain
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_ChainStorageContainer is iOVM_ChainStorageContainer, Lib_AddressResolver {
/*************
* Libraries *
*************/
using Lib_Buffer for Lib_Buffer.Buffer;
/*************
* Variables *
*************/
string public owner;
Lib_Buffer.Buffer internal buffer;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
* @param _owner Name of the contract that owns this container (will be resolved later).
*/
constructor(
address _libAddressManager,
string memory _owner
)
Lib_AddressResolver(_libAddressManager)
{
owner = _owner;
}
/**********************
* Function Modifiers *
**********************/
modifier onlyOwner() {
require(
msg.sender == resolve(owner),
"OVM_ChainStorageContainer: Function can only be called by the owner."
);
_;
}
/********************
* Public Functions *
********************/
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function setGlobalMetadata(
bytes27 _globalMetadata
)
override
public
onlyOwner
{
return buffer.setExtraData(_globalMetadata);
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function getGlobalMetadata()
override
public
view
returns (
bytes27
)
{
return buffer.getExtraData();
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function length()
override
public
view
returns (
uint256
)
{
return uint256(buffer.getLength());
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function push(
bytes32 _object
)
override
public
onlyOwner
{
buffer.push(_object);
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function push(
bytes32 _object,
bytes27 _globalMetadata
)
override
public
onlyOwner
{
buffer.push(_object, _globalMetadata);
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function get(
uint256 _index
)
override
public
view
returns (
bytes32
)
{
return buffer.get(uint40(_index));
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function deleteElementsAfterInclusive(
uint256 _index
)
override
public
onlyOwner
{
buffer.deleteElementsAfterInclusive(
uint40(_index)
);
}
/**
* @inheritdoc iOVM_ChainStorageContainer
*/
function deleteElementsAfterInclusive(
uint256 _index,
bytes27 _globalMetadata
)
override
public
onlyOwner
{
buffer.deleteElementsAfterInclusive(
uint40(_index),
_globalMetadata
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Buffer
* @dev This library implements a bytes32 storage array with some additional gas-optimized
* functionality. In particular, it encodes its length as a uint40, and tightly packs this with an
* overwritable "extra data" field so we can store more information with a single SSTORE.
*/
library Lib_Buffer {
/*************
* Libraries *
*************/
using Lib_Buffer for Buffer;
/***********
* Structs *
***********/
struct Buffer {
bytes32 context;
mapping (uint256 => bytes32) buf;
}
struct BufferContext {
// Stores the length of the array. Uint40 is way more elements than we'll ever reasonably
// need in an array and we get an extra 27 bytes of extra data to play with.
uint40 length;
// Arbitrary extra data that can be modified whenever the length is updated. Useful for
// squeezing out some gas optimizations.
bytes27 extraData;
}
/**********************
* Internal Functions *
**********************/
/**
* Pushes a single element to the buffer.
* @param _self Buffer to access.
* @param _value Value to push to the buffer.
* @param _extraData Global extra data.
*/
function push(
Buffer storage _self,
bytes32 _value,
bytes27 _extraData
)
internal
{
BufferContext memory ctx = _self.getContext();
_self.buf[ctx.length] = _value;
// Bump the global index and insert our extra data, then save the context.
ctx.length++;
ctx.extraData = _extraData;
_self.setContext(ctx);
}
/**
* Pushes a single element to the buffer.
* @param _self Buffer to access.
* @param _value Value to push to the buffer.
*/
function push(
Buffer storage _self,
bytes32 _value
)
internal
{
BufferContext memory ctx = _self.getContext();
_self.push(
_value,
ctx.extraData
);
}
/**
* Retrieves an element from the buffer.
* @param _self Buffer to access.
* @param _index Element index to retrieve.
* @return Value of the element at the given index.
*/
function get(
Buffer storage _self,
uint256 _index
)
internal
view
returns (
bytes32
)
{
BufferContext memory ctx = _self.getContext();
require(
_index < ctx.length,
"Index out of bounds."
);
return _self.buf[_index];
}
/**
* Deletes all elements after (and including) a given index.
* @param _self Buffer to access.
* @param _index Index of the element to delete from (inclusive).
* @param _extraData Optional global extra data.
*/
function deleteElementsAfterInclusive(
Buffer storage _self,
uint40 _index,
bytes27 _extraData
)
internal
{
BufferContext memory ctx = _self.getContext();
require(
_index < ctx.length,
"Index out of bounds."
);
// Set our length and extra data, save the context.
ctx.length = _index;
ctx.extraData = _extraData;
_self.setContext(ctx);
}
/**
* Deletes all elements after (and including) a given index.
* @param _self Buffer to access.
* @param _index Index of the element to delete from (inclusive).
*/
function deleteElementsAfterInclusive(
Buffer storage _self,
uint40 _index
)
internal
{
BufferContext memory ctx = _self.getContext();
_self.deleteElementsAfterInclusive(
_index,
ctx.extraData
);
}
/**
* Retrieves the current global index.
* @param _self Buffer to access.
* @return Current global index.
*/
function getLength(
Buffer storage _self
)
internal
view
returns (
uint40
)
{
BufferContext memory ctx = _self.getContext();
return ctx.length;
}
/**
* Changes current global extra data.
* @param _self Buffer to access.
* @param _extraData New global extra data.
*/
function setExtraData(
Buffer storage _self,
bytes27 _extraData
)
internal
{
BufferContext memory ctx = _self.getContext();
ctx.extraData = _extraData;
_self.setContext(ctx);
}
/**
* Retrieves the current global extra data.
* @param _self Buffer to access.
* @return Current global extra data.
*/
function getExtraData(
Buffer storage _self
)
internal
view
returns (
bytes27
)
{
BufferContext memory ctx = _self.getContext();
return ctx.extraData;
}
/**
* Sets the current buffer context.
* @param _self Buffer to access.
* @param _ctx Current buffer context.
*/
function setContext(
Buffer storage _self,
BufferContext memory _ctx
)
internal
{
bytes32 context;
uint40 length = _ctx.length;
bytes27 extraData = _ctx.extraData;
assembly {
context := length
context := or(context, extraData)
}
if (_self.context != context) {
_self.context = context;
}
}
/**
* Retrieves the current buffer context.
* @param _self Buffer to access.
* @return Current buffer context.
*/
function getContext(
Buffer storage _self
)
internal
view
returns (
BufferContext memory
)
{
bytes32 context = _self.context;
uint40 length;
bytes27 extraData;
assembly {
// solhint-disable-next-line max-line-length
length := and(context, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
// solhint-disable-next-line max-line-length
extraData := and(context, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000)
}
return BufferContext({
length: length,
extraData: extraData
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_Buffer } from "../../optimistic-ethereum/libraries/utils/Lib_Buffer.sol";
/**
* @title TestLib_Buffer
*/
contract TestLib_Buffer {
using Lib_Buffer for Lib_Buffer.Buffer;
Lib_Buffer.Buffer internal buf;
function push(
bytes32 _value,
bytes27 _extraData
)
public
{
buf.push(
_value,
_extraData
);
}
function get(
uint256 _index
)
public
view
returns (
bytes32
)
{
return buf.get(_index);
}
function deleteElementsAfterInclusive(
uint40 _index
)
public
{
return buf.deleteElementsAfterInclusive(
_index
);
}
function deleteElementsAfterInclusive(
uint40 _index,
bytes27 _extraData
)
public
{
return buf.deleteElementsAfterInclusive(
_index,
_extraData
);
}
function getLength()
public
view
returns (
uint40
)
{
return buf.getLength();
}
function setExtraData(
bytes27 _extraData
)
public
{
return buf.setExtraData(
_extraData
);
}
function getExtraData()
public
view
returns (
bytes27
)
{
return buf.getExtraData();
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_MerkleTree } from "../../libraries/utils/Lib_MerkleTree.sol";
/* Interface Imports */
import { iOVM_CanonicalTransactionChain } from
"../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
import { iOVM_ChainStorageContainer } from "../../iOVM/chain/iOVM_ChainStorageContainer.sol";
/* Contract Imports */
import { OVM_ExecutionManager } from "../execution/OVM_ExecutionManager.sol";
/* External Imports */
import { Math } from "@openzeppelin/contracts/math/Math.sol";
/**
* @title OVM_CanonicalTransactionChain
* @dev The Canonical Transaction Chain (CTC) contract is an append-only log of transactions
* which must be applied to the rollup state. It defines the ordering of rollup transactions by
* writing them to the 'CTC:batches' instance of the Chain Storage Container.
* The CTC also allows any account to 'enqueue' an L2 transaction, which will require that the
* Sequencer will eventually append it to the rollup state.
* If the Sequencer does not include an enqueued transaction within the 'force inclusion period',
* then any account may force it to be included by calling appendQueueBatch().
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_CanonicalTransactionChain is iOVM_CanonicalTransactionChain, Lib_AddressResolver {
/*************
* Constants *
*************/
// L2 tx gas-related
uint256 constant public MIN_ROLLUP_TX_GAS = 100000;
uint256 constant public MAX_ROLLUP_TX_SIZE = 50000;
uint256 constant public L2_GAS_DISCOUNT_DIVISOR = 32;
// Encoding-related (all in bytes)
uint256 constant internal BATCH_CONTEXT_SIZE = 16;
uint256 constant internal BATCH_CONTEXT_LENGTH_POS = 12;
uint256 constant internal BATCH_CONTEXT_START_POS = 15;
uint256 constant internal TX_DATA_HEADER_SIZE = 3;
uint256 constant internal BYTES_TILL_TX_DATA = 65;
/*************
* Variables *
*************/
uint256 public forceInclusionPeriodSeconds;
uint256 public forceInclusionPeriodBlocks;
uint256 public maxTransactionGasLimit;
/***************
* Constructor *
***************/
constructor(
address _libAddressManager,
uint256 _forceInclusionPeriodSeconds,
uint256 _forceInclusionPeriodBlocks,
uint256 _maxTransactionGasLimit
)
Lib_AddressResolver(_libAddressManager)
{
forceInclusionPeriodSeconds = _forceInclusionPeriodSeconds;
forceInclusionPeriodBlocks = _forceInclusionPeriodBlocks;
maxTransactionGasLimit = _maxTransactionGasLimit;
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches()
override
public
view
returns (
iOVM_ChainStorageContainer
)
{
return iOVM_ChainStorageContainer(
resolve("OVM_ChainStorageContainer-CTC-batches")
);
}
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue()
override
public
view
returns (
iOVM_ChainStorageContainer
)
{
return iOVM_ChainStorageContainer(
resolve("OVM_ChainStorageContainer-CTC-queue")
);
}
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
override
public
view
returns (
uint256 _totalElements
)
{
(uint40 totalElements,,,) = _getBatchExtraData();
return uint256(totalElements);
}
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
override
public
view
returns (
uint256 _totalBatches
)
{
return batches().length();
}
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex()
override
public
view
returns (
uint40
)
{
(,uint40 nextQueueIndex,,) = _getBatchExtraData();
return nextQueueIndex;
}
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp()
override
public
view
returns (
uint40
)
{
(,,uint40 lastTimestamp,) = _getBatchExtraData();
return lastTimestamp;
}
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber()
override
public
view
returns (
uint40
)
{
(,,,uint40 lastBlockNumber) = _getBatchExtraData();
return lastBlockNumber;
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(
uint256 _index
)
override
public
view
returns (
Lib_OVMCodec.QueueElement memory _element
)
{
return _getQueueElement(
_index,
queue()
);
}
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements()
override
public
view
returns (
uint40
)
{
return getQueueLength() - getNextQueueIndex();
}
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength()
override
public
view
returns (
uint40
)
{
return _getQueueLength(
queue()
);
}
/**
* Adds a transaction to the queue.
* @param _target Target L2 contract to send the transaction to.
* @param _gasLimit Gas limit for the enqueued L2 transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
override
public
{
require(
_data.length <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction."
);
require(
_gasLimit <= maxTransactionGasLimit,
"Transaction gas limit exceeds maximum for rollup transaction."
);
require(
_gasLimit >= MIN_ROLLUP_TX_GAS,
"Transaction gas limit too low to enqueue."
);
// We need to consume some amount of L1 gas in order to rate limit transactions going into
// L2. However, L2 is cheaper than L1 so we only need to burn some small proportion of the
// provided L1 gas.
uint256 gasToConsume = _gasLimit/L2_GAS_DISCOUNT_DIVISOR;
uint256 startingGas = gasleft();
// Although this check is not necessary (burn below will run out of gas if not true), it
// gives the user an explicit reason as to why the enqueue attempt failed.
require(
startingGas > gasToConsume,
"Insufficient gas for L2 rate limiting burn."
);
// Here we do some "dumb" work in order to burn gas, although we should probably replace
// this with something like minting gas token later on.
uint256 i;
while(startingGas - gasleft() < gasToConsume) {
i++;
}
bytes32 transactionHash = keccak256(
abi.encode(
msg.sender,
_target,
_gasLimit,
_data
)
);
bytes32 timestampAndBlockNumber;
assembly {
timestampAndBlockNumber := timestamp()
timestampAndBlockNumber := or(timestampAndBlockNumber, shl(40, number()))
}
iOVM_ChainStorageContainer queueRef = queue();
queueRef.push(transactionHash);
queueRef.push(timestampAndBlockNumber);
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2 and subtract 1.
uint256 queueIndex = queueRef.length() / 2 - 1;
emit TransactionEnqueued(
msg.sender,
_target,
_gasLimit,
_data,
queueIndex,
block.timestamp
);
}
/**
* Appends a given number of queued transactions as a single batch.
* param _numQueuedTransactions Number of transactions to append.
*/
function appendQueueBatch(
uint256 // _numQueuedTransactions
)
override
public
pure
{
// TEMPORARY: Disable `appendQueueBatch` for minnet
revert("appendQueueBatch is currently disabled.");
// solhint-disable max-line-length
// _numQueuedTransactions = Math.min(_numQueuedTransactions, getNumPendingQueueElements());
// require(
// _numQueuedTransactions > 0,
// "Must append more than zero transactions."
// );
// bytes32[] memory leaves = new bytes32[](_numQueuedTransactions);
// uint40 nextQueueIndex = getNextQueueIndex();
// for (uint256 i = 0; i < _numQueuedTransactions; i++) {
// if (msg.sender != resolve("OVM_Sequencer")) {
// Lib_OVMCodec.QueueElement memory el = getQueueElement(nextQueueIndex);
// require(
// el.timestamp + forceInclusionPeriodSeconds < block.timestamp,
// "Queue transactions cannot be submitted during the sequencer inclusion period."
// );
// }
// leaves[i] = _getQueueLeafHash(nextQueueIndex);
// nextQueueIndex++;
// }
// Lib_OVMCodec.QueueElement memory lastElement = getQueueElement(nextQueueIndex - 1);
// _appendBatch(
// Lib_MerkleTree.getMerkleRoot(leaves),
// _numQueuedTransactions,
// _numQueuedTransactions,
// lastElement.timestamp,
// lastElement.blockNumber
// );
// emit QueueBatchAppended(
// nextQueueIndex - _numQueuedTransactions,
// _numQueuedTransactions,
// getTotalElements()
// );
// solhint-enable max-line-length
}
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch()
override
public
{
uint40 shouldStartAtElement;
uint24 totalElementsToAppend;
uint24 numContexts;
assembly {
shouldStartAtElement := shr(216, calldataload(4))
totalElementsToAppend := shr(232, calldataload(9))
numContexts := shr(232, calldataload(12))
}
require(
shouldStartAtElement == getTotalElements(),
"Actual batch start index does not match expected start index."
);
require(
msg.sender == resolve("OVM_Sequencer"),
"Function can only be called by the Sequencer."
);
require(
numContexts > 0,
"Must provide at least one batch context."
);
require(
totalElementsToAppend > 0,
"Must append at least one element."
);
uint40 nextTransactionPtr = uint40(
BATCH_CONTEXT_START_POS + BATCH_CONTEXT_SIZE * numContexts
);
require(
msg.data.length >= nextTransactionPtr,
"Not enough BatchContexts provided."
);
// Take a reference to the queue and its length so we don't have to keep resolving it.
// Length isn't going to change during the course of execution, so it's fine to simply
// resolve this once at the start. Saves gas.
iOVM_ChainStorageContainer queueRef = queue();
uint40 queueLength = _getQueueLength(queueRef);
// Reserve some memory to save gas on hashing later on. This is a relatively safe estimate
// for the average transaction size that will prevent having to resize this chunk of memory
// later on. Saves gas.
bytes memory hashMemory = new bytes((msg.data.length / totalElementsToAppend) * 2);
// Initialize the array of canonical chain leaves that we will append.
bytes32[] memory leaves = new bytes32[](totalElementsToAppend);
// Each leaf index corresponds to a tx, either sequenced or enqueued.
uint32 leafIndex = 0;
// Counter for number of sequencer transactions appended so far.
uint32 numSequencerTransactions = 0;
// We will sequentially append leaves which are pointers to the queue.
// The initial queue index is what is currently in storage.
uint40 nextQueueIndex = getNextQueueIndex();
BatchContext memory curContext;
for (uint32 i = 0; i < numContexts; i++) {
BatchContext memory nextContext = _getBatchContext(i);
if (i == 0) {
// Execute a special check for the first batch.
_validateFirstBatchContext(nextContext);
}
// Execute this check on every single batch, including the first one.
_validateNextBatchContext(
curContext,
nextContext,
nextQueueIndex,
queueRef
);
// Now we can update our current context.
curContext = nextContext;
// Process sequencer transactions first.
for (uint32 j = 0; j < curContext.numSequencedTransactions; j++) {
uint256 txDataLength;
assembly {
txDataLength := shr(232, calldataload(nextTransactionPtr))
}
require(
txDataLength <= MAX_ROLLUP_TX_SIZE,
"Transaction data size exceeds maximum for rollup transaction."
);
leaves[leafIndex] = _getSequencerLeafHash(
curContext,
nextTransactionPtr,
txDataLength,
hashMemory
);
nextTransactionPtr += uint40(TX_DATA_HEADER_SIZE + txDataLength);
numSequencerTransactions++;
leafIndex++;
}
// Now process any subsequent queue transactions.
for (uint32 j = 0; j < curContext.numSubsequentQueueTransactions; j++) {
require(
nextQueueIndex < queueLength,
"Not enough queued transactions to append."
);
leaves[leafIndex] = _getQueueLeafHash(nextQueueIndex);
nextQueueIndex++;
leafIndex++;
}
}
_validateFinalBatchContext(
curContext,
nextQueueIndex,
queueLength,
queueRef
);
require(
msg.data.length == nextTransactionPtr,
"Not all sequencer transactions were processed."
);
require(
leafIndex == totalElementsToAppend,
"Actual transaction index does not match expected total elements to append."
);
// Generate the required metadata that we need to append this batch
uint40 numQueuedTransactions = totalElementsToAppend - numSequencerTransactions;
uint40 blockTimestamp;
uint40 blockNumber;
if (curContext.numSubsequentQueueTransactions == 0) {
// The last element is a sequencer tx, therefore pull timestamp and block number from
// the last context.
blockTimestamp = uint40(curContext.timestamp);
blockNumber = uint40(curContext.blockNumber);
} else {
// The last element is a queue tx, therefore pull timestamp and block number from the
// queue element.
// curContext.numSubsequentQueueTransactions > 0 which means that we've processed at
// least one queue element. We increment nextQueueIndex after processing each queue
// element, so the index of the last element we processed is nextQueueIndex - 1.
Lib_OVMCodec.QueueElement memory lastElement = _getQueueElement(
nextQueueIndex - 1,
queueRef
);
blockTimestamp = lastElement.timestamp;
blockNumber = lastElement.blockNumber;
}
// For efficiency reasons getMerkleRoot modifies the `leaves` argument in place
// while calculating the root hash therefore any arguments passed to it must not
// be used again afterwards
_appendBatch(
Lib_MerkleTree.getMerkleRoot(leaves),
totalElementsToAppend,
numQueuedTransactions,
blockTimestamp,
blockNumber
);
emit SequencerBatchAppended(
nextQueueIndex - numQueuedTransactions,
numQueuedTransactions,
getTotalElements()
);
}
/**
* Verifies whether a transaction is included in the chain.
* @param _transaction Transaction to verify.
* @param _txChainElement Transaction chain element corresponding to the transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof Inclusion proof for the provided transaction chain element.
* @return True if the transaction exists in the CTC, false if not.
*/
function verifyTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
override
public
view
returns (
bool
)
{
if (_txChainElement.isSequenced == true) {
return _verifySequencerTransaction(
_transaction,
_txChainElement,
_batchHeader,
_inclusionProof
);
} else {
return _verifyQueueTransaction(
_transaction,
_txChainElement.queueIndex,
_batchHeader,
_inclusionProof
);
}
}
/**********************
* Internal Functions *
**********************/
/**
* Returns the BatchContext located at a particular index.
* @param _index The index of the BatchContext
* @return The BatchContext at the specified index.
*/
function _getBatchContext(
uint256 _index
)
internal
pure
returns (
BatchContext memory
)
{
uint256 contextPtr = 15 + _index * BATCH_CONTEXT_SIZE;
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 ctxTimestamp;
uint256 ctxBlockNumber;
assembly {
numSequencedTransactions := shr(232, calldataload(contextPtr))
numSubsequentQueueTransactions := shr(232, calldataload(add(contextPtr, 3)))
ctxTimestamp := shr(216, calldataload(add(contextPtr, 6)))
ctxBlockNumber := shr(216, calldataload(add(contextPtr, 11)))
}
return BatchContext({
numSequencedTransactions: numSequencedTransactions,
numSubsequentQueueTransactions: numSubsequentQueueTransactions,
timestamp: ctxTimestamp,
blockNumber: ctxBlockNumber
});
}
/**
* Parses the batch context from the extra data.
* @return Total number of elements submitted.
* @return Index of the next queue element.
*/
function _getBatchExtraData()
internal
view
returns (
uint40,
uint40,
uint40,
uint40
)
{
bytes27 extraData = batches().getGlobalMetadata();
uint40 totalElements;
uint40 nextQueueIndex;
uint40 lastTimestamp;
uint40 lastBlockNumber;
// solhint-disable max-line-length
assembly {
extraData := shr(40, extraData)
totalElements := and(extraData, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
nextQueueIndex := shr(40, and(extraData, 0x00000000000000000000000000000000000000000000FFFFFFFFFF0000000000))
lastTimestamp := shr(80, and(extraData, 0x0000000000000000000000000000000000FFFFFFFFFF00000000000000000000))
lastBlockNumber := shr(120, and(extraData, 0x000000000000000000000000FFFFFFFFFF000000000000000000000000000000))
}
// solhint-enable max-line-length
return (
totalElements,
nextQueueIndex,
lastTimestamp,
lastBlockNumber
);
}
/**
* Encodes the batch context for the extra data.
* @param _totalElements Total number of elements submitted.
* @param _nextQueueIndex Index of the next queue element.
* @param _timestamp Timestamp for the last batch.
* @param _blockNumber Block number of the last batch.
* @return Encoded batch context.
*/
function _makeBatchExtraData(
uint40 _totalElements,
uint40 _nextQueueIndex,
uint40 _timestamp,
uint40 _blockNumber
)
internal
pure
returns (
bytes27
)
{
bytes27 extraData;
assembly {
extraData := _totalElements
extraData := or(extraData, shl(40, _nextQueueIndex))
extraData := or(extraData, shl(80, _timestamp))
extraData := or(extraData, shl(120, _blockNumber))
extraData := shl(40, extraData)
}
return extraData;
}
/**
* Retrieves the hash of a queue element.
* @param _index Index of the queue element to retrieve a hash for.
* @return Hash of the queue element.
*/
function _getQueueLeafHash(
uint256 _index
)
internal
pure
returns (
bytes32
)
{
return _hashTransactionChainElement(
Lib_OVMCodec.TransactionChainElement({
isSequenced: false,
queueIndex: _index,
timestamp: 0,
blockNumber: 0,
txData: hex""
})
);
}
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function _getQueueElement(
uint256 _index,
iOVM_ChainStorageContainer _queueRef
)
internal
view
returns (
Lib_OVMCodec.QueueElement memory _element
)
{
// The underlying queue data structure stores 2 elements
// per insertion, so to get the actual desired queue index
// we need to multiply by 2.
uint40 trueIndex = uint40(_index * 2);
bytes32 transactionHash = _queueRef.get(trueIndex);
bytes32 timestampAndBlockNumber = _queueRef.get(trueIndex + 1);
uint40 elementTimestamp;
uint40 elementBlockNumber;
// solhint-disable max-line-length
assembly {
elementTimestamp := and(timestampAndBlockNumber, 0x000000000000000000000000000000000000000000000000000000FFFFFFFFFF)
elementBlockNumber := shr(40, and(timestampAndBlockNumber, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000000000))
}
// solhint-enable max-line-length
return Lib_OVMCodec.QueueElement({
transactionHash: transactionHash,
timestamp: elementTimestamp,
blockNumber: elementBlockNumber
});
}
/**
* Retrieves the length of the queue.
* @return Length of the queue.
*/
function _getQueueLength(
iOVM_ChainStorageContainer _queueRef
)
internal
view
returns (
uint40
)
{
// The underlying queue data structure stores 2 elements
// per insertion, so to get the real queue length we need
// to divide by 2.
return uint40(_queueRef.length() / 2);
}
/**
* Retrieves the hash of a sequencer element.
* @param _context Batch context for the given element.
* @param _nextTransactionPtr Pointer to the next transaction in the calldata.
* @param _txDataLength Length of the transaction item.
* @return Hash of the sequencer element.
*/
function _getSequencerLeafHash(
BatchContext memory _context,
uint256 _nextTransactionPtr,
uint256 _txDataLength,
bytes memory _hashMemory
)
internal
pure
returns (
bytes32
)
{
// Only allocate more memory if we didn't reserve enough to begin with.
if (BYTES_TILL_TX_DATA + _txDataLength > _hashMemory.length) {
_hashMemory = new bytes(BYTES_TILL_TX_DATA + _txDataLength);
}
uint256 ctxTimestamp = _context.timestamp;
uint256 ctxBlockNumber = _context.blockNumber;
bytes32 leafHash;
assembly {
let chainElementStart := add(_hashMemory, 0x20)
// Set the first byte equal to `1` to indicate this is a sequencer chain element.
// This distinguishes sequencer ChainElements from queue ChainElements because
// all queue ChainElements are ABI encoded and the first byte of ABI encoded
// elements is always zero
mstore8(chainElementStart, 1)
mstore(add(chainElementStart, 1), ctxTimestamp)
mstore(add(chainElementStart, 33), ctxBlockNumber)
// solhint-disable-next-line max-line-length
calldatacopy(add(chainElementStart, BYTES_TILL_TX_DATA), add(_nextTransactionPtr, 3), _txDataLength)
leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, _txDataLength))
}
return leafHash;
}
/**
* Retrieves the hash of a sequencer element.
* @param _txChainElement The chain element which is hashed to calculate the leaf.
* @return Hash of the sequencer element.
*/
function _getSequencerLeafHash(
Lib_OVMCodec.TransactionChainElement memory _txChainElement
)
internal
view
returns(
bytes32
)
{
bytes memory txData = _txChainElement.txData;
uint256 txDataLength = _txChainElement.txData.length;
bytes memory chainElement = new bytes(BYTES_TILL_TX_DATA + txDataLength);
uint256 ctxTimestamp = _txChainElement.timestamp;
uint256 ctxBlockNumber = _txChainElement.blockNumber;
bytes32 leafHash;
assembly {
let chainElementStart := add(chainElement, 0x20)
// Set the first byte equal to `1` to indicate this is a sequencer chain element.
// This distinguishes sequencer ChainElements from queue ChainElements because
// all queue ChainElements are ABI encoded and the first byte of ABI encoded
// elements is always zero
mstore8(chainElementStart, 1)
mstore(add(chainElementStart, 1), ctxTimestamp)
mstore(add(chainElementStart, 33), ctxBlockNumber)
// solhint-disable-next-line max-line-length
pop(staticcall(gas(), 0x04, add(txData, 0x20), txDataLength, add(chainElementStart, BYTES_TILL_TX_DATA), txDataLength))
leafHash := keccak256(chainElementStart, add(BYTES_TILL_TX_DATA, txDataLength))
}
return leafHash;
}
/**
* Inserts a batch into the chain of batches.
* @param _transactionRoot Root of the transaction tree for this batch.
* @param _batchSize Number of elements in the batch.
* @param _numQueuedTransactions Number of queue transactions in the batch.
* @param _timestamp The latest batch timestamp.
* @param _blockNumber The latest batch blockNumber.
*/
function _appendBatch(
bytes32 _transactionRoot,
uint256 _batchSize,
uint256 _numQueuedTransactions,
uint40 _timestamp,
uint40 _blockNumber
)
internal
{
iOVM_ChainStorageContainer batchesRef = batches();
(uint40 totalElements, uint40 nextQueueIndex,,) = _getBatchExtraData();
Lib_OVMCodec.ChainBatchHeader memory header = Lib_OVMCodec.ChainBatchHeader({
batchIndex: batchesRef.length(),
batchRoot: _transactionRoot,
batchSize: _batchSize,
prevTotalElements: totalElements,
extraData: hex""
});
emit TransactionBatchAppended(
header.batchIndex,
header.batchRoot,
header.batchSize,
header.prevTotalElements,
header.extraData
);
bytes32 batchHeaderHash = Lib_OVMCodec.hashBatchHeader(header);
bytes27 latestBatchContext = _makeBatchExtraData(
totalElements + uint40(header.batchSize),
nextQueueIndex + uint40(_numQueuedTransactions),
_timestamp,
_blockNumber
);
batchesRef.push(batchHeaderHash, latestBatchContext);
}
/**
* Checks that the first batch context in a sequencer submission is valid
* @param _firstContext The batch context to validate.
*/
function _validateFirstBatchContext(
BatchContext memory _firstContext
)
internal
view
{
// If there are existing elements, this batch must have the same context
// or a later timestamp and block number.
if (getTotalElements() > 0) {
(,, uint40 lastTimestamp, uint40 lastBlockNumber) = _getBatchExtraData();
require(
_firstContext.blockNumber >= lastBlockNumber,
"Context block number is lower than last submitted."
);
require(
_firstContext.timestamp >= lastTimestamp,
"Context timestamp is lower than last submitted."
);
}
// Sequencer cannot submit contexts which are more than the force inclusion period old.
require(
_firstContext.timestamp + forceInclusionPeriodSeconds >= block.timestamp,
"Context timestamp too far in the past."
);
require(
_firstContext.blockNumber + forceInclusionPeriodBlocks >= block.number,
"Context block number too far in the past."
);
}
/**
* Checks that a given batch context has a time context which is below a given que element
* @param _context The batch context to validate has values lower.
* @param _queueIndex Index of the queue element we are validating came later than the context.
* @param _queueRef The storage container for the queue.
*/
function _validateContextBeforeEnqueue(
BatchContext memory _context,
uint40 _queueIndex,
iOVM_ChainStorageContainer _queueRef
)
internal
view
{
Lib_OVMCodec.QueueElement memory nextQueueElement = _getQueueElement(
_queueIndex,
_queueRef
);
// If the force inclusion period has passed for an enqueued transaction, it MUST be the
// next chain element.
require(
block.timestamp < nextQueueElement.timestamp + forceInclusionPeriodSeconds,
// solhint-disable-next-line max-line-length
"Previously enqueued batches have expired and must be appended before a new sequencer batch."
);
// Just like sequencer transaction times must be increasing relative to each other,
// We also require that they be increasing relative to any interspersed queue elements.
require(
_context.timestamp <= nextQueueElement.timestamp,
"Sequencer transaction timestamp exceeds that of next queue element."
);
require(
_context.blockNumber <= nextQueueElement.blockNumber,
"Sequencer transaction blockNumber exceeds that of next queue element."
);
}
/**
* Checks that a given batch context is valid based on its previous context, and the next queue
* elemtent.
* @param _prevContext The previously validated batch context.
* @param _nextContext The batch context to validate with this call.
* @param _nextQueueIndex Index of the next queue element to process for the _nextContext's
* subsequentQueueElements.
* @param _queueRef The storage container for the queue.
*/
function _validateNextBatchContext(
BatchContext memory _prevContext,
BatchContext memory _nextContext,
uint40 _nextQueueIndex,
iOVM_ChainStorageContainer _queueRef
)
internal
view
{
// All sequencer transactions' times must be greater than or equal to the previous ones.
require(
_nextContext.timestamp >= _prevContext.timestamp,
"Context timestamp values must monotonically increase."
);
require(
_nextContext.blockNumber >= _prevContext.blockNumber,
"Context blockNumber values must monotonically increase."
);
// If there is going to be a queue element pulled in from this context:
if (_nextContext.numSubsequentQueueTransactions > 0) {
_validateContextBeforeEnqueue(
_nextContext,
_nextQueueIndex,
_queueRef
);
}
}
/**
* Checks that the final batch context in a sequencer submission is valid.
* @param _finalContext The batch context to validate.
* @param _queueLength The length of the queue at the start of the batchAppend call.
* @param _nextQueueIndex The next element in the queue that will be pulled into the CTC.
* @param _queueRef The storage container for the queue.
*/
function _validateFinalBatchContext(
BatchContext memory _finalContext,
uint40 _nextQueueIndex,
uint40 _queueLength,
iOVM_ChainStorageContainer _queueRef
)
internal
view
{
// If the queue is not now empty, check the mononoticity of whatever the next batch that
// will come in is.
if (_queueLength - _nextQueueIndex > 0 && _finalContext.numSubsequentQueueTransactions == 0)
{
_validateContextBeforeEnqueue(
_finalContext,
_nextQueueIndex,
_queueRef
);
}
// Batches cannot be added from the future, or subsequent enqueue() contexts would violate
// monotonicity.
require(_finalContext.timestamp <= block.timestamp,
"Context timestamp is from the future.");
require(_finalContext.blockNumber <= block.number,
"Context block number is from the future.");
}
/**
* Hashes a transaction chain element.
* @param _element Chain element to hash.
* @return Hash of the chain element.
*/
function _hashTransactionChainElement(
Lib_OVMCodec.TransactionChainElement memory _element
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_element.isSequenced,
_element.queueIndex,
_element.timestamp,
_element.blockNumber,
_element.txData
)
);
}
/**
* Verifies a sequencer transaction, returning true if it was indeed included in the CTC
* @param _transaction The transaction we are verifying inclusion of.
* @param _txChainElement The chain element that the transaction is claimed to be a part of.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof An inclusion proof into the CTC at a particular index.
* @return True if the transaction was included in the specified location, else false.
*/
function _verifySequencerTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
internal
view
returns (
bool
)
{
OVM_ExecutionManager ovmExecutionManager =
OVM_ExecutionManager(resolve("OVM_ExecutionManager"));
uint256 gasLimit = ovmExecutionManager.getMaxTransactionGasLimit();
bytes32 leafHash = _getSequencerLeafHash(_txChainElement);
require(
_verifyElement(
leafHash,
_batchHeader,
_inclusionProof
),
"Invalid Sequencer transaction inclusion proof."
);
require(
_transaction.blockNumber == _txChainElement.blockNumber
&& _transaction.timestamp == _txChainElement.timestamp
&& _transaction.entrypoint == resolve("OVM_DecompressionPrecompileAddress")
&& _transaction.gasLimit == gasLimit
&& _transaction.l1TxOrigin == address(0)
&& _transaction.l1QueueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE
&& keccak256(_transaction.data) == keccak256(_txChainElement.txData),
"Invalid Sequencer transaction."
);
return true;
}
/**
* Verifies a queue transaction, returning true if it was indeed included in the CTC
* @param _transaction The transaction we are verifying inclusion of.
* @param _queueIndex The queueIndex of the queued transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof An inclusion proof into the CTC at a particular index (should point to
* queue tx).
* @return True if the transaction was included in the specified location, else false.
*/
function _verifyQueueTransaction(
Lib_OVMCodec.Transaction memory _transaction,
uint256 _queueIndex,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
internal
view
returns (
bool
)
{
bytes32 leafHash = _getQueueLeafHash(_queueIndex);
require(
_verifyElement(
leafHash,
_batchHeader,
_inclusionProof
),
"Invalid Queue transaction inclusion proof."
);
bytes32 transactionHash = keccak256(
abi.encode(
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
)
);
Lib_OVMCodec.QueueElement memory el = getQueueElement(_queueIndex);
require(
el.transactionHash == transactionHash
&& el.timestamp == _transaction.timestamp
&& el.blockNumber == _transaction.blockNumber,
"Invalid Queue transaction."
);
return true;
}
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function _verifyElement(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
require(
Lib_OVMCodec.hashBatchHeader(_batchHeader) ==
batches().get(uint32(_batchHeader.batchIndex)),
"Invalid batch header."
);
require(
Lib_MerkleTree.verify(
_batchHeader.batchRoot,
_element,
_proof.index,
_proof.siblings,
_batchHeader.batchSize
),
"Invalid inclusion proof."
);
return true;
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol";
import { Lib_ErrorUtils } from "../../libraries/utils/Lib_ErrorUtils.sol";
import { Lib_PredeployAddresses } from "../../libraries/constants/Lib_PredeployAddresses.sol";
/* Interface Imports */
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol";
/* Contract Imports */
import { OVM_DeployerWhitelist } from "../predeploys/OVM_DeployerWhitelist.sol";
/* External Imports */
import { Math } from "@openzeppelin/contracts/math/Math.sol";
/**
* @title OVM_ExecutionManager
* @dev The Execution Manager (EM) is the core of our OVM implementation, and provides a sandboxed
* environment allowing us to execute OVM transactions deterministically on either Layer 1 or
* Layer 2.
* The EM's run() function is the first function called during the execution of any
* transaction on L2.
* For each context-dependent EVM operation the EM has a function which implements a corresponding
* OVM operation, which will read state from the State Manager contract.
* The EM relies on the Safety Checker to verify that code deployed to Layer 2 does not contain any
* context-dependent operations.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_ExecutionManager is iOVM_ExecutionManager, Lib_AddressResolver {
/********************************
* External Contract References *
********************************/
iOVM_SafetyChecker internal ovmSafetyChecker;
iOVM_StateManager internal ovmStateManager;
/*******************************
* Execution Context Variables *
*******************************/
GasMeterConfig internal gasMeterConfig;
GlobalContext internal globalContext;
TransactionContext internal transactionContext;
MessageContext internal messageContext;
TransactionRecord internal transactionRecord;
MessageRecord internal messageRecord;
/**************************
* Gas Metering Constants *
**************************/
address constant GAS_METADATA_ADDRESS = 0x06a506A506a506A506a506a506A506A506A506A5;
uint256 constant NUISANCE_GAS_SLOAD = 20000;
uint256 constant NUISANCE_GAS_SSTORE = 20000;
uint256 constant MIN_NUISANCE_GAS_PER_CONTRACT = 30000;
uint256 constant NUISANCE_GAS_PER_CONTRACT_BYTE = 100;
uint256 constant MIN_GAS_FOR_INVALID_STATE_ACCESS = 30000;
/**************************
* Native Value Constants *
**************************/
// Public so we can access and make assertions in integration tests.
uint256 public constant CALL_WITH_VALUE_INTRINSIC_GAS = 90000;
/**************************
* Default Context Values *
**************************/
uint256 constant DEFAULT_UINT256 =
0xdefa017defa017defa017defa017defa017defa017defa017defa017defa017d;
address constant DEFAULT_ADDRESS = 0xdEfa017defA017DeFA017DEfa017DeFA017DeFa0;
/*************************************
* Container Contract Address Prefix *
*************************************/
/**
* @dev The Execution Manager and State Manager each have this 30 byte prefix,
* and are uncallable.
*/
address constant CONTAINER_CONTRACT_PREFIX = 0xDeadDeAddeAddEAddeadDEaDDEAdDeaDDeAD0000;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager,
GasMeterConfig memory _gasMeterConfig,
GlobalContext memory _globalContext
)
Lib_AddressResolver(_libAddressManager)
{
ovmSafetyChecker = iOVM_SafetyChecker(resolve("OVM_SafetyChecker"));
gasMeterConfig = _gasMeterConfig;
globalContext = _globalContext;
_resetContext();
}
/**********************
* Function Modifiers *
**********************/
/**
* Applies dynamically-sized refund to a transaction to account for the difference in execution
* between L1 and L2, so that the overall cost of the ovmOPCODE is fixed.
* @param _cost Desired gas cost for the function after the refund.
*/
modifier netGasCost(
uint256 _cost
) {
uint256 gasProvided = gasleft();
_;
uint256 gasUsed = gasProvided - gasleft();
// We want to refund everything *except* the specified cost.
if (_cost < gasUsed) {
transactionRecord.ovmGasRefund += gasUsed - _cost;
}
}
/**
* Applies a fixed-size gas refund to a transaction to account for the difference in execution
* between L1 and L2, so that the overall cost of an ovmOPCODE can be lowered.
* @param _discount Amount of gas cost to refund for the ovmOPCODE.
*/
modifier fixedGasDiscount(
uint256 _discount
) {
uint256 gasProvided = gasleft();
_;
uint256 gasUsed = gasProvided - gasleft();
// We want to refund the specified _discount, unless this risks underflow.
if (_discount < gasUsed) {
transactionRecord.ovmGasRefund += _discount;
} else {
// refund all we can without risking underflow.
transactionRecord.ovmGasRefund += gasUsed;
}
}
/**
* Makes sure we're not inside a static context.
*/
modifier notStatic() {
if (messageContext.isStatic == true) {
_revertWithFlag(RevertFlag.STATIC_VIOLATION);
}
_;
}
/************************************
* Transaction Execution Entrypoint *
************************************/
/**
* Starts the execution of a transaction via the OVM_ExecutionManager.
* @param _transaction Transaction data to be executed.
* @param _ovmStateManager iOVM_StateManager implementation providing account state.
*/
function run(
Lib_OVMCodec.Transaction memory _transaction,
address _ovmStateManager
)
override
external
returns (
bytes memory
)
{
// Make sure that run() is not re-enterable. This condition should always be satisfied
// Once run has been called once, due to the behavior of _isValidInput().
if (transactionContext.ovmNUMBER != DEFAULT_UINT256) {
return bytes("");
}
// Store our OVM_StateManager instance (significantly easier than attempting to pass the
// address around in calldata).
ovmStateManager = iOVM_StateManager(_ovmStateManager);
// Make sure this function can't be called by anyone except the owner of the
// OVM_StateManager (expected to be an OVM_StateTransitioner). We can revert here because
// this would make the `run` itself invalid.
require(
// This method may return false during fraud proofs, but always returns true in
// L2 nodes' State Manager precompile.
ovmStateManager.isAuthenticated(msg.sender),
"Only authenticated addresses in ovmStateManager can call this function"
);
// Initialize the execution context, must be initialized before we perform any gas metering
// or we'll throw a nuisance gas error.
_initContext(_transaction);
// TEMPORARY: Gas metering is disabled for minnet.
// // Check whether we need to start a new epoch, do so if necessary.
// _checkNeedsNewEpoch(_transaction.timestamp);
// Make sure the transaction's gas limit is valid. We don't revert here because we reserve
// reverts for INVALID_STATE_ACCESS.
if (_isValidInput(_transaction) == false) {
_resetContext();
return bytes("");
}
// TEMPORARY: Gas metering is disabled for minnet.
// // Check gas right before the call to get total gas consumed by OVM transaction.
// uint256 gasProvided = gasleft();
// Run the transaction, make sure to meter the gas usage.
(, bytes memory returndata) = ovmCALL(
_transaction.gasLimit - gasMeterConfig.minTransactionGasLimit,
_transaction.entrypoint,
0,
_transaction.data
);
// TEMPORARY: Gas metering is disabled for minnet.
// // Update the cumulative gas based on the amount of gas used.
// uint256 gasUsed = gasProvided - gasleft();
// _updateCumulativeGas(gasUsed, _transaction.l1QueueOrigin);
// Wipe the execution context.
_resetContext();
return returndata;
}
/******************************
* Opcodes: Execution Context *
******************************/
/**
* @notice Overrides CALLER.
* @return _CALLER Address of the CALLER within the current message context.
*/
function ovmCALLER()
override
external
view
returns (
address _CALLER
)
{
return messageContext.ovmCALLER;
}
/**
* @notice Overrides ADDRESS.
* @return _ADDRESS Active ADDRESS within the current message context.
*/
function ovmADDRESS()
override
public
view
returns (
address _ADDRESS
)
{
return messageContext.ovmADDRESS;
}
/**
* @notice Overrides CALLVALUE.
* @return _CALLVALUE Value sent along with the call according to the current message context.
*/
function ovmCALLVALUE()
override
public
view
returns (
uint256 _CALLVALUE
)
{
return messageContext.ovmCALLVALUE;
}
/**
* @notice Overrides TIMESTAMP.
* @return _TIMESTAMP Value of the TIMESTAMP within the transaction context.
*/
function ovmTIMESTAMP()
override
external
view
returns (
uint256 _TIMESTAMP
)
{
return transactionContext.ovmTIMESTAMP;
}
/**
* @notice Overrides NUMBER.
* @return _NUMBER Value of the NUMBER within the transaction context.
*/
function ovmNUMBER()
override
external
view
returns (
uint256 _NUMBER
)
{
return transactionContext.ovmNUMBER;
}
/**
* @notice Overrides GASLIMIT.
* @return _GASLIMIT Value of the block's GASLIMIT within the transaction context.
*/
function ovmGASLIMIT()
override
external
view
returns (
uint256 _GASLIMIT
)
{
return transactionContext.ovmGASLIMIT;
}
/**
* @notice Overrides CHAINID.
* @return _CHAINID Value of the chain's CHAINID within the global context.
*/
function ovmCHAINID()
override
external
view
returns (
uint256 _CHAINID
)
{
return globalContext.ovmCHAINID;
}
/*********************************
* Opcodes: L2 Execution Context *
*********************************/
/**
* @notice Specifies from which source (Sequencer or Queue) this transaction originated from.
* @return _queueOrigin Enum indicating the ovmL1QUEUEORIGIN within the current message context.
*/
function ovmL1QUEUEORIGIN()
override
external
view
returns (
Lib_OVMCodec.QueueOrigin _queueOrigin
)
{
return transactionContext.ovmL1QUEUEORIGIN;
}
/**
* @notice Specifies which L1 account, if any, sent this transaction by calling enqueue().
* @return _l1TxOrigin Address of the account which sent the tx into L2 from L1.
*/
function ovmL1TXORIGIN()
override
external
view
returns (
address _l1TxOrigin
)
{
return transactionContext.ovmL1TXORIGIN;
}
/********************
* Opcodes: Halting *
********************/
/**
* @notice Overrides REVERT.
* @param _data Bytes data to pass along with the REVERT.
*/
function ovmREVERT(
bytes memory _data
)
override
public
{
_revertWithFlag(RevertFlag.INTENTIONAL_REVERT, _data);
}
/******************************
* Opcodes: Contract Creation *
******************************/
/**
* @notice Overrides CREATE.
* @param _bytecode Code to be used to CREATE a new contract.
* @return Address of the created contract.
* @return Revert data, if and only if the creation threw an exception.
*/
function ovmCREATE(
bytes memory _bytecode
)
override
public
notStatic
fixedGasDiscount(40000)
returns (
address,
bytes memory
)
{
// Creator is always the current ADDRESS.
address creator = ovmADDRESS();
// Check that the deployer is whitelisted, or
// that arbitrary contract deployment has been enabled.
_checkDeployerAllowed(creator);
// Generate the correct CREATE address.
address contractAddress = Lib_EthUtils.getAddressForCREATE(
creator,
_getAccountNonce(creator)
);
return _createContract(
contractAddress,
_bytecode,
MessageType.ovmCREATE
);
}
/**
* @notice Overrides CREATE2.
* @param _bytecode Code to be used to CREATE2 a new contract.
* @param _salt Value used to determine the contract's address.
* @return Address of the created contract.
* @return Revert data, if and only if the creation threw an exception.
*/
function ovmCREATE2(
bytes memory _bytecode,
bytes32 _salt
)
override
external
notStatic
fixedGasDiscount(40000)
returns (
address,
bytes memory
)
{
// Creator is always the current ADDRESS.
address creator = ovmADDRESS();
// Check that the deployer is whitelisted, or
// that arbitrary contract deployment has been enabled.
_checkDeployerAllowed(creator);
// Generate the correct CREATE2 address.
address contractAddress = Lib_EthUtils.getAddressForCREATE2(
creator,
_bytecode,
_salt
);
return _createContract(
contractAddress,
_bytecode,
MessageType.ovmCREATE2
);
}
/*******************************
* Account Abstraction Opcodes *
******************************/
/**
* Retrieves the nonce of the current ovmADDRESS.
* @return _nonce Nonce of the current contract.
*/
function ovmGETNONCE()
override
external
returns (
uint256 _nonce
)
{
return _getAccountNonce(ovmADDRESS());
}
/**
* Bumps the nonce of the current ovmADDRESS by one.
*/
function ovmINCREMENTNONCE()
override
external
notStatic
{
address account = ovmADDRESS();
uint256 nonce = _getAccountNonce(account);
// Prevent overflow.
if (nonce + 1 > nonce) {
_setAccountNonce(account, nonce + 1);
}
}
/**
* Creates a new EOA contract account, for account abstraction.
* @dev Essentially functions like ovmCREATE or ovmCREATE2, but we can bypass a lot of checks
* because the contract we're creating is trusted (no need to do safety checking or to
* handle unexpected reverts). Doesn't need to return an address because the address is
* assumed to be the user's actual address.
* @param _messageHash Hash of a message signed by some user, for verification.
* @param _v Signature `v` parameter.
* @param _r Signature `r` parameter.
* @param _s Signature `s` parameter.
*/
function ovmCREATEEOA(
bytes32 _messageHash,
uint8 _v,
bytes32 _r,
bytes32 _s
)
override
public
notStatic
{
// Recover the EOA address from the message hash and signature parameters. Since we do the
// hashing in advance, we don't have handle different message hashing schemes. Even if this
// function were to return the wrong address (rather than explicitly returning the zero
// address), the rest of the transaction would simply fail (since there's no EOA account to
// actually execute the transaction).
address eoa = ecrecover(
_messageHash,
_v + 27,
_r,
_s
);
// Invalid signature is a case we proactively handle with a revert. We could alternatively
// have this function return a `success` boolean, but this is just easier.
if (eoa == address(0)) {
ovmREVERT(bytes("Signature provided for EOA contract creation is invalid."));
}
// If the user already has an EOA account, then there's no need to perform this operation.
if (_hasEmptyAccount(eoa) == false) {
return;
}
// We always need to initialize the contract with the default account values.
_initPendingAccount(eoa);
// Temporarily set the current address so it's easier to access on L2.
address prevADDRESS = messageContext.ovmADDRESS;
messageContext.ovmADDRESS = eoa;
// Creates a duplicate of the OVM_ProxyEOA located at 0x42....09. Uses the following
// "magic" prefix to deploy an exact copy of the code:
// PUSH1 0x0D # size of this prefix in bytes
// CODESIZE
// SUB # subtract prefix size from codesize
// DUP1
// PUSH1 0x0D
// PUSH1 0x00
// CODECOPY # copy everything after prefix into memory at pos 0
// PUSH1 0x00
// RETURN # return the copied code
address proxyEOA = Lib_EthUtils.createContract(abi.encodePacked(
hex"600D380380600D6000396000f3",
ovmEXTCODECOPY(
Lib_PredeployAddresses.PROXY_EOA,
0,
ovmEXTCODESIZE(Lib_PredeployAddresses.PROXY_EOA)
)
));
// Reset the address now that we're done deploying.
messageContext.ovmADDRESS = prevADDRESS;
// Commit the account with its final values.
_commitPendingAccount(
eoa,
address(proxyEOA),
keccak256(Lib_EthUtils.getCode(address(proxyEOA)))
);
_setAccountNonce(eoa, 0);
}
/*********************************
* Opcodes: Contract Interaction *
*********************************/
/**
* @notice Overrides CALL.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _value ETH value to pass with the call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmCALL(
uint256 _gasLimit,
address _address,
uint256 _value,
bytes memory _calldata
)
override
public
fixedGasDiscount(100000)
returns (
bool _success,
bytes memory _returndata
)
{
// CALL updates the CALLER and ADDRESS.
MessageContext memory nextMessageContext = messageContext;
nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS;
nextMessageContext.ovmADDRESS = _address;
nextMessageContext.ovmCALLVALUE = _value;
return _callContract(
nextMessageContext,
_gasLimit,
_address,
_calldata,
MessageType.ovmCALL
);
}
/**
* @notice Overrides STATICCALL.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmSTATICCALL(
uint256 _gasLimit,
address _address,
bytes memory _calldata
)
override
public
fixedGasDiscount(80000)
returns (
bool _success,
bytes memory _returndata
)
{
// STATICCALL updates the CALLER, updates the ADDRESS, and runs in a static,
// valueless context.
MessageContext memory nextMessageContext = messageContext;
nextMessageContext.ovmCALLER = nextMessageContext.ovmADDRESS;
nextMessageContext.ovmADDRESS = _address;
nextMessageContext.isStatic = true;
nextMessageContext.ovmCALLVALUE = 0;
return _callContract(
nextMessageContext,
_gasLimit,
_address,
_calldata,
MessageType.ovmSTATICCALL
);
}
/**
* @notice Overrides DELEGATECALL.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmDELEGATECALL(
uint256 _gasLimit,
address _address,
bytes memory _calldata
)
override
public
fixedGasDiscount(40000)
returns (
bool _success,
bytes memory _returndata
)
{
// DELEGATECALL does not change anything about the message context.
MessageContext memory nextMessageContext = messageContext;
return _callContract(
nextMessageContext,
_gasLimit,
_address,
_calldata,
MessageType.ovmDELEGATECALL
);
}
/**
* @notice Legacy ovmCALL function which did not support ETH value; this maintains backwards
* compatibility.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _address Address of the contract to call.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function ovmCALL(
uint256 _gasLimit,
address _address,
bytes memory _calldata
)
override
public
returns(
bool _success,
bytes memory _returndata
)
{
// Legacy ovmCALL assumed always-0 value.
return ovmCALL(
_gasLimit,
_address,
0,
_calldata
);
}
/************************************
* Opcodes: Contract Storage Access *
************************************/
/**
* @notice Overrides SLOAD.
* @param _key 32 byte key of the storage slot to load.
* @return _value 32 byte value of the requested storage slot.
*/
function ovmSLOAD(
bytes32 _key
)
override
external
netGasCost(40000)
returns (
bytes32 _value
)
{
// We always SLOAD from the storage of ADDRESS.
address contractAddress = ovmADDRESS();
return _getContractStorage(
contractAddress,
_key
);
}
/**
* @notice Overrides SSTORE.
* @param _key 32 byte key of the storage slot to set.
* @param _value 32 byte value for the storage slot.
*/
function ovmSSTORE(
bytes32 _key,
bytes32 _value
)
override
external
notStatic
netGasCost(60000)
{
// We always SSTORE to the storage of ADDRESS.
address contractAddress = ovmADDRESS();
_putContractStorage(
contractAddress,
_key,
_value
);
}
/*********************************
* Opcodes: Contract Code Access *
*********************************/
/**
* @notice Overrides EXTCODECOPY.
* @param _contract Address of the contract to copy code from.
* @param _offset Offset in bytes from the start of contract code to copy beyond.
* @param _length Total number of bytes to copy from the contract's code.
* @return _code Bytes of code copied from the requested contract.
*/
function ovmEXTCODECOPY(
address _contract,
uint256 _offset,
uint256 _length
)
override
public
returns (
bytes memory _code
)
{
return Lib_EthUtils.getCode(
_getAccountEthAddress(_contract),
_offset,
_length
);
}
/**
* @notice Overrides EXTCODESIZE.
* @param _contract Address of the contract to query the size of.
* @return _EXTCODESIZE Size of the requested contract in bytes.
*/
function ovmEXTCODESIZE(
address _contract
)
override
public
returns (
uint256 _EXTCODESIZE
)
{
return Lib_EthUtils.getCodeSize(
_getAccountEthAddress(_contract)
);
}
/**
* @notice Overrides EXTCODEHASH.
* @param _contract Address of the contract to query the hash of.
* @return _EXTCODEHASH Hash of the requested contract.
*/
function ovmEXTCODEHASH(
address _contract
)
override
external
returns (
bytes32 _EXTCODEHASH
)
{
return Lib_EthUtils.getCodeHash(
_getAccountEthAddress(_contract)
);
}
/***************************************
* Public Functions: ETH Value Opcodes *
***************************************/
/**
* @notice Overrides BALANCE.
* NOTE: In the future, this could be optimized to directly invoke EM._getContractStorage(...).
* @param _contract Address of the contract to query the OVM_ETH balance of.
* @return _BALANCE OVM_ETH balance of the requested contract.
*/
function ovmBALANCE(
address _contract
)
override
public
returns (
uint256 _BALANCE
)
{
// Easiest way to get the balance is query OVM_ETH as normal.
bytes memory balanceOfCalldata = abi.encodeWithSignature(
"balanceOf(address)",
_contract
);
// Static call because this should be a read-only query.
(bool success, bytes memory returndata) = ovmSTATICCALL(
gasleft(),
Lib_PredeployAddresses.OVM_ETH,
balanceOfCalldata
);
// All balanceOf queries should successfully return a uint, otherwise this must be an OOG.
if (!success || returndata.length != 32) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
// Return the decoded balance.
return abi.decode(returndata, (uint256));
}
/**
* @notice Overrides SELFBALANCE.
* @return _BALANCE OVM_ETH balance of the requesting contract.
*/
function ovmSELFBALANCE()
override
external
returns (
uint256 _BALANCE
)
{
return ovmBALANCE(ovmADDRESS());
}
/***************************************
* Public Functions: Execution Context *
***************************************/
function getMaxTransactionGasLimit()
external
view
override
returns (
uint256 _maxTransactionGasLimit
)
{
return gasMeterConfig.maxTransactionGasLimit;
}
/********************************************
* Public Functions: Deployment Whitelisting *
********************************************/
/**
* Checks whether the given address is on the whitelist to ovmCREATE/ovmCREATE2,
* and reverts if not.
* @param _deployerAddress Address attempting to deploy a contract.
*/
function _checkDeployerAllowed(
address _deployerAddress
)
internal
{
// From an OVM semantics perspective, this will appear identical to
// the deployer ovmCALLing the whitelist. This is fine--in a sense, we are forcing them to.
(bool success, bytes memory data) = ovmSTATICCALL(
gasleft(),
Lib_PredeployAddresses.DEPLOYER_WHITELIST,
abi.encodeWithSelector(
OVM_DeployerWhitelist.isDeployerAllowed.selector,
_deployerAddress
)
);
bool isAllowed = abi.decode(data, (bool));
if (!isAllowed || !success) {
_revertWithFlag(RevertFlag.CREATOR_NOT_ALLOWED);
}
}
/********************************************
* Internal Functions: Contract Interaction *
********************************************/
/**
* Creates a new contract and associates it with some contract address.
* @param _contractAddress Address to associate the created contract with.
* @param _bytecode Bytecode to be used to create the contract.
* @return Final OVM contract address.
* @return Revertdata, if and only if the creation threw an exception.
*/
function _createContract(
address _contractAddress,
bytes memory _bytecode,
MessageType _messageType
)
internal
returns (
address,
bytes memory
)
{
// We always update the nonce of the creating account, even if the creation fails.
_setAccountNonce(ovmADDRESS(), _getAccountNonce(ovmADDRESS()) + 1);
// We're stepping into a CREATE or CREATE2, so we need to update ADDRESS to point
// to the contract's associated address and CALLER to point to the previous ADDRESS.
MessageContext memory nextMessageContext = messageContext;
nextMessageContext.ovmCALLER = messageContext.ovmADDRESS;
nextMessageContext.ovmADDRESS = _contractAddress;
// Run the common logic which occurs between call-type and create-type messages,
// passing in the creation bytecode and `true` to trigger create-specific logic.
(bool success, bytes memory data) = _handleExternalMessage(
nextMessageContext,
gasleft(),
_contractAddress,
_bytecode,
_messageType
);
// Yellow paper requires that address returned is zero if the contract deployment fails.
return (
success ? _contractAddress : address(0),
data
);
}
/**
* Calls the deployed contract associated with a given address.
* @param _nextMessageContext Message context to be used for the call.
* @param _gasLimit Amount of gas to be passed into this call.
* @param _contract OVM address to be called.
* @param _calldata Data to send along with the call.
* @return _success Whether or not the call returned (rather than reverted).
* @return _returndata Data returned by the call.
*/
function _callContract(
MessageContext memory _nextMessageContext,
uint256 _gasLimit,
address _contract,
bytes memory _calldata,
MessageType _messageType
)
internal
returns (
bool _success,
bytes memory _returndata
)
{
// We reserve addresses of the form 0xdeaddeaddead...NNNN for the container contracts in L2
// geth. So, we block calls to these addresses since they are not safe to run as an OVM
// contract itself.
if (
(uint256(_contract) &
uint256(0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000))
== uint256(CONTAINER_CONTRACT_PREFIX)
) {
// solhint-disable-next-line max-line-length
// EVM does not return data in the success case, see: https://github.com/ethereum/go-ethereum/blob/aae7660410f0ef90279e14afaaf2f429fdc2a186/core/vm/instructions.go#L600-L604
return (true, hex'');
}
// Both 0x0000... and the EVM precompiles have the same address on L1 and L2 -->
// no trie lookup needed.
address codeContractAddress =
uint(_contract) < 100
? _contract
: _getAccountEthAddress(_contract);
return _handleExternalMessage(
_nextMessageContext,
_gasLimit,
codeContractAddress,
_calldata,
_messageType
);
}
/**
* Handles all interactions which involve the execution manager calling out to untrusted code
* (both calls and creates). Ensures that OVM-related measures are enforced, including L2 gas
* refunds, nuisance gas, and flagged reversions.
*
* @param _nextMessageContext Message context to be used for the external message.
* @param _gasLimit Amount of gas to be passed into this message. NOTE: this argument is
* overwritten in some cases to avoid stack-too-deep.
* @param _contract OVM address being called or deployed to
* @param _data Data for the message (either calldata or creation code)
* @param _messageType What type of ovmOPCODE this message corresponds to.
* @return Whether or not the message (either a call or deployment) succeeded.
* @return Data returned by the message.
*/
function _handleExternalMessage(
MessageContext memory _nextMessageContext,
// NOTE: this argument is overwritten in some cases to avoid stack-too-deep.
uint256 _gasLimit,
address _contract,
bytes memory _data,
MessageType _messageType
)
internal
returns (
bool,
bytes memory
)
{
uint256 messageValue = _nextMessageContext.ovmCALLVALUE;
// If there is value in this message, we need to transfer the ETH over before switching
// contexts.
if (
messageValue > 0
&& _isValueType(_messageType)
) {
// Handle out-of-intrinsic gas consistent with EVM behavior -- the subcall "appears to
// revert" if we don't have enough gas to transfer the ETH.
// Similar to dynamic gas cost of value exceeding gas here:
// solhint-disable-next-line max-line-length
// https://github.com/ethereum/go-ethereum/blob/c503f98f6d5e80e079c1d8a3601d188af2a899da/core/vm/interpreter.go#L268-L273
if (gasleft() < CALL_WITH_VALUE_INTRINSIC_GAS) {
return (false, hex"");
}
// If there *is* enough gas to transfer ETH, then we need to make sure this amount of
// gas is reserved (i.e. not given to the _contract.call below) to guarantee that
// _handleExternalMessage can't run out of gas. In particular, in the event that
// the call fails, we will need to transfer the ETH back to the sender.
// Taking the lesser of _gasLimit and gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS
// guarantees that the second _attemptForcedEthTransfer below, if needed, always has
// enough gas to succeed.
_gasLimit = Math.min(
_gasLimit,
gasleft() - CALL_WITH_VALUE_INTRINSIC_GAS // Cannot overflow due to the above check.
);
// Now transfer the value of the call.
// The target is interpreted to be the next message's ovmADDRESS account.
bool transferredOvmEth = _attemptForcedEthTransfer(
_nextMessageContext.ovmADDRESS,
messageValue
);
// If the ETH transfer fails (should only be possible in the case of insufficient
// balance), then treat this as a revert. This mirrors EVM behavior, see
// solhint-disable-next-line max-line-length
// https://github.com/ethereum/go-ethereum/blob/2dee31930c9977af2a9fcb518fb9838aa609a7cf/core/vm/evm.go#L298
if (!transferredOvmEth) {
return (false, hex"");
}
}
// We need to switch over to our next message context for the duration of this call.
MessageContext memory prevMessageContext = messageContext;
_switchMessageContext(prevMessageContext, _nextMessageContext);
// Nuisance gas is a system used to bound the ability for an attacker to make fraud proofs
// expensive by touching a lot of different accounts or storage slots. Since most contracts
// only use a few storage slots during any given transaction, this shouldn't be a limiting
// factor.
uint256 prevNuisanceGasLeft = messageRecord.nuisanceGasLeft;
uint256 nuisanceGasLimit = _getNuisanceGasLimit(_gasLimit);
messageRecord.nuisanceGasLeft = nuisanceGasLimit;
// Make the call and make sure to pass in the gas limit. Another instance of hidden
// complexity. `_contract` is guaranteed to be a safe contract, meaning its return/revert
// behavior can be controlled. In particular, we enforce that flags are passed through
// revert data as to retrieve execution metadata that would normally be reverted out of
// existence.
bool success;
bytes memory returndata;
if (_isCreateType(_messageType)) {
// safeCREATE() is a function which replicates a CREATE message, but uses return values
// Which match that of CALL (i.e. bool, bytes). This allows many security checks to be
// to be shared between untrusted call and create call frames.
(success, returndata) = address(this).call{gas: _gasLimit}(
abi.encodeWithSelector(
this.safeCREATE.selector,
_data,
_contract
)
);
} else {
(success, returndata) = _contract.call{gas: _gasLimit}(_data);
}
// If the message threw an exception, its value should be returned back to the sender.
// So, we force it back, BEFORE returning the messageContext to the previous addresses.
// This operation is part of the reason we "reserved the intrinsic gas" above.
if (
messageValue > 0
&& _isValueType(_messageType)
&& !success
) {
bool transferredOvmEth = _attemptForcedEthTransfer(
prevMessageContext.ovmADDRESS,
messageValue
);
// Since we transferred it in above and the call reverted, the transfer back should
// always pass. This code path should NEVER be triggered since we sent `messageValue`
// worth of OVM_ETH into the target and reserved sufficient gas to execute the transfer,
// but in case there is some edge case which has been missed, we revert the entire frame
// (and its parent) to make sure the ETH gets sent back.
if (!transferredOvmEth) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
}
// Switch back to the original message context now that we're out of the call and all
// OVM_ETH is in the right place.
_switchMessageContext(_nextMessageContext, prevMessageContext);
// Assuming there were no reverts, the message record should be accurate here. We'll update
// this value in the case of a revert.
uint256 nuisanceGasLeft = messageRecord.nuisanceGasLeft;
// Reverts at this point are completely OK, but we need to make a few updates based on the
// information passed through the revert.
if (success == false) {
(
RevertFlag flag,
uint256 nuisanceGasLeftPostRevert,
uint256 ovmGasRefund,
bytes memory returndataFromFlag
) = _decodeRevertData(returndata);
// INVALID_STATE_ACCESS is the only flag that triggers an immediate abort of the
// parent EVM message. This behavior is necessary because INVALID_STATE_ACCESS must
// halt any further transaction execution that could impact the execution result.
if (flag == RevertFlag.INVALID_STATE_ACCESS) {
_revertWithFlag(flag);
}
// INTENTIONAL_REVERT, UNSAFE_BYTECODE, STATIC_VIOLATION, and CREATOR_NOT_ALLOWED aren't
// dependent on the input state, so we can just handle them like standard reverts.
// Our only change here is to record the gas refund reported by the call (enforced by
// safety checking).
if (
flag == RevertFlag.INTENTIONAL_REVERT
|| flag == RevertFlag.UNSAFE_BYTECODE
|| flag == RevertFlag.STATIC_VIOLATION
|| flag == RevertFlag.CREATOR_NOT_ALLOWED
) {
transactionRecord.ovmGasRefund = ovmGasRefund;
}
// INTENTIONAL_REVERT needs to pass up the user-provided return data encoded into the
// flag, *not* the full encoded flag. Additionally, we surface custom error messages
// to developers in the case of unsafe creations for improved devex.
// All other revert types return no data.
if (
flag == RevertFlag.INTENTIONAL_REVERT
|| flag == RevertFlag.UNSAFE_BYTECODE
) {
returndata = returndataFromFlag;
} else {
returndata = hex'';
}
// Reverts mean we need to use up whatever "nuisance gas" was used by the call.
// EXCEEDS_NUISANCE_GAS explicitly reduces the remaining nuisance gas for this message
// to zero. OUT_OF_GAS is a "pseudo" flag given that messages return no data when they
// run out of gas, so we have to treat this like EXCEEDS_NUISANCE_GAS. All other flags
// will simply pass up the remaining nuisance gas.
nuisanceGasLeft = nuisanceGasLeftPostRevert;
}
// We need to reset the nuisance gas back to its original value minus the amount used here.
messageRecord.nuisanceGasLeft = prevNuisanceGasLeft - (nuisanceGasLimit - nuisanceGasLeft);
return (
success,
returndata
);
}
/**
* Handles the creation-specific safety measures required for OVM contract deployment.
* This function sanitizes the return types for creation messages to match calls (bool, bytes),
* by being an external function which the EM can call, that mimics the success/fail case of the
* CREATE.
* This allows for consistent handling of both types of messages in _handleExternalMessage().
* Having this step occur as a separate call frame also allows us to easily revert the
* contract deployment in the event that the code is unsafe.
*
* @param _creationCode Code to pass into CREATE for deployment.
* @param _address OVM address being deployed to.
*/
function safeCREATE(
bytes memory _creationCode,
address _address
)
external
{
// The only way this should callable is from within _createContract(),
// and it should DEFINITELY not be callable by a non-EM code contract.
if (msg.sender != address(this)) {
return;
}
// Check that there is not already code at this address.
if (_hasEmptyAccount(_address) == false) {
// Note: in the EVM, this case burns all allotted gas. For improved
// developer experience, we do return the remaining gas.
_revertWithFlag(
RevertFlag.CREATE_COLLISION
);
}
// Check the creation bytecode against the OVM_SafetyChecker.
if (ovmSafetyChecker.isBytecodeSafe(_creationCode) == false) {
// Note: in the EVM, this case burns all allotted gas. For improved
// developer experience, we do return the remaining gas.
_revertWithFlag(
RevertFlag.UNSAFE_BYTECODE,
// solhint-disable-next-line max-line-length
Lib_ErrorUtils.encodeRevertString("Contract creation code contains unsafe opcodes. Did you use the right compiler or pass an unsafe constructor argument?")
);
}
// We always need to initialize the contract with the default account values.
_initPendingAccount(_address);
// Actually execute the EVM create message.
// NOTE: The inline assembly below means we can NOT make any evm calls between here and then
address ethAddress = Lib_EthUtils.createContract(_creationCode);
if (ethAddress == address(0)) {
// If the creation fails, the EVM lets us grab its revert data. This may contain a
// revert flag to be used above in _handleExternalMessage, so we pass the revert data
// back up unmodified.
assembly {
returndatacopy(0,0,returndatasize())
revert(0, returndatasize())
}
}
// Again simply checking that the deployed code is safe too. Contracts can generate
// arbitrary deployment code, so there's no easy way to analyze this beforehand.
bytes memory deployedCode = Lib_EthUtils.getCode(ethAddress);
if (ovmSafetyChecker.isBytecodeSafe(deployedCode) == false) {
_revertWithFlag(
RevertFlag.UNSAFE_BYTECODE,
// solhint-disable-next-line max-line-length
Lib_ErrorUtils.encodeRevertString("Constructor attempted to deploy unsafe bytecode.")
);
}
// Contract creation didn't need to be reverted and the bytecode is safe. We finish up by
// associating the desired address with the newly created contract's code hash and address.
_commitPendingAccount(
_address,
ethAddress,
Lib_EthUtils.getCodeHash(ethAddress)
);
}
/******************************************
* Internal Functions: Value Manipulation *
******************************************/
/**
* Invokes an ovmCALL to OVM_ETH.transfer on behalf of the current ovmADDRESS, allowing us to
* force movement of OVM_ETH in correspondence with ETH's native value functionality.
* WARNING: this will send on behalf of whatever the messageContext.ovmADDRESS is in storage
* at the time of the call.
* NOTE: In the future, this could be optimized to directly invoke EM._setContractStorage(...).
* @param _to Amount of OVM_ETH to be sent.
* @param _value Amount of OVM_ETH to send.
* @return _success Whether or not the transfer worked.
*/
function _attemptForcedEthTransfer(
address _to,
uint256 _value
)
internal
returns(
bool _success
)
{
bytes memory transferCalldata = abi.encodeWithSignature(
"transfer(address,uint256)",
_to,
_value
);
// OVM_ETH inherits from the UniswapV2ERC20 standard. In this implementation, its return
// type is a boolean. However, the implementation always returns true if it does not revert
// Thus, success of the call frame is sufficient to infer success of the transfer itself.
(bool success, ) = ovmCALL(
gasleft(),
Lib_PredeployAddresses.OVM_ETH,
0,
transferCalldata
);
return success;
}
/******************************************
* Internal Functions: State Manipulation *
******************************************/
/**
* Checks whether an account exists within the OVM_StateManager.
* @param _address Address of the account to check.
* @return _exists Whether or not the account exists.
*/
function _hasAccount(
address _address
)
internal
returns (
bool _exists
)
{
_checkAccountLoad(_address);
return ovmStateManager.hasAccount(_address);
}
/**
* Checks whether a known empty account exists within the OVM_StateManager.
* @param _address Address of the account to check.
* @return _exists Whether or not the account empty exists.
*/
function _hasEmptyAccount(
address _address
)
internal
returns (
bool _exists
)
{
_checkAccountLoad(_address);
return ovmStateManager.hasEmptyAccount(_address);
}
/**
* Sets the nonce of an account.
* @param _address Address of the account to modify.
* @param _nonce New account nonce.
*/
function _setAccountNonce(
address _address,
uint256 _nonce
)
internal
{
_checkAccountChange(_address);
ovmStateManager.setAccountNonce(_address, _nonce);
}
/**
* Gets the nonce of an account.
* @param _address Address of the account to access.
* @return _nonce Nonce of the account.
*/
function _getAccountNonce(
address _address
)
internal
returns (
uint256 _nonce
)
{
_checkAccountLoad(_address);
return ovmStateManager.getAccountNonce(_address);
}
/**
* Retrieves the Ethereum address of an account.
* @param _address Address of the account to access.
* @return _ethAddress Corresponding Ethereum address.
*/
function _getAccountEthAddress(
address _address
)
internal
returns (
address _ethAddress
)
{
_checkAccountLoad(_address);
return ovmStateManager.getAccountEthAddress(_address);
}
/**
* Creates the default account object for the given address.
* @param _address Address of the account create.
*/
function _initPendingAccount(
address _address
)
internal
{
// Although it seems like `_checkAccountChange` would be more appropriate here, we don't
// actually consider an account "changed" until it's inserted into the state (in this case
// by `_commitPendingAccount`).
_checkAccountLoad(_address);
ovmStateManager.initPendingAccount(_address);
}
/**
* Stores additional relevant data for a new account, thereby "committing" it to the state.
* This function is only called during `ovmCREATE` and `ovmCREATE2` after a successful contract
* creation.
* @param _address Address of the account to commit.
* @param _ethAddress Address of the associated deployed contract.
* @param _codeHash Hash of the code stored at the address.
*/
function _commitPendingAccount(
address _address,
address _ethAddress,
bytes32 _codeHash
)
internal
{
_checkAccountChange(_address);
ovmStateManager.commitPendingAccount(
_address,
_ethAddress,
_codeHash
);
}
/**
* Retrieves the value of a storage slot.
* @param _contract Address of the contract to query.
* @param _key 32 byte key of the storage slot.
* @return _value 32 byte storage slot value.
*/
function _getContractStorage(
address _contract,
bytes32 _key
)
internal
returns (
bytes32 _value
)
{
_checkContractStorageLoad(_contract, _key);
return ovmStateManager.getContractStorage(_contract, _key);
}
/**
* Sets the value of a storage slot.
* @param _contract Address of the contract to modify.
* @param _key 32 byte key of the storage slot.
* @param _value 32 byte storage slot value.
*/
function _putContractStorage(
address _contract,
bytes32 _key,
bytes32 _value
)
internal
{
// We don't set storage if the value didn't change. Although this acts as a convenient
// optimization, it's also necessary to avoid the case in which a contract with no storage
// attempts to store the value "0" at any key. Putting this value (and therefore requiring
// that the value be committed into the storage trie after execution) would incorrectly
// modify the storage root.
if (_getContractStorage(_contract, _key) == _value) {
return;
}
_checkContractStorageChange(_contract, _key);
ovmStateManager.putContractStorage(_contract, _key, _value);
}
/**
* Validation whenever a contract needs to be loaded. Checks that the account exists, charges
* nuisance gas if the account hasn't been loaded before.
* @param _address Address of the account to load.
*/
function _checkAccountLoad(
address _address
)
internal
{
// See `_checkContractStorageLoad` for more information.
if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
// See `_checkContractStorageLoad` for more information.
if (ovmStateManager.hasAccount(_address) == false) {
_revertWithFlag(RevertFlag.INVALID_STATE_ACCESS);
}
// Check whether the account has been loaded before and mark it as loaded if not. We need
// this because "nuisance gas" only applies to the first time that an account is loaded.
(
bool _wasAccountAlreadyLoaded
) = ovmStateManager.testAndSetAccountLoaded(_address);
// If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based
// on the size of the contract code.
if (_wasAccountAlreadyLoaded == false) {
_useNuisanceGas(
(Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address))
* NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT
);
}
}
/**
* Validation whenever a contract needs to be changed. Checks that the account exists, charges
* nuisance gas if the account hasn't been changed before.
* @param _address Address of the account to change.
*/
function _checkAccountChange(
address _address
)
internal
{
// Start by checking for a load as we only want to charge nuisance gas proportional to
// contract size once.
_checkAccountLoad(_address);
// Check whether the account has been changed before and mark it as changed if not. We need
// this because "nuisance gas" only applies to the first time that an account is changed.
(
bool _wasAccountAlreadyChanged
) = ovmStateManager.testAndSetAccountChanged(_address);
// If we hadn't already loaded the account, then we'll need to charge "nuisance gas" based
// on the size of the contract code.
if (_wasAccountAlreadyChanged == false) {
ovmStateManager.incrementTotalUncommittedAccounts();
_useNuisanceGas(
(Lib_EthUtils.getCodeSize(_getAccountEthAddress(_address))
* NUISANCE_GAS_PER_CONTRACT_BYTE) + MIN_NUISANCE_GAS_PER_CONTRACT
);
}
}
/**
* Validation whenever a slot needs to be loaded. Checks that the account exists, charges
* nuisance gas if the slot hasn't been loaded before.
* @param _contract Address of the account to load from.
* @param _key 32 byte key to load.
*/
function _checkContractStorageLoad(
address _contract,
bytes32 _key
)
internal
{
// Another case of hidden complexity. If we didn't enforce this requirement, then a
// contract could pass in just enough gas to cause the INVALID_STATE_ACCESS check to fail
// on L1 but not on L2. A contract could use this behavior to prevent the
// OVM_ExecutionManager from detecting an invalid state access. Reverting with OUT_OF_GAS
// allows us to also charge for the full message nuisance gas, because you deserve that for
// trying to break the contract in this way.
if (gasleft() < MIN_GAS_FOR_INVALID_STATE_ACCESS) {
_revertWithFlag(RevertFlag.OUT_OF_GAS);
}
// We need to make sure that the transaction isn't trying to access storage that hasn't
// been provided to the OVM_StateManager. We'll immediately abort if this is the case.
// We know that we have enough gas to do this check because of the above test.
if (ovmStateManager.hasContractStorage(_contract, _key) == false) {
_revertWithFlag(RevertFlag.INVALID_STATE_ACCESS);
}
// Check whether the slot has been loaded before and mark it as loaded if not. We need
// this because "nuisance gas" only applies to the first time that a slot is loaded.
(
bool _wasContractStorageAlreadyLoaded
) = ovmStateManager.testAndSetContractStorageLoaded(_contract, _key);
// If we hadn't already loaded the account, then we'll need to charge some fixed amount of
// "nuisance gas".
if (_wasContractStorageAlreadyLoaded == false) {
_useNuisanceGas(NUISANCE_GAS_SLOAD);
}
}
/**
* Validation whenever a slot needs to be changed. Checks that the account exists, charges
* nuisance gas if the slot hasn't been changed before.
* @param _contract Address of the account to change.
* @param _key 32 byte key to change.
*/
function _checkContractStorageChange(
address _contract,
bytes32 _key
)
internal
{
// Start by checking for load to make sure we have the storage slot and that we charge the
// "nuisance gas" necessary to prove the storage slot state.
_checkContractStorageLoad(_contract, _key);
// Check whether the slot has been changed before and mark it as changed if not. We need
// this because "nuisance gas" only applies to the first time that a slot is changed.
(
bool _wasContractStorageAlreadyChanged
) = ovmStateManager.testAndSetContractStorageChanged(_contract, _key);
// If we hadn't already changed the account, then we'll need to charge some fixed amount of
// "nuisance gas".
if (_wasContractStorageAlreadyChanged == false) {
// Changing a storage slot means that we're also going to have to change the
// corresponding account, so do an account change check.
_checkAccountChange(_contract);
ovmStateManager.incrementTotalUncommittedContractStorage();
_useNuisanceGas(NUISANCE_GAS_SSTORE);
}
}
/************************************
* Internal Functions: Revert Logic *
************************************/
/**
* Simple encoding for revert data.
* @param _flag Flag to revert with.
* @param _data Additional user-provided revert data.
* @return _revertdata Encoded revert data.
*/
function _encodeRevertData(
RevertFlag _flag,
bytes memory _data
)
internal
view
returns (
bytes memory _revertdata
)
{
// Out of gas and create exceptions will fundamentally return no data, so simulating it
// shouldn't either.
if (
_flag == RevertFlag.OUT_OF_GAS
) {
return bytes("");
}
// INVALID_STATE_ACCESS doesn't need to return any data other than the flag.
if (_flag == RevertFlag.INVALID_STATE_ACCESS) {
return abi.encode(
_flag,
0,
0,
bytes("")
);
}
// Just ABI encode the rest of the parameters.
return abi.encode(
_flag,
messageRecord.nuisanceGasLeft,
transactionRecord.ovmGasRefund,
_data
);
}
/**
* Simple decoding for revert data.
* @param _revertdata Revert data to decode.
* @return _flag Flag used to revert.
* @return _nuisanceGasLeft Amount of nuisance gas unused by the message.
* @return _ovmGasRefund Amount of gas refunded during the message.
* @return _data Additional user-provided revert data.
*/
function _decodeRevertData(
bytes memory _revertdata
)
internal
pure
returns (
RevertFlag _flag,
uint256 _nuisanceGasLeft,
uint256 _ovmGasRefund,
bytes memory _data
)
{
// A length of zero means the call ran out of gas, just return empty data.
if (_revertdata.length == 0) {
return (
RevertFlag.OUT_OF_GAS,
0,
0,
bytes("")
);
}
// ABI decode the incoming data.
return abi.decode(_revertdata, (RevertFlag, uint256, uint256, bytes));
}
/**
* Causes a message to revert or abort.
* @param _flag Flag to revert with.
* @param _data Additional user-provided data.
*/
function _revertWithFlag(
RevertFlag _flag,
bytes memory _data
)
internal
view
{
bytes memory revertdata = _encodeRevertData(
_flag,
_data
);
assembly {
revert(add(revertdata, 0x20), mload(revertdata))
}
}
/**
* Causes a message to revert or abort.
* @param _flag Flag to revert with.
*/
function _revertWithFlag(
RevertFlag _flag
)
internal
{
_revertWithFlag(_flag, bytes(""));
}
/******************************************
* Internal Functions: Nuisance Gas Logic *
******************************************/
/**
* Computes the nuisance gas limit from the gas limit.
* @dev This function is currently using a naive implementation whereby the nuisance gas limit
* is set to exactly equal the lesser of the gas limit or remaining gas. It's likely that
* this implementation is perfectly fine, but we may change this formula later.
* @param _gasLimit Gas limit to compute from.
* @return _nuisanceGasLimit Computed nuisance gas limit.
*/
function _getNuisanceGasLimit(
uint256 _gasLimit
)
internal
view
returns (
uint256 _nuisanceGasLimit
)
{
return _gasLimit < gasleft() ? _gasLimit : gasleft();
}
/**
* Uses a certain amount of nuisance gas.
* @param _amount Amount of nuisance gas to use.
*/
function _useNuisanceGas(
uint256 _amount
)
internal
{
// Essentially the same as a standard OUT_OF_GAS, except we also retain a record of the gas
// refund to be given at the end of the transaction.
if (messageRecord.nuisanceGasLeft < _amount) {
_revertWithFlag(RevertFlag.EXCEEDS_NUISANCE_GAS);
}
messageRecord.nuisanceGasLeft -= _amount;
}
/************************************
* Internal Functions: Gas Metering *
************************************/
/**
* Checks whether a transaction needs to start a new epoch and does so if necessary.
* @param _timestamp Transaction timestamp.
*/
function _checkNeedsNewEpoch(
uint256 _timestamp
)
internal
{
if (
_timestamp >= (
_getGasMetadata(GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP)
+ gasMeterConfig.secondsPerEpoch
)
) {
_putGasMetadata(
GasMetadataKey.CURRENT_EPOCH_START_TIMESTAMP,
_timestamp
);
_putGasMetadata(
GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS,
_getGasMetadata(
GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS
)
);
_putGasMetadata(
GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS,
_getGasMetadata(
GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS
)
);
}
}
/**
* Validates the input values of a transaction.
* @return _valid Whether or not the transaction data is valid.
*/
function _isValidInput(
Lib_OVMCodec.Transaction memory _transaction
)
view
internal
returns (
bool
)
{
// Prevent reentrancy to run():
// This check prevents calling run with the default ovmNumber.
// Combined with the first check in run():
// if (transactionContext.ovmNUMBER != DEFAULT_UINT256) { return; }
// It should be impossible to re-enter since run() returns before any other call frames are
// created. Since this value is already being written to storage, we save much gas compared
// to using the standard nonReentrant pattern.
if (_transaction.blockNumber == DEFAULT_UINT256) {
return false;
}
if (_isValidGasLimit(_transaction.gasLimit, _transaction.l1QueueOrigin) == false) {
return false;
}
return true;
}
/**
* Validates the gas limit for a given transaction.
* @param _gasLimit Gas limit provided by the transaction.
* param _queueOrigin Queue from which the transaction originated.
* @return _valid Whether or not the gas limit is valid.
*/
function _isValidGasLimit(
uint256 _gasLimit,
Lib_OVMCodec.QueueOrigin // _queueOrigin
)
view
internal
returns (
bool _valid
)
{
// Always have to be below the maximum gas limit.
if (_gasLimit > gasMeterConfig.maxTransactionGasLimit) {
return false;
}
// Always have to be above the minimum gas limit.
if (_gasLimit < gasMeterConfig.minTransactionGasLimit) {
return false;
}
// TEMPORARY: Gas metering is disabled for minnet.
return true;
// GasMetadataKey cumulativeGasKey;
// GasMetadataKey prevEpochGasKey;
// if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) {
// cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS;
// prevEpochGasKey = GasMetadataKey.PREV_EPOCH_SEQUENCER_QUEUE_GAS;
// } else {
// cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS;
// prevEpochGasKey = GasMetadataKey.PREV_EPOCH_L1TOL2_QUEUE_GAS;
// }
// return (
// (
// _getGasMetadata(cumulativeGasKey)
// - _getGasMetadata(prevEpochGasKey)
// + _gasLimit
// ) < gasMeterConfig.maxGasPerQueuePerEpoch
// );
}
/**
* Updates the cumulative gas after a transaction.
* @param _gasUsed Gas used by the transaction.
* @param _queueOrigin Queue from which the transaction originated.
*/
function _updateCumulativeGas(
uint256 _gasUsed,
Lib_OVMCodec.QueueOrigin _queueOrigin
)
internal
{
GasMetadataKey cumulativeGasKey;
if (_queueOrigin == Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE) {
cumulativeGasKey = GasMetadataKey.CUMULATIVE_SEQUENCER_QUEUE_GAS;
} else {
cumulativeGasKey = GasMetadataKey.CUMULATIVE_L1TOL2_QUEUE_GAS;
}
_putGasMetadata(
cumulativeGasKey,
(
_getGasMetadata(cumulativeGasKey)
+ gasMeterConfig.minTransactionGasLimit
+ _gasUsed
- transactionRecord.ovmGasRefund
)
);
}
/**
* Retrieves the value of a gas metadata key.
* @param _key Gas metadata key to retrieve.
* @return _value Value stored at the given key.
*/
function _getGasMetadata(
GasMetadataKey _key
)
internal
returns (
uint256 _value
)
{
return uint256(_getContractStorage(
GAS_METADATA_ADDRESS,
bytes32(uint256(_key))
));
}
/**
* Sets the value of a gas metadata key.
* @param _key Gas metadata key to set.
* @param _value Value to store at the given key.
*/
function _putGasMetadata(
GasMetadataKey _key,
uint256 _value
)
internal
{
_putContractStorage(
GAS_METADATA_ADDRESS,
bytes32(uint256(_key)),
bytes32(uint256(_value))
);
}
/*****************************************
* Internal Functions: Execution Context *
*****************************************/
/**
* Swaps over to a new message context.
* @param _prevMessageContext Context we're switching from.
* @param _nextMessageContext Context we're switching to.
*/
function _switchMessageContext(
MessageContext memory _prevMessageContext,
MessageContext memory _nextMessageContext
)
internal
{
// These conditionals allow us to avoid unneccessary SSTOREs. However, they do mean that
// the current storage value for the messageContext MUST equal the _prevMessageContext
// argument, or an SSTORE might be erroneously skipped.
if (_prevMessageContext.ovmCALLER != _nextMessageContext.ovmCALLER) {
messageContext.ovmCALLER = _nextMessageContext.ovmCALLER;
}
if (_prevMessageContext.ovmADDRESS != _nextMessageContext.ovmADDRESS) {
messageContext.ovmADDRESS = _nextMessageContext.ovmADDRESS;
}
if (_prevMessageContext.isStatic != _nextMessageContext.isStatic) {
messageContext.isStatic = _nextMessageContext.isStatic;
}
if (_prevMessageContext.ovmCALLVALUE != _nextMessageContext.ovmCALLVALUE) {
messageContext.ovmCALLVALUE = _nextMessageContext.ovmCALLVALUE;
}
}
/**
* Initializes the execution context.
* @param _transaction OVM transaction being executed.
*/
function _initContext(
Lib_OVMCodec.Transaction memory _transaction
)
internal
{
transactionContext.ovmTIMESTAMP = _transaction.timestamp;
transactionContext.ovmNUMBER = _transaction.blockNumber;
transactionContext.ovmTXGASLIMIT = _transaction.gasLimit;
transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin;
transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin;
transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch;
messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit);
}
/**
* Resets the transaction and message context.
*/
function _resetContext()
internal
{
transactionContext.ovmL1TXORIGIN = DEFAULT_ADDRESS;
transactionContext.ovmTIMESTAMP = DEFAULT_UINT256;
transactionContext.ovmNUMBER = DEFAULT_UINT256;
transactionContext.ovmGASLIMIT = DEFAULT_UINT256;
transactionContext.ovmTXGASLIMIT = DEFAULT_UINT256;
transactionContext.ovmL1QUEUEORIGIN = Lib_OVMCodec.QueueOrigin.SEQUENCER_QUEUE;
transactionRecord.ovmGasRefund = DEFAULT_UINT256;
messageContext.ovmCALLER = DEFAULT_ADDRESS;
messageContext.ovmADDRESS = DEFAULT_ADDRESS;
messageContext.isStatic = false;
messageRecord.nuisanceGasLeft = DEFAULT_UINT256;
// Reset the ovmStateManager.
ovmStateManager = iOVM_StateManager(address(0));
}
/******************************************
* Internal Functions: Message Typechecks *
******************************************/
/**
* Returns whether or not the given message type is a CREATE-type.
* @param _messageType the message type in question.
*/
function _isCreateType(
MessageType _messageType
)
internal
pure
returns(
bool
)
{
return (
_messageType == MessageType.ovmCREATE
|| _messageType == MessageType.ovmCREATE2
);
}
/**
* Returns whether or not the given message type (potentially) requires the transfer of ETH
* value along with the message.
* @param _messageType the message type in question.
*/
function _isValueType(
MessageType _messageType
)
internal
pure
returns(
bool
)
{
// ovmSTATICCALL and ovmDELEGATECALL types do not accept or transfer value.
return (
_messageType == MessageType.ovmCALL
|| _messageType == MessageType.ovmCREATE
|| _messageType == MessageType.ovmCREATE2
);
}
/*****************************
* L2-only Helper Functions *
*****************************/
/**
* Unreachable helper function for simulating eth_calls with an OVM message context.
* This function will throw an exception in all cases other than when used as a custom
* entrypoint in L2 Geth to simulate eth_call.
* @param _transaction the message transaction to simulate.
* @param _from the OVM account the simulated call should be from.
* @param _value the amount of ETH value to send.
* @param _ovmStateManager the address of the OVM_StateManager precompile in the L2 state.
*/
function simulateMessage(
Lib_OVMCodec.Transaction memory _transaction,
address _from,
uint256 _value,
iOVM_StateManager _ovmStateManager
)
external
returns (
bytes memory
)
{
// Prevent this call from having any effect unless in a custom-set VM frame
require(msg.sender == address(0));
// Initialize the EM's internal state, ignoring nuisance gas.
ovmStateManager = _ovmStateManager;
_initContext(_transaction);
messageRecord.nuisanceGasLeft = uint(-1);
// Set the ovmADDRESS to the _from so that the subsequent call frame "comes from" them.
messageContext.ovmADDRESS = _from;
// Execute the desired message.
bool isCreate = _transaction.entrypoint == address(0);
if (isCreate) {
(address created, bytes memory revertData) = ovmCREATE(_transaction.data);
if (created == address(0)) {
return abi.encode(false, revertData);
} else {
// The eth_call RPC endpoint for to = undefined will return the deployed bytecode
// in the success case, differing from standard create messages.
return abi.encode(true, Lib_EthUtils.getCode(created));
}
} else {
(bool success, bytes memory returndata) = ovmCALL(
_transaction.gasLimit,
_transaction.entrypoint,
_value,
_transaction.data
);
return abi.encode(success, returndata);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_SafetyChecker
*/
interface iOVM_SafetyChecker {
/********************
* Public Functions *
********************/
function isBytecodeSafe(bytes calldata _bytecode) external pure returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_DeployerWhitelist } from "../../iOVM/predeploys/iOVM_DeployerWhitelist.sol";
/**
* @title OVM_DeployerWhitelist
* @dev The Deployer Whitelist is a temporary predeploy used to provide additional safety during the
* initial phases of our mainnet roll out. It is owned by the Optimism team, and defines accounts
* which are allowed to deploy contracts on Layer2. The Execution Manager will only allow an
* ovmCREATE or ovmCREATE2 operation to proceed if the deployer's address whitelisted.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_DeployerWhitelist is iOVM_DeployerWhitelist {
/**********************
* Contract Constants *
**********************/
bool public initialized;
bool public allowArbitraryDeployment;
address override public owner;
mapping (address => bool) public whitelist;
/**********************
* Function Modifiers *
**********************/
/**
* Blocks functions to anyone except the contract owner.
*/
modifier onlyOwner() {
require(
msg.sender == owner,
"Function can only be called by the owner of this contract."
);
_;
}
/********************
* Public Functions *
********************/
/**
* Initializes the whitelist.
* @param _owner Address of the owner for this contract.
* @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.
*/
function initialize(
address _owner,
bool _allowArbitraryDeployment
)
override
external
{
if (initialized == true) {
return;
}
initialized = true;
allowArbitraryDeployment = _allowArbitraryDeployment;
owner = _owner;
}
/**
* Adds or removes an address from the deployment whitelist.
* @param _deployer Address to update permissions for.
* @param _isWhitelisted Whether or not the address is whitelisted.
*/
function setWhitelistedDeployer(
address _deployer,
bool _isWhitelisted
)
override
external
onlyOwner
{
whitelist[_deployer] = _isWhitelisted;
}
/**
* Updates the owner of this contract.
* @param _owner Address of the new owner.
*/
function setOwner(
address _owner
)
override
public
onlyOwner
{
owner = _owner;
}
/**
* Updates the arbitrary deployment flag.
* @param _allowArbitraryDeployment Whether or not to allow arbitrary contract deployment.
*/
function setAllowArbitraryDeployment(
bool _allowArbitraryDeployment
)
override
public
onlyOwner
{
allowArbitraryDeployment = _allowArbitraryDeployment;
}
/**
* Permanently enables arbitrary contract deployment and deletes the owner.
*/
function enableArbitraryContractDeployment()
override
external
onlyOwner
{
setAllowArbitraryDeployment(true);
setOwner(address(0));
}
/**
* Checks whether an address is allowed to deploy contracts.
* @param _deployer Address to check.
* @return _allowed Whether or not the address can deploy contracts.
*/
function isDeployerAllowed(
address _deployer
)
override
external
returns (
bool
)
{
return (
initialized == false
|| allowArbitraryDeployment == true
|| whitelist[_deployer]
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_DeployerWhitelist
*/
interface iOVM_DeployerWhitelist {
/********************
* Public Functions *
********************/
function initialize(address _owner, bool _allowArbitraryDeployment) external;
function owner() external returns (address _owner);
function setWhitelistedDeployer(address _deployer, bool _isWhitelisted) external;
function setOwner(address _newOwner) external;
function setAllowArbitraryDeployment(bool _allowArbitraryDeployment) external;
function enableArbitraryContractDeployment() external;
function isDeployerAllowed(address _deployer) external returns (bool _allowed);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_SafetyChecker } from "../../iOVM/execution/iOVM_SafetyChecker.sol";
/**
* @title OVM_SafetyChecker
* @dev The Safety Checker verifies that contracts deployed on L2 do not contain any
* "unsafe" operations. An operation is considered unsafe if it would access state variables which
* are specific to the environment (ie. L1 or L2) in which it is executed, as this could be used
* to "escape the sandbox" of the OVM, resulting in non-deterministic fraud proofs.
* That is, an attacker would be able to "prove fraud" on an honestly applied transaction.
* Note that a "safe" contract requires opcodes to appear in a particular pattern;
* omission of "unsafe" opcodes is necessary, but not sufficient.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_SafetyChecker is iOVM_SafetyChecker {
/********************
* Public Functions *
********************/
/**
* Returns whether or not all of the provided bytecode is safe.
* @param _bytecode The bytecode to safety check.
* @return `true` if the bytecode is safe, `false` otherwise.
*/
function isBytecodeSafe(
bytes memory _bytecode
)
override
external
pure
returns (
bool
)
{
// autogenerated by gen_safety_checker_constants.py
// number of bytes to skip for each opcode
uint256[8] memory opcodeSkippableBytes = [
uint256(0x0001010101010101010101010000000001010101010101010101010101010000),
uint256(0x0100000000000000000000000000000000000000010101010101000000010100),
uint256(0x0000000000000000000000000000000001010101000000010101010100000000),
uint256(0x0203040500000000000000000000000000000000000000000000000000000000),
uint256(0x0101010101010101010101010101010101010101010101010101010101010101),
uint256(0x0101010101000000000000000000000000000000000000000000000000000000),
uint256(0x0000000000000000000000000000000000000000000000000000000000000000),
uint256(0x0000000000000000000000000000000000000000000000000000000000000000)
];
// Mask to gate opcode specific cases
// solhint-disable-next-line max-line-length
uint256 opcodeGateMask = ~uint256(0xffffffffffffffffffffffe000000000fffffffff070ffff9c0ffffec000f001);
// Halting opcodes
// solhint-disable-next-line max-line-length
uint256 opcodeHaltingMask = ~uint256(0x4008000000000000000000000000000000000000004000000000000000000001);
// PUSH opcodes
uint256 opcodePushMask = ~uint256(0xffffffff000000000000000000000000);
uint256 codeLength;
uint256 _pc;
assembly {
_pc := add(_bytecode, 0x20)
}
codeLength = _pc + _bytecode.length;
do {
// current opcode: 0x00...0xff
uint256 opNum;
/* solhint-disable max-line-length */
// inline assembly removes the extra add + bounds check
assembly {
let word := mload(_pc) //load the next 32 bytes at pc into word
// Look up number of bytes to skip from opcodeSkippableBytes and then update indexInWord
// E.g. the 02030405 in opcodeSkippableBytes is the number of bytes to skip for PUSH1->4
// We repeat this 6 times, thus we can only skip bytes for up to PUSH4 ((1+4) * 6 = 30 < 32).
// If we see an opcode that is listed as 0 skippable bytes e.g. PUSH5,
// then we will get stuck on that indexInWord and then opNum will be set to the PUSH5 opcode.
let indexInWord := byte(0, mload(add(opcodeSkippableBytes, byte(0, word))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
indexInWord := add(indexInWord, byte(0, mload(add(opcodeSkippableBytes, byte(indexInWord, word)))))
_pc := add(_pc, indexInWord)
opNum := byte(indexInWord, word)
}
/* solhint-enable max-line-length */
// + push opcodes
// + stop opcodes [STOP(0x00),JUMP(0x56),RETURN(0xf3),INVALID(0xfe)]
// + caller opcode CALLER(0x33)
// + blacklisted opcodes
uint256 opBit = 1 << opNum;
if (opBit & opcodeGateMask == 0) {
if (opBit & opcodePushMask == 0) {
// all pushes are valid opcodes
// subsequent bytes are not opcodes. Skip them.
_pc += (opNum - 0x5e); // PUSH1 is 0x60, so opNum-0x5f = PUSHed bytes and we
// +1 to skip the _pc++; line below in order to save gas ((-0x5f + 1) = -0x5e)
continue;
} else if (opBit & opcodeHaltingMask == 0) {
// STOP or JUMP or RETURN or INVALID (Note: REVERT is blacklisted, so not
// included here)
// We are now inside unreachable code until we hit a JUMPDEST!
do {
_pc++;
assembly {
opNum := byte(0, mload(_pc))
}
// encountered a JUMPDEST
if (opNum == 0x5b) break;
// skip PUSHed bytes
// opNum-0x5f = PUSHed bytes (PUSH1 is 0x60)
if ((1 << opNum) & opcodePushMask == 0) _pc += (opNum - 0x5f);
} while (_pc < codeLength);
// opNum is 0x5b, so we don't continue here since the pc++ is fine
} else if (opNum == 0x33) { // Caller opcode
uint256 firstOps; // next 32 bytes of bytecode
uint256 secondOps; // following 32 bytes of bytecode
assembly {
firstOps := mload(_pc)
// 37 bytes total, 5 left over --> 32 - 5 bytes = 27 bytes = 216 bits
secondOps := shr(216, mload(add(_pc, 0x20)))
}
// Call identity precompile
// CALLER POP PUSH1 0x00 PUSH1 0x04 GAS CALL
// 32 - 8 bytes = 24 bytes = 192
if ((firstOps >> 192) == 0x3350600060045af1) {
_pc += 8;
// Call EM and abort execution if instructed
// CALLER PUSH1 0x00 SWAP1 GAS CALL PC PUSH1 0x0E ADD JUMPI RETURNDATASIZE
// PUSH1 0x00 DUP1 RETURNDATACOPY RETURNDATASIZE PUSH1 0x00 REVERT JUMPDEST
// RETURNDATASIZE PUSH1 0x01 EQ ISZERO PC PUSH1 0x0a ADD JUMPI PUSH1 0x01 PUSH1
// 0x00 RETURN JUMPDEST
// solhint-disable-next-line max-line-length
} else if (firstOps == 0x336000905af158600e01573d6000803e3d6000fd5b3d6001141558600a015760 && secondOps == 0x016000f35b) {
_pc += 37;
} else {
return false;
}
continue;
} else {
// encountered a non-whitelisted opcode!
return false;
}
}
_pc++;
} while (_pc < codeLength);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol";
/* Contract Imports */
import { OVM_StateManager } from "./OVM_StateManager.sol";
/**
* @title OVM_StateManagerFactory
* @dev The State Manager Factory is called by a State Transitioner's init code, to create a new
* State Manager for use in the Fraud Verification process.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateManagerFactory is iOVM_StateManagerFactory {
/********************
* Public Functions *
********************/
/**
* Creates a new OVM_StateManager
* @param _owner Owner of the created contract.
* @return New OVM_StateManager instance.
*/
function create(
address _owner
)
override
public
returns (
iOVM_StateManager
)
{
return new OVM_StateManager(_owner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
/**
* @title OVM_StateManager
* @dev The State Manager contract holds all storage values for contracts in the OVM. It can only be
* written to by the Execution Manager and State Transitioner. It runs on L1 during the setup and
* execution of a fraud proof.
* The same logic runs on L2, but has been implemented as a precompile in the L2 go-ethereum client
* (see https://github.com/ethereum-optimism/go-ethereum/blob/master/core/vm/ovm_state_manager.go).
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateManager is iOVM_StateManager {
/*************
* Constants *
*************/
bytes32 constant internal EMPTY_ACCOUNT_STORAGE_ROOT =
0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;
bytes32 constant internal EMPTY_ACCOUNT_CODE_HASH =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 constant internal STORAGE_XOR_VALUE =
0xFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEFFEEDFACECAFEBEEF;
/*************
* Variables *
*************/
address override public owner;
address override public ovmExecutionManager;
mapping (address => Lib_OVMCodec.Account) internal accounts;
mapping (address => mapping (bytes32 => bytes32)) internal contractStorage;
mapping (address => mapping (bytes32 => bool)) internal verifiedContractStorage;
mapping (bytes32 => ItemState) internal itemStates;
uint256 internal totalUncommittedAccounts;
uint256 internal totalUncommittedContractStorage;
/***************
* Constructor *
***************/
/**
* @param _owner Address of the owner of this contract.
*/
constructor(
address _owner
)
{
owner = _owner;
}
/**********************
* Function Modifiers *
**********************/
/**
* Simple authentication, this contract should only be accessible to the owner
* (which is expected to be the State Transitioner during `PRE_EXECUTION`
* or the OVM_ExecutionManager during transaction execution.
*/
modifier authenticated() {
// owner is the State Transitioner
require(
msg.sender == owner || msg.sender == ovmExecutionManager,
"Function can only be called by authenticated addresses"
);
_;
}
/********************
* Public Functions *
********************/
/**
* Checks whether a given address is allowed to modify this contract.
* @param _address Address to check.
* @return Whether or not the address can modify this contract.
*/
function isAuthenticated(
address _address
)
override
public
view
returns (
bool
)
{
return (_address == owner || _address == ovmExecutionManager);
}
/**
* Sets the address of the OVM_ExecutionManager.
* @param _ovmExecutionManager Address of the OVM_ExecutionManager.
*/
function setExecutionManager(
address _ovmExecutionManager
)
override
public
authenticated
{
ovmExecutionManager = _ovmExecutionManager;
}
/**
* Inserts an account into the state.
* @param _address Address of the account to insert.
* @param _account Account to insert for the given address.
*/
function putAccount(
address _address,
Lib_OVMCodec.Account memory _account
)
override
public
authenticated
{
accounts[_address] = _account;
}
/**
* Marks an account as empty.
* @param _address Address of the account to mark.
*/
function putEmptyAccount(
address _address
)
override
public
authenticated
{
Lib_OVMCodec.Account storage account = accounts[_address];
account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT;
account.codeHash = EMPTY_ACCOUNT_CODE_HASH;
}
/**
* Retrieves an account from the state.
* @param _address Address of the account to retrieve.
* @return Account for the given address.
*/
function getAccount(
address _address
)
override
public
view
returns (
Lib_OVMCodec.Account memory
)
{
return accounts[_address];
}
/**
* Checks whether the state has a given account.
* @param _address Address of the account to check.
* @return Whether or not the state has the account.
*/
function hasAccount(
address _address
)
override
public
view
returns (
bool
)
{
return accounts[_address].codeHash != bytes32(0);
}
/**
* Checks whether the state has a given known empty account.
* @param _address Address of the account to check.
* @return Whether or not the state has the empty account.
*/
function hasEmptyAccount(
address _address
)
override
public
view
returns (
bool
)
{
return (
accounts[_address].codeHash == EMPTY_ACCOUNT_CODE_HASH
&& accounts[_address].nonce == 0
);
}
/**
* Sets the nonce of an account.
* @param _address Address of the account to modify.
* @param _nonce New account nonce.
*/
function setAccountNonce(
address _address,
uint256 _nonce
)
override
public
authenticated
{
accounts[_address].nonce = _nonce;
}
/**
* Gets the nonce of an account.
* @param _address Address of the account to access.
* @return Nonce of the account.
*/
function getAccountNonce(
address _address
)
override
public
view
returns (
uint256
)
{
return accounts[_address].nonce;
}
/**
* Retrieves the Ethereum address of an account.
* @param _address Address of the account to access.
* @return Corresponding Ethereum address.
*/
function getAccountEthAddress(
address _address
)
override
public
view
returns (
address
)
{
return accounts[_address].ethAddress;
}
/**
* Retrieves the storage root of an account.
* @param _address Address of the account to access.
* @return Corresponding storage root.
*/
function getAccountStorageRoot(
address _address
)
override
public
view
returns (
bytes32
)
{
return accounts[_address].storageRoot;
}
/**
* Initializes a pending account (during CREATE or CREATE2) with the default values.
* @param _address Address of the account to initialize.
*/
function initPendingAccount(
address _address
)
override
public
authenticated
{
Lib_OVMCodec.Account storage account = accounts[_address];
account.nonce = 1;
account.storageRoot = EMPTY_ACCOUNT_STORAGE_ROOT;
account.codeHash = EMPTY_ACCOUNT_CODE_HASH;
account.isFresh = true;
}
/**
* Finalizes the creation of a pending account (during CREATE or CREATE2).
* @param _address Address of the account to finalize.
* @param _ethAddress Address of the account's associated contract on Ethereum.
* @param _codeHash Hash of the account's code.
*/
function commitPendingAccount(
address _address,
address _ethAddress,
bytes32 _codeHash
)
override
public
authenticated
{
Lib_OVMCodec.Account storage account = accounts[_address];
account.ethAddress = _ethAddress;
account.codeHash = _codeHash;
}
/**
* Checks whether an account has already been retrieved, and marks it as retrieved if not.
* @param _address Address of the account to check.
* @return Whether or not the account was already loaded.
*/
function testAndSetAccountLoaded(
address _address
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_address),
ItemState.ITEM_LOADED
);
}
/**
* Checks whether an account has already been modified, and marks it as modified if not.
* @param _address Address of the account to check.
* @return Whether or not the account was already modified.
*/
function testAndSetAccountChanged(
address _address
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_address),
ItemState.ITEM_CHANGED
);
}
/**
* Attempts to mark an account as committed.
* @param _address Address of the account to commit.
* @return Whether or not the account was committed.
*/
function commitAccount(
address _address
)
override
public
authenticated
returns (
bool
)
{
bytes32 item = _getItemHash(_address);
if (itemStates[item] != ItemState.ITEM_CHANGED) {
return false;
}
itemStates[item] = ItemState.ITEM_COMMITTED;
totalUncommittedAccounts -= 1;
return true;
}
/**
* Increments the total number of uncommitted accounts.
*/
function incrementTotalUncommittedAccounts()
override
public
authenticated
{
totalUncommittedAccounts += 1;
}
/**
* Gets the total number of uncommitted accounts.
* @return Total uncommitted accounts.
*/
function getTotalUncommittedAccounts()
override
public
view
returns (
uint256
)
{
return totalUncommittedAccounts;
}
/**
* Checks whether a given account was changed during execution.
* @param _address Address to check.
* @return Whether or not the account was changed.
*/
function wasAccountChanged(
address _address
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_address);
return itemStates[item] >= ItemState.ITEM_CHANGED;
}
/**
* Checks whether a given account was committed after execution.
* @param _address Address to check.
* @return Whether or not the account was committed.
*/
function wasAccountCommitted(
address _address
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_address);
return itemStates[item] >= ItemState.ITEM_COMMITTED;
}
/************************************
* Public Functions: Storage Access *
************************************/
/**
* Changes a contract storage slot value.
* @param _contract Address of the contract to modify.
* @param _key 32 byte storage slot key.
* @param _value 32 byte storage slot value.
*/
function putContractStorage(
address _contract,
bytes32 _key,
bytes32 _value
)
override
public
authenticated
{
// A hilarious optimization. `SSTORE`ing a value of `bytes32(0)` is common enough that it's
// worth populating this with a non-zero value in advance (during the fraud proof
// initialization phase) to cut the execution-time cost down to 5000 gas.
contractStorage[_contract][_key] = _value ^ STORAGE_XOR_VALUE;
// Only used when initially populating the contract storage. OVM_ExecutionManager will
// perform a `hasContractStorage` INVALID_STATE_ACCESS check before putting any contract
// storage because writing to zero when the actual value is nonzero causes a gas
// discrepancy. Could be moved into a new `putVerifiedContractStorage` function, or
// something along those lines.
if (verifiedContractStorage[_contract][_key] == false) {
verifiedContractStorage[_contract][_key] = true;
}
}
/**
* Retrieves a contract storage slot value.
* @param _contract Address of the contract to access.
* @param _key 32 byte storage slot key.
* @return 32 byte storage slot value.
*/
function getContractStorage(
address _contract,
bytes32 _key
)
override
public
view
returns (
bytes32
)
{
// Storage XOR system doesn't work for newly created contracts that haven't set this
// storage slot value yet.
if (
verifiedContractStorage[_contract][_key] == false
&& accounts[_contract].isFresh
) {
return bytes32(0);
}
// See `putContractStorage` for more information about the XOR here.
return contractStorage[_contract][_key] ^ STORAGE_XOR_VALUE;
}
/**
* Checks whether a contract storage slot exists in the state.
* @param _contract Address of the contract to access.
* @param _key 32 byte storage slot key.
* @return Whether or not the key was set in the state.
*/
function hasContractStorage(
address _contract,
bytes32 _key
)
override
public
view
returns (
bool
)
{
return verifiedContractStorage[_contract][_key] || accounts[_contract].isFresh;
}
/**
* Checks whether a storage slot has already been retrieved, and marks it as retrieved if not.
* @param _contract Address of the contract to check.
* @param _key 32 byte storage slot key.
* @return Whether or not the slot was already loaded.
*/
function testAndSetContractStorageLoaded(
address _contract,
bytes32 _key
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_contract, _key),
ItemState.ITEM_LOADED
);
}
/**
* Checks whether a storage slot has already been modified, and marks it as modified if not.
* @param _contract Address of the contract to check.
* @param _key 32 byte storage slot key.
* @return Whether or not the slot was already modified.
*/
function testAndSetContractStorageChanged(
address _contract,
bytes32 _key
)
override
public
authenticated
returns (
bool
)
{
return _testAndSetItemState(
_getItemHash(_contract, _key),
ItemState.ITEM_CHANGED
);
}
/**
* Attempts to mark a storage slot as committed.
* @param _contract Address of the account to commit.
* @param _key 32 byte slot key to commit.
* @return Whether or not the slot was committed.
*/
function commitContractStorage(
address _contract,
bytes32 _key
)
override
public
authenticated
returns (
bool
)
{
bytes32 item = _getItemHash(_contract, _key);
if (itemStates[item] != ItemState.ITEM_CHANGED) {
return false;
}
itemStates[item] = ItemState.ITEM_COMMITTED;
totalUncommittedContractStorage -= 1;
return true;
}
/**
* Increments the total number of uncommitted storage slots.
*/
function incrementTotalUncommittedContractStorage()
override
public
authenticated
{
totalUncommittedContractStorage += 1;
}
/**
* Gets the total number of uncommitted storage slots.
* @return Total uncommitted storage slots.
*/
function getTotalUncommittedContractStorage()
override
public
view
returns (
uint256
)
{
return totalUncommittedContractStorage;
}
/**
* Checks whether a given storage slot was changed during execution.
* @param _contract Address to check.
* @param _key Key of the storage slot to check.
* @return Whether or not the storage slot was changed.
*/
function wasContractStorageChanged(
address _contract,
bytes32 _key
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_contract, _key);
return itemStates[item] >= ItemState.ITEM_CHANGED;
}
/**
* Checks whether a given storage slot was committed after execution.
* @param _contract Address to check.
* @param _key Key of the storage slot to check.
* @return Whether or not the storage slot was committed.
*/
function wasContractStorageCommitted(
address _contract,
bytes32 _key
)
override
public
view
returns (
bool
)
{
bytes32 item = _getItemHash(_contract, _key);
return itemStates[item] >= ItemState.ITEM_COMMITTED;
}
/**********************
* Internal Functions *
**********************/
/**
* Generates a unique hash for an address.
* @param _address Address to generate a hash for.
* @return Unique hash for the given address.
*/
function _getItemHash(
address _address
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_address));
}
/**
* Generates a unique hash for an address/key pair.
* @param _contract Address to generate a hash for.
* @param _key Key to generate a hash for.
* @return Unique hash for the given pair.
*/
function _getItemHash(
address _contract,
bytes32 _key
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(
_contract,
_key
));
}
/**
* Checks whether an item is in a particular state (ITEM_LOADED or ITEM_CHANGED) and sets the
* item to the provided state if not.
* @param _item 32 byte item ID to check.
* @param _minItemState Minimum state that must be satisfied by the item.
* @return Whether or not the item was already in the state.
*/
function _testAndSetItemState(
bytes32 _item,
ItemState _minItemState
)
internal
returns (
bool
)
{
bool wasItemState = itemStates[_item] >= _minItemState;
if (wasItemState == false) {
itemStates[_item] = _minItemState;
}
return wasItemState;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../optimistic-ethereum/libraries/codec/Lib_OVMCodec.sol";
/**
* @title TestLib_OVMCodec
*/
contract TestLib_OVMCodec {
function encodeTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
public
pure
returns (
bytes memory _encoded
)
{
return Lib_OVMCodec.encodeTransaction(_transaction);
}
function hashTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
public
pure
returns (
bytes32 _hash
)
{
return Lib_OVMCodec.hashTransaction(_transaction);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressManager } from "../../../libraries/resolver/Lib_AddressManager.sol";
import { Lib_SecureMerkleTrie } from "../../../libraries/trie/Lib_SecureMerkleTrie.sol";
import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol";
import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol";
/* Interface Imports */
import { iOVM_L1CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol";
import { iOVM_CanonicalTransactionChain } from
"../../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
import { iOVM_StateCommitmentChain } from "../../../iOVM/chain/iOVM_StateCommitmentChain.sol";
/* External Imports */
import { OwnableUpgradeable } from
"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { PausableUpgradeable } from
"@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import { ReentrancyGuardUpgradeable } from
"@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
/**
* @title OVM_L1CrossDomainMessenger
* @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages
* from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2
* epoch gas limit, it can be resubmitted via this contract's replay function.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_L1CrossDomainMessenger is
iOVM_L1CrossDomainMessenger,
Lib_AddressResolver,
OwnableUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable
{
/**********
* Events *
**********/
event MessageBlocked(
bytes32 indexed _xDomainCalldataHash
);
event MessageAllowed(
bytes32 indexed _xDomainCalldataHash
);
/*************
* Constants *
*************/
// The default x-domain message sender being set to a non-zero value makes
// deployment a bit more expensive, but in exchange the refund on every call to
// `relayMessage` by the L1 and L2 messengers will be higher.
address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD;
/**********************
* Contract Variables *
**********************/
mapping (bytes32 => bool) public blockedMessages;
mapping (bytes32 => bool) public relayedMessages;
mapping (bytes32 => bool) public successfulMessages;
address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
/***************
* Constructor *
***************/
/**
* This contract is intended to be behind a delegate proxy.
* We pass the zero address to the address resolver just to satisfy the constructor.
* We still need to set this value in initialize().
*/
constructor()
Lib_AddressResolver(address(0))
{}
/**********************
* Function Modifiers *
**********************/
/**
* Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may
* successfully call a method.
*/
modifier onlyRelayer() {
address relayer = resolve("OVM_L2MessageRelayer");
if (relayer != address(0)) {
require(
msg.sender == relayer,
"Only OVM_L2MessageRelayer can relay L2-to-L1 messages."
);
}
_;
}
/********************
* Public Functions *
********************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
function initialize(
address _libAddressManager
)
public
initializer
{
require(
address(libAddressManager) == address(0),
"L1CrossDomainMessenger already intialized."
);
libAddressManager = Lib_AddressManager(_libAddressManager);
xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
// Initialize upgradable OZ contracts
__Context_init_unchained(); // Context is a dependency for both Ownable and Pausable
__Ownable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
/**
* Pause relaying.
*/
function pause()
external
onlyOwner
{
_pause();
}
/**
* Block a message.
* @param _xDomainCalldataHash Hash of the message to block.
*/
function blockMessage(
bytes32 _xDomainCalldataHash
)
external
onlyOwner
{
blockedMessages[_xDomainCalldataHash] = true;
emit MessageBlocked(_xDomainCalldataHash);
}
/**
* Allow a message.
* @param _xDomainCalldataHash Hash of the message to block.
*/
function allowMessage(
bytes32 _xDomainCalldataHash
)
external
onlyOwner
{
blockedMessages[_xDomainCalldataHash] = false;
emit MessageAllowed(_xDomainCalldataHash);
}
function xDomainMessageSender()
public
override
view
returns (
address
)
{
require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set");
return xDomainMsgSender;
}
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes memory _message,
uint32 _gasLimit
)
override
public
{
address ovmCanonicalTransactionChain = resolve("OVM_CanonicalTransactionChain");
// Use the CTC queue length as nonce
uint40 nonce =
iOVM_CanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength();
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
msg.sender,
_message,
nonce
);
address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger");
_sendXDomainMessage(
ovmCanonicalTransactionChain,
l2CrossDomainMessenger,
xDomainCalldata,
_gasLimit
);
emit SentMessage(xDomainCalldata);
}
/**
* Relays a cross domain message to a contract.
* @inheritdoc iOVM_L1CrossDomainMessenger
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce,
L2MessageInclusionProof memory _proof
)
override
public
nonReentrant
onlyRelayer
whenNotPaused
{
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
_sender,
_message,
_messageNonce
);
require(
_verifyXDomainMessage(
xDomainCalldata,
_proof
) == true,
"Provided message could not be verified."
);
bytes32 xDomainCalldataHash = keccak256(xDomainCalldata);
require(
successfulMessages[xDomainCalldataHash] == false,
"Provided message has already been received."
);
require(
blockedMessages[xDomainCalldataHash] == false,
"Provided message has been blocked."
);
require(
_target != resolve("OVM_CanonicalTransactionChain"),
"Cannot send L2->L1 messages to L1 system contracts."
);
xDomainMsgSender = _sender;
(bool success, ) = _target.call(_message);
xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
// Mark the message as received if the call was successful. Ensures that a message can be
// relayed multiple times in the case that the call reverted.
if (success == true) {
successfulMessages[xDomainCalldataHash] = true;
emit RelayedMessage(xDomainCalldataHash);
} else {
emit FailedRelayedMessage(xDomainCalldataHash);
}
// Store an identifier that can be used to prove that the given message was relayed by some
// user. Gives us an easy way to pay relayers for their work.
bytes32 relayId = keccak256(
abi.encodePacked(
xDomainCalldata,
msg.sender,
block.number
)
);
relayedMessages[relayId] = true;
}
/**
* Replays a cross domain message to the target messenger.
* @inheritdoc iOVM_L1CrossDomainMessenger
*/
function replayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _queueIndex,
uint32 _gasLimit
)
override
public
{
// Verify that the message is in the queue:
address canonicalTransactionChain = resolve("OVM_CanonicalTransactionChain");
Lib_OVMCodec.QueueElement memory element =
iOVM_CanonicalTransactionChain(canonicalTransactionChain).getQueueElement(_queueIndex);
address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger");
// Compute the transactionHash
bytes32 transactionHash = keccak256(
abi.encode(
address(this),
l2CrossDomainMessenger,
_gasLimit,
_message
)
);
require(
transactionHash == element.transactionHash,
"Provided message has not been enqueued."
);
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
_sender,
_message,
_queueIndex
);
_sendXDomainMessage(
canonicalTransactionChain,
l2CrossDomainMessenger,
xDomainCalldata,
_gasLimit
);
}
/**********************
* Internal Functions *
**********************/
/**
* Verifies that the given message is valid.
* @param _xDomainCalldata Calldata to verify.
* @param _proof Inclusion proof for the message.
* @return Whether or not the provided message is valid.
*/
function _verifyXDomainMessage(
bytes memory _xDomainCalldata,
L2MessageInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
return (
_verifyStateRootProof(_proof)
&& _verifyStorageProof(_xDomainCalldata, _proof)
);
}
/**
* Verifies that the state root within an inclusion proof is valid.
* @param _proof Message inclusion proof.
* @return Whether or not the provided proof is valid.
*/
function _verifyStateRootProof(
L2MessageInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(
resolve("OVM_StateCommitmentChain")
);
return (
ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false
&& ovmStateCommitmentChain.verifyStateCommitment(
_proof.stateRoot,
_proof.stateRootBatchHeader,
_proof.stateRootProof
)
);
}
/**
* Verifies that the storage proof within an inclusion proof is valid.
* @param _xDomainCalldata Encoded message calldata.
* @param _proof Message inclusion proof.
* @return Whether or not the provided proof is valid.
*/
function _verifyStorageProof(
bytes memory _xDomainCalldata,
L2MessageInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
bytes32 storageKey = keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_xDomainCalldata,
resolve("OVM_L2CrossDomainMessenger")
)
),
uint256(0)
)
);
(
bool exists,
bytes memory encodedMessagePassingAccount
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER),
_proof.stateTrieWitness,
_proof.stateRoot
);
require(
exists == true,
"Message passing predeploy has not been initialized or invalid proof provided."
);
Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(
encodedMessagePassingAccount
);
return Lib_SecureMerkleTrie.verifyInclusionProof(
abi.encodePacked(storageKey),
abi.encodePacked(uint8(1)),
_proof.storageTrieWitness,
account.storageRoot
);
}
/**
* Sends a cross domain message.
* @param _canonicalTransactionChain Address of the OVM_CanonicalTransactionChain instance.
* @param _l2CrossDomainMessenger Address of the OVM_L2CrossDomainMessenger instance.
* @param _message Message to send.
* @param _gasLimit OVM gas limit for the message.
*/
function _sendXDomainMessage(
address _canonicalTransactionChain,
address _l2CrossDomainMessenger,
bytes memory _message,
uint256 _gasLimit
)
internal
{
iOVM_CanonicalTransactionChain(_canonicalTransactionChain).enqueue(
_l2CrossDomainMessenger,
_gasLimit,
_message
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
/**
* @title Lib_CrossDomainUtils
*/
library Lib_CrossDomainUtils {
/**
* Generates the correct cross domain calldata for a message.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
* @return ABI encoded cross domain calldata.
*/
function encodeXDomainCalldata(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce
)
internal
pure
returns (
bytes memory
)
{
return abi.encodeWithSignature(
"relayMessage(address,address,bytes,uint256)",
_target,
_sender,
_message,
_messageNonce
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol";
/**
* @title iOVM_L1CrossDomainMessenger
*/
interface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger {
/*******************
* Data Structures *
*******************/
struct L2MessageInclusionProof {
bytes32 stateRoot;
Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader;
Lib_OVMCodec.ChainInclusionProof stateRootProof;
bytes stateTrieWitness;
bytes storageTrieWitness;
}
/********************
* Public Functions *
********************/
/**
* Relays a cross domain message to a contract.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
* @param _proof Inclusion proof for the given message.
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce,
L2MessageInclusionProof memory _proof
) external;
/**
* Replays a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _sender Original sender address.
* @param _message Message to send to the target.
* @param _queueIndex CTC Queue index for the message to replay.
* @param _gasLimit Gas limit for the provided message.
*/
function replayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _queueIndex,
uint32 _gasLimit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.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 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 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 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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.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 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 initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/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 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 ContextUpgradeable is Initializable {
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;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.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 !AddressUpgradeable.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 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;
// 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);
}
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
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol";
import { iOVM_L1MultiMessageRelayer } from
"../../../iOVM/bridge/messaging/iOVM_L1MultiMessageRelayer.sol";
/* Library Imports */
import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol";
/**
* @title OVM_L1MultiMessageRelayer
* @dev The L1 Multi-Message Relayer contract is a gas efficiency optimization which enables the
* relayer to submit multiple messages in a single transaction to be relayed by the L1 Cross Domain
* Message Sender.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_L1MultiMessageRelayer is iOVM_L1MultiMessageRelayer, Lib_AddressResolver {
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/**********************
* Function Modifiers *
**********************/
modifier onlyBatchRelayer() {
require(
msg.sender == resolve("OVM_L2BatchMessageRelayer"),
// solhint-disable-next-line max-line-length
"OVM_L1MultiMessageRelayer: Function can only be called by the OVM_L2BatchMessageRelayer"
);
_;
}
/********************
* Public Functions *
********************/
/**
* @notice Forwards multiple cross domain messages to the L1 Cross Domain Messenger for relaying
* @param _messages An array of L2 to L1 messages
*/
function batchRelayMessages(
L2ToL1Message[] calldata _messages
)
override
external
onlyBatchRelayer
{
iOVM_L1CrossDomainMessenger messenger = iOVM_L1CrossDomainMessenger(
resolve("Proxy__OVM_L1CrossDomainMessenger")
);
for (uint256 i = 0; i < _messages.length; i++) {
L2ToL1Message memory message = _messages[i];
messenger.relayMessage(
message.target,
message.sender,
message.message,
message.messageNonce,
message.proof
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_L1CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol";
interface iOVM_L1MultiMessageRelayer {
struct L2ToL1Message {
address target;
address sender;
bytes message;
uint256 messageNonce;
iOVM_L1CrossDomainMessenger.L2MessageInclusionProof proof;
}
function batchRelayMessages(L2ToL1Message[] calldata _messages) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol";
/* Interface Imports */
import { iOVM_L2CrossDomainMessenger } from
"../../../iOVM/bridge/messaging/iOVM_L2CrossDomainMessenger.sol";
import { iOVM_L1MessageSender } from "../../../iOVM/predeploys/iOVM_L1MessageSender.sol";
import { iOVM_L2ToL1MessagePasser } from "../../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol";
/* External Imports */
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/* External Imports */
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
/**
* @title OVM_L2CrossDomainMessenger
* @dev The L2 Cross Domain Messenger contract sends messages from L2 to L1, and is the entry point
* for L2 messages sent via the L1 Cross Domain Messenger.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_L2CrossDomainMessenger is
iOVM_L2CrossDomainMessenger,
Lib_AddressResolver,
ReentrancyGuard
{
/*************
* Constants *
*************/
// The default x-domain message sender being set to a non-zero value makes
// deployment a bit more expensive, but in exchange the refund on every call to
// `relayMessage` by the L1 and L2 messengers will be higher.
address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD;
/*************
* Variables *
*************/
mapping (bytes32 => bool) public relayedMessages;
mapping (bytes32 => bool) public successfulMessages;
mapping (bytes32 => bool) public sentMessages;
uint256 public messageNonce;
address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
constructor(address _libAddressManager)
Lib_AddressResolver(_libAddressManager)
ReentrancyGuard()
{}
/********************
* Public Functions *
********************/
function xDomainMessageSender()
public
override
view
returns (
address
)
{
require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set");
return xDomainMsgSender;
}
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes memory _message,
uint32 _gasLimit
)
override
public
{
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
msg.sender,
_message,
messageNonce
);
messageNonce += 1;
sentMessages[keccak256(xDomainCalldata)] = true;
_sendXDomainMessage(xDomainCalldata, _gasLimit);
emit SentMessage(xDomainCalldata);
}
/**
* Relays a cross domain message to a contract.
* @inheritdoc iOVM_L2CrossDomainMessenger
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce
)
override
nonReentrant
public
{
require(
_verifyXDomainMessage() == true,
"Provided message could not be verified."
);
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
_sender,
_message,
_messageNonce
);
bytes32 xDomainCalldataHash = keccak256(xDomainCalldata);
require(
successfulMessages[xDomainCalldataHash] == false,
"Provided message has already been received."
);
// Prevent calls to OVM_L2ToL1MessagePasser, which would enable
// an attacker to maliciously craft the _message to spoof
// a call from any L2 account.
if(_target == resolve("OVM_L2ToL1MessagePasser")){
// Write to the successfulMessages mapping and return immediately.
successfulMessages[xDomainCalldataHash] = true;
return;
}
xDomainMsgSender = _sender;
(bool success, ) = _target.call(_message);
xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
// Mark the message as received if the call was successful. Ensures that a message can be
// relayed multiple times in the case that the call reverted.
if (success == true) {
successfulMessages[xDomainCalldataHash] = true;
emit RelayedMessage(xDomainCalldataHash);
} else {
emit FailedRelayedMessage(xDomainCalldataHash);
}
// Store an identifier that can be used to prove that the given message was relayed by some
// user. Gives us an easy way to pay relayers for their work.
bytes32 relayId = keccak256(
abi.encodePacked(
xDomainCalldata,
msg.sender,
block.number
)
);
relayedMessages[relayId] = true;
}
/**********************
* Internal Functions *
**********************/
/**
* Verifies that a received cross domain message is valid.
* @return _valid Whether or not the message is valid.
*/
function _verifyXDomainMessage()
view
internal
returns (
bool _valid
)
{
return (
iOVM_L1MessageSender(
resolve("OVM_L1MessageSender")
).getL1MessageSender() == resolve("OVM_L1CrossDomainMessenger")
);
}
/**
* Sends a cross domain message.
* @param _message Message to send.
* param _gasLimit Gas limit for the provided message.
*/
function _sendXDomainMessage(
bytes memory _message,
uint256 // _gasLimit
)
internal
{
iOVM_L2ToL1MessagePasser(resolve("OVM_L2ToL1MessagePasser")).passMessageToL1(_message);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Interface Imports */
import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol";
/**
* @title iOVM_L2CrossDomainMessenger
*/
interface iOVM_L2CrossDomainMessenger is iOVM_CrossDomainMessenger {
/********************
* Public Functions *
********************/
/**
* Relays a cross domain message to a contract.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_L1MessageSender
*/
interface iOVM_L1MessageSender {
/********************
* Public Functions *
********************/
function getL1MessageSender() external view returns (address _l1MessageSender);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_L2ToL1MessagePasser
*/
interface iOVM_L2ToL1MessagePasser {
/**********
* Events *
**********/
event L2ToL1Message(
uint256 _nonce,
address _sender,
bytes _data
);
/********************
* Public Functions *
********************/
function passMessageToL1(bytes calldata _message) external;
}
// 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.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_L2ToL1MessagePasser } from "../../iOVM/predeploys/iOVM_L2ToL1MessagePasser.sol";
/**
* @title OVM_L2ToL1MessagePasser
* @dev The L2 to L1 Message Passer is a utility contract which facilitate an L1 proof of the
* of a message on L2. The L1 Cross Domain Messenger performs this proof in its
* _verifyStorageProof function, which verifies the existence of the transaction hash in this
* contract's `sentMessages` mapping.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_L2ToL1MessagePasser is iOVM_L2ToL1MessagePasser {
/**********************
* Contract Variables *
**********************/
mapping (bytes32 => bool) public sentMessages;
/********************
* Public Functions *
********************/
/**
* Passes a message to L1.
* @param _message Message to pass to L1.
*/
function passMessageToL1(
bytes memory _message
)
override
public
{
// Note: although this function is public, only messages sent from the
// OVM_L2CrossDomainMessenger will be relayed by the OVM_L1CrossDomainMessenger.
// This is enforced by a check in OVM_L1CrossDomainMessenger._verifyStorageProof().
sentMessages[keccak256(
abi.encodePacked(
_message,
msg.sender
)
)] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_L1MessageSender } from "../../iOVM/predeploys/iOVM_L1MessageSender.sol";
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
/**
* @title OVM_L1MessageSender
* @dev The L1MessageSender is a predeploy contract running on L2. During the execution of cross
* domain transaction from L1 to L2, it returns the address of the L1 account (either an EOA or
* contract) which sent the message to L2 via the Canonical Transaction Chain's `enqueue()`
* function.
*
* This contract exclusively serves as a getter for the ovmL1TXORIGIN operation. This is necessary
* because there is no corresponding operation in the EVM which the the optimistic solidity compiler
* can be replaced with a call to the ExecutionManager's ovmL1TXORIGIN() function.
*
*
* Compiler used: solc
* Runtime target: OVM
*/
contract OVM_L1MessageSender is iOVM_L1MessageSender {
/********************
* Public Functions *
********************/
/**
* @return _l1MessageSender L1 message sender address (msg.sender).
*/
function getL1MessageSender()
override
public
view
returns (
address _l1MessageSender
)
{
// Note that on L2 msg.sender (ie. evmCALLER) will always be the Execution Manager
return iOVM_ExecutionManager(msg.sender).ovmL1TXORIGIN();
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../../optimistic-ethereum/libraries/rlp/Lib_RLPReader.sol";
/**
* @title TestLib_RLPReader
*/
contract TestLib_RLPReader {
function readList(
bytes memory _in
)
public
pure
returns (
bytes[] memory
)
{
Lib_RLPReader.RLPItem[] memory decoded = Lib_RLPReader.readList(_in);
bytes[] memory out = new bytes[](decoded.length);
for (uint256 i = 0; i < out.length; i++) {
out[i] = Lib_RLPReader.readRawBytes(decoded[i]);
}
return out;
}
function readString(
bytes memory _in
)
public
pure
returns (
string memory
)
{
return Lib_RLPReader.readString(_in);
}
function readBytes(
bytes memory _in
)
public
pure
returns (
bytes memory
)
{
return Lib_RLPReader.readBytes(_in);
}
function readBytes32(
bytes memory _in
)
public
pure
returns (
bytes32
)
{
return Lib_RLPReader.readBytes32(_in);
}
function readUint256(
bytes memory _in
)
public
pure
returns (
uint256
)
{
return Lib_RLPReader.readUint256(_in);
}
function readBool(
bytes memory _in
)
public
pure
returns (
bool
)
{
return Lib_RLPReader.readBool(_in);
}
function readAddress(
bytes memory _in
)
public
pure
returns (
address
)
{
return Lib_RLPReader.readAddress(_in);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_MerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_MerkleTrie.sol";
/**
* @title TestLib_MerkleTrie
*/
contract TestLib_MerkleTrie {
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bool
)
{
return Lib_MerkleTrie.verifyInclusionProof(
_key,
_value,
_proof,
_root
);
}
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bytes32
)
{
return Lib_MerkleTrie.update(
_key,
_value,
_proof,
_root
);
}
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bool,
bytes memory
)
{
return Lib_MerkleTrie.get(
_key,
_proof,
_root
);
}
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
public
pure
returns (
bytes32
)
{
return Lib_MerkleTrie.getSingleNodeRootHash(
_key,
_value
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_SecureMerkleTrie } from "../../optimistic-ethereum/libraries/trie/Lib_SecureMerkleTrie.sol";
/**
* @title TestLib_SecureMerkleTrie
*/
contract TestLib_SecureMerkleTrie {
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bool
)
{
return Lib_SecureMerkleTrie.verifyInclusionProof(
_key,
_value,
_proof,
_root
);
}
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bytes32
)
{
return Lib_SecureMerkleTrie.update(
_key,
_value,
_proof,
_root
);
}
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
public
pure
returns (
bool,
bytes memory
)
{
return Lib_SecureMerkleTrie.get(
_key,
_proof,
_root
);
}
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
public
pure
returns (
bytes32
)
{
return Lib_SecureMerkleTrie.getSingleNodeRootHash(
_key,
_value
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_ResolvedDelegateProxy
*/
contract Lib_ResolvedDelegateProxy {
/*************
* Variables *
*************/
// Using mappings to store fields to avoid overwriting storage slots in the
// implementation contract. For example, instead of storing these fields at
// storage slot `0` & `1`, they are stored at `keccak256(key + slot)`.
// See: https://solidity.readthedocs.io/en/v0.7.0/internals/layout_in_storage.html
// NOTE: Do not use this code in your own contract system.
// There is a known flaw in this contract, and we will remove it from the repository
// in the near future. Due to the very limited way that we are using it, this flaw is
// not an issue in our system.
mapping (address => string) private implementationName;
mapping (address => Lib_AddressManager) private addressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
* @param _implementationName implementationName of the contract to proxy to.
*/
constructor(
address _libAddressManager,
string memory _implementationName
) {
addressManager[address(this)] = Lib_AddressManager(_libAddressManager);
implementationName[address(this)] = _implementationName;
}
/*********************
* Fallback Function *
*********************/
fallback()
external
payable
{
address target = addressManager[address(this)].getAddress(
(implementationName[address(this)])
);
require(
target != address(0),
"Target address must be initialized."
);
(bool success, bytes memory returndata) = target.delegatecall(msg.data);
if (success == true) {
assembly {
return(add(returndata, 0x20), mload(returndata))
}
} else {
assembly {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title OVM_GasPriceOracle
* @dev This contract exposes the current l2 gas price, a measure of how congested the network
* currently is. This measure is used by the Sequencer to determine what fee to charge for
* transactions. When the system is more congested, the l2 gas price will increase and fees
* will also increase as a result.
*
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_GasPriceOracle is Ownable {
/*************
* Variables *
*************/
// Current l2 gas price
uint256 public gasPrice;
/***************
* Constructor *
***************/
/**
* @param _owner Address that will initially own this contract.
*/
constructor(
address _owner,
uint256 _initialGasPrice
)
Ownable()
{
setGasPrice(_initialGasPrice);
transferOwnership(_owner);
}
/********************
* Public Functions *
********************/
/**
* Allows the owner to modify the l2 gas price.
* @param _gasPrice New l2 gas price.
*/
function setGasPrice(
uint256 _gasPrice
)
public
onlyOwner
{
gasPrice = _gasPrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Contract Imports */
import { L2StandardERC20 } from "../../../libraries/standards/L2StandardERC20.sol";
import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol";
/**
* @title OVM_L2StandardTokenFactory
* @dev Factory contract for creating standard L2 token representations of L1 ERC20s
* compatible with and working on the standard bridge.
* Compiler used: optimistic-solc
* Runtime target: OVM
*/
contract OVM_L2StandardTokenFactory {
event StandardL2TokenCreated(address indexed _l1Token, address indexed _l2Token);
/**
* @dev Creates an instance of the standard ERC20 token on L2.
* @param _l1Token Address of the corresponding L1 token.
* @param _name ERC20 name.
* @param _symbol ERC20 symbol.
*/
function createStandardL2Token(
address _l1Token,
string memory _name,
string memory _symbol
)
external
{
require (_l1Token != address(0), "Must provide L1 token address");
L2StandardERC20 l2Token = new L2StandardERC20(
Lib_PredeployAddresses.L2_STANDARD_BRIDGE,
_l1Token,
_name,
_symbol
);
emit StandardL2TokenCreated(_l1Token, address(l2Token));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_Bytes32Utils } from "../../optimistic-ethereum/libraries/utils/Lib_Bytes32Utils.sol";
/**
* @title TestLib_Byte32Utils
*/
contract TestLib_Bytes32Utils {
function toBool(
bytes32 _in
)
public
pure
returns (
bool _out
)
{
return Lib_Bytes32Utils.toBool(_in);
}
function fromBool(
bool _in
)
public
pure
returns (
bytes32 _out
)
{
return Lib_Bytes32Utils.fromBool(_in);
}
function toAddress(
bytes32 _in
)
public
pure
returns (
address _out
)
{
return Lib_Bytes32Utils.toAddress(_in);
}
function fromAddress(
address _in
)
public
pure
returns (
bytes32 _out
)
{
return Lib_Bytes32Utils.fromAddress(_in);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_EthUtils } from "../../optimistic-ethereum/libraries/utils/Lib_EthUtils.sol";
/**
* @title TestLib_EthUtils
*/
contract TestLib_EthUtils {
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
public
view
returns (
bytes memory _code
)
{
return Lib_EthUtils.getCode(
_address,
_offset,
_length
);
}
function getCode(
address _address
)
public
view
returns (
bytes memory _code
)
{
return Lib_EthUtils.getCode(
_address
);
}
function getCodeSize(
address _address
)
public
view
returns (
uint256 _codeSize
)
{
return Lib_EthUtils.getCodeSize(
_address
);
}
function getCodeHash(
address _address
)
public
view
returns (
bytes32 _codeHash
)
{
return Lib_EthUtils.getCodeHash(
_address
);
}
function createContract(
bytes memory _code
)
public
returns (
address _created
)
{
return Lib_EthUtils.createContract(
_code
);
}
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
public
pure
returns (
address _address
)
{
return Lib_EthUtils.getAddressForCREATE(
_creator,
_nonce
);
}
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
public
pure
returns (address _address)
{
return Lib_EthUtils.getAddressForCREATE2(
_creator,
_bytecode,
_salt
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_MerkleTree } from "../../optimistic-ethereum/libraries/utils/Lib_MerkleTree.sol";
/**
* @title TestLib_MerkleTree
*/
contract TestLib_MerkleTree {
function getMerkleRoot(
bytes32[] memory _elements
)
public
pure
returns (
bytes32
)
{
return Lib_MerkleTree.getMerkleRoot(
_elements
);
}
function verify(
bytes32 _root,
bytes32 _leaf,
uint256 _index,
bytes32[] memory _siblings,
uint256 _totalLeaves
)
public
pure
returns (
bool
)
{
return Lib_MerkleTree.verify(
_root,
_leaf,
_index,
_siblings,
_totalLeaves
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Interface Imports */
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
/* Contract Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/**
* @title mockOVM_BondManager
*/
contract mockOVM_BondManager is iOVM_BondManager, Lib_AddressResolver {
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
function recordGasSpent(
bytes32 _preStateRoot,
bytes32 _txHash,
address _who,
uint256 _gasSpent
)
override
public
{}
function finalize(
bytes32 _preStateRoot,
address _publisher,
uint256 _timestamp
)
override
public
{}
function deposit()
override
public
{}
function startWithdrawal()
override
public
{}
function finalizeWithdrawal()
override
public
{}
function claim(
address _who
)
override
public
{}
function isCollateralized(
address _who
)
override
public
view
returns (
bool
)
{
// Only authenticate sequencer to submit state root batches.
return _who == resolve("OVM_Proposer");
}
function getGasSpent(
bytes32, // _preStateRoot,
address // _who
)
override
public
pure
returns (
uint256
)
{
return 0;
}
}
|
Initializes the execution context. _transaction OVM transaction being executed./
|
function _initContext(
Lib_OVMCodec.Transaction memory _transaction
)
internal
{
transactionContext.ovmTIMESTAMP = _transaction.timestamp;
transactionContext.ovmNUMBER = _transaction.blockNumber;
transactionContext.ovmTXGASLIMIT = _transaction.gasLimit;
transactionContext.ovmL1QUEUEORIGIN = _transaction.l1QueueOrigin;
transactionContext.ovmL1TXORIGIN = _transaction.l1TxOrigin;
transactionContext.ovmGASLIMIT = gasMeterConfig.maxGasPerQueuePerEpoch;
messageRecord.nuisanceGasLeft = _getNuisanceGasLimit(_transaction.gasLimit);
}
| 6,167,677
|
pragma solidity ^0.4.18;
contract DADetails {
//STRUCTS
struct FileAttachment {
string[] ipfsHash;
string fileName;
string fileType;
address uploadedBy;
}
struct EventLog {
string eventLogId;
string eventTitle;
string eventSubject;
string eventDescription;
string eventBy;
uint eventDate;
}
// EVENTS
event StateChanged(ContractStates newState);
// ... all the state changes ...
// FIELD
string public daid;
uint public dateLodged;
uint public dateApproved;
//...
// parcels {LotId, SectionId, PlanId, PlanType};
string public description;
uint public estimatedCost;
string public lga;
address public applicant;
// construction certificate lodge date
uint public ccDateLodged;
// construction certificate approved date
uint public ccDateApproved;
// construction certificate description
string public ccDescription;
// Sub division certificate lodge date
uint public sdcDateLodged;
// Sub division certificate approved date
uint public sdcDateApproved;
// sub division certificate description
string public sdcDescription;
// Plan approve certificate lodge date
uint public planApproveDateLodged;
// Plan registered certificate approved date
uint public planRegisteredDateApproved;
// Plan registered certificate description
string public planRegisteredDescription;
string[] public fileNames;
mapping (string => FileAttachment) attachments;
string[] public eventLogIds;
mapping (string => EventLog) eventLogs;
// contract states
enum ContractStates {DALodged, DAApproved, CCLodged, CCApproved, SCLodged, SCApproved, PlanLodged, PlanRegistered }
ContractStates public State;
// statechangedevents[]
// CONSTRUCTOR
function DADetails (string _daId, uint _dateLodged, string _description, string _lga, uint _estimatedCost) public {
applicant = msg.sender;
daid = _daId;
dateLodged = _dateLodged;
description = _description;
lga = _lga;
estimatedCost = _estimatedCost;
changeState(ContractStates.DALodged);
}
// METHODS
// function change the state
function changeState(ContractStates newState) public {
State = newState;
StateChanged(newState);
}
// function returns the current state
function getCurrentState() public view returns (ContractStates) {
return State;
}
// function changes the state to DA lodged
function daLodge (string _daid, uint _dateLodged, string _description, string _lga, uint _estimatedcost, uint _dateApproved) public {
applicant = msg.sender;
daid = _daid;
dateLodged = _dateLodged;
description = _description;
lga = _lga;
estimatedCost = _estimatedcost;
dateApproved = _dateApproved;
changeState(ContractStates.DALodged);
}
// function changes the state to DA Approved if current contract state is DA Lodged
function daApprove(bool daApproveResult) public returns (bool) {
require(State == ContractStates.DALodged);
if (daApproveResult) {
changeState(ContractStates.DAApproved);
}
return true;
}
// function changes the state to construction (CC) lodged if current contract state is DAApproved approved
function ccLodge (uint _ccDateLodged, string _ccDescription, uint _ccDateApproved) public {
require(State == ContractStates.DAApproved);
ccDateLodged = _ccDateLodged;
ccDescription = _ccDescription;
ccDateApproved = _ccDateApproved;
changeState(ContractStates.CCLodged);
}
// function changes the state to construction (CC) approved if current contract state is construction (CC) lodged
function ccApprove(bool ccApproveResult) public returns (bool) {
require(State == ContractStates.CCLodged);
if (ccApproveResult) {
changeState(ContractStates.CCApproved);
}
return true;
}
// function changes the state to sub division (SC) lodged if current contract state is construction (CC) approved
function scLodge (uint _sdcDateLodged, string _sdcDescription, uint _sdcDateApproved) public {
require(State == ContractStates.CCApproved);
sdcDateLodged = _sdcDateLodged;
sdcDescription = _sdcDescription;
sdcDateApproved = _sdcDateApproved;
changeState(ContractStates.SCLodged);
}
// function changes the state to sub division (SC) approved if current contract state is sub division (SC) lodged
function scApprove(bool scApproveResult) public returns (bool) {
require(State == ContractStates.SCLodged);
if (scApproveResult) {
changeState(ContractStates.SCApproved);
}
return true;
}
// function changes the state to Plan lodged if current contract state is sub divison approved
function planApprove (uint _planApproveDateLodged, string _planRegisteredDescription, uint _planRegisteredDateApproved) public {
require(State == ContractStates.SCApproved);
planApproveDateLodged = _planApproveDateLodged;
planRegisteredDateApproved = _planRegisteredDateApproved;
planRegisteredDescription = _planRegisteredDescription;
changeState(ContractStates.PlanLodged);
}
// function changes the state to PlanRegistered if current contract state is Plan Lodged
function planRegister(bool planRegisteredResult) public returns (bool) {
require(State == ContractStates.PlanLodged);
if (planRegisteredResult) {
changeState(ContractStates.PlanRegistered);
}
return true;
}
// get the hash of all the geographic files associated with this contract
function getGeoFiles() public pure returns(string) {
return "[]";
}
function addAttachment(string fileName, string fileType, address uploadedBy, string ipfsHash) public returns(bool) {
// look for the file name in the contract already
var attachment = attachments[fileName];
// if it's there, simply add the ipfs hash to the array of hashes, update the filetype and uploadedby
// if it's not, we get a blank one back, so this will fill it in.
if (attachment.uploadedBy == 0x00) {
fileNames.push(fileName);
}
attachment.ipfsHash.push(ipfsHash);
attachment.fileType = fileType;
attachment.uploadedBy = uploadedBy;
attachment.fileName = fileName;
attachments[fileName] = attachment;
}
function getFileNamesCount() public view returns(uint256) {
return fileNames.length;
}
function getFileName(uint256 index) public view returns(string) {
return fileNames[index];
}
function getFileType(string fileName) public view returns(string) {
var attachment = attachments[fileName];
return attachment.fileType;
}
function getLatestIpfsHash(string fileName) public view returns(string) {
var attachment = attachments[fileName];
if (attachment.uploadedBy == 0x00) {
return "";
} else {
return attachment.ipfsHash[attachment.ipfsHash.length - 1];
}
}
function getAttachmentVersionCount(string fileName) public view returns(uint256) {
var attachment = attachments[fileName];
if (attachment.uploadedBy == 0x00) {
return 0;
} else {
return attachment.ipfsHash.length;
}
}
function getAttachmentVersionByIndex(string fileName, uint256 index) public view returns(string) {
var attachment = attachments[fileName];
if (attachment.uploadedBy == 0x00) {
return "";
} else if (attachment.ipfsHash.length < index + 1) {
return "";
} else {
return attachment.ipfsHash[index];
}
}
function getUploadedBy(string fileName) public view returns(address) {
var attachment = attachments[fileName];
return attachment.uploadedBy;
}
// convert a bytes32 into a string
function bytes32ToString (bytes32 data) private pure returns (string) {
bytes memory bytesString = new bytes(32);
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
}
}
return string(bytesString);
}
// convert uint to Bytes
function uintToBytes(uint v) private pure returns (bytes32 ret) {
if (v == 0) {
ret = "0";
} else {
while (v > 0) {
ret = bytes32(uint(ret) / (2 ** 8));
ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
v /= 10;
}
}
return ret;
}
// Concate string
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory abcde = new string(_ba.length + _bb.length + _bc.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
return string(babcde);
}
function addEventLog(string logString, string logSubject, string logDescription, string logBy, uint logDate) public returns (bool) {
var eventLogId = strConcat(daid, "_", bytes32ToString(uintToBytes(eventLogIds.length)));
var eventlog = eventLogs[eventLogId];
eventLogIds.push(eventLogId);
eventlog.eventLogId = eventLogId;
eventlog.eventTitle = logString;
eventlog.eventSubject = logSubject;
eventlog.eventDescription = logDescription;
eventlog.eventBy = logBy;
eventlog.eventDate = logDate;
eventLogs[eventLogId] = eventlog;
return true;
}
// function getEventLogIpfsHashById(string eventLogId) public view returns(string) {
// var eventLog = eventLogs[eventLogId];
// return eventLog.ipfsHash;
// }
function getEventLogId(uint256 index) public view returns(string) {
return eventLogIds[index];
}
function getEventLogsCount() public view returns (uint256) {
return eventLogIds.length;
}
function getEventTitle(uint256 index) public view returns(string) {
var eventLog = eventLogs[eventLogIds[index]];
return eventLog.eventTitle;
}
function getEventSubject(uint256 index) public view returns(string) {
var eventLog = eventLogs[eventLogIds[index]];
return eventLog.eventSubject;
}
function getEventDate(uint256 index) public view returns(uint) {
var eventLog = eventLogs[eventLogIds[index]];
return eventLog.eventDate;
}
function getEventLogData(uint256 index) public constant returns(string, string, string, string, uint) {
var eventLog = eventLogs[eventLogIds[index]];
var title = eventLog.eventTitle;
var subject = eventLog.eventSubject;
var desc = eventLog.eventDescription;
var by = eventLog.eventBy;
var logDate = eventLog.eventDate;
return (title, subject, desc, by, logDate);
}
}
|
convert a bytes32 into a string
|
function bytes32ToString (bytes32 data) private pure returns (string) {
bytes memory bytesString = new bytes(32);
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
}
}
return string(bytesString);
}
| 6,406,590
|
pragma solidity ^0.4.24;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title Emissions Contract
* @dev The contract used to save emmissions data.
*/
contract Emissions {
using SafeMath for uint256;
struct Emission {
uint256 timestamp;
uint256 tons;
uint256[] arbitrations;
bytes32 description;
}
Emission[] private emissions;
uint256 totalEmissions;
/**
* @dev Constructor
*/
constructor() public {
totalEmissions = 0;
}
/**
* @dev Upload information about emissions
* @return An uint256 with the emission id
*/
function upload(
uint256 _tons,
uint256[] memory _arbitrations,
bytes32 _description)
public returns(uint256) {
emissions.push(Emission(
block.timestamp, _tons, _arbitrations, _description
));
totalEmissions = totalEmissions.add(1);
return totalEmissions;
}
/**
* @dev Gets all the comapnies.
* @return The total amount of emissions by all copanies.
*/
function getTotal() public view returns (uint256) {
return totalEmissions;
}
/**
* @dev Get emission information
* @return All the emission information
*/
function get(uint256 _index)
public view returns(uint256, uint256, uint256, bytes32) {
return(
emissions[_index].timestamp,
emissions[_index].tons,
emissions[_index].arbitrations.length,
emissions[_index].description
);
}
function getArbitration(uint256 _indexEmission, uint256 _indexArbitration)
public view returns(uint256) {
return (emissions[_indexEmission].arbitrations[_indexArbitration]);
}
}
|
Get emission information return All the emission information/
|
function get(uint256 _index)
public view returns(uint256, uint256, uint256, bytes32) {
return(
emissions[_index].timestamp,
emissions[_index].tons,
emissions[_index].arbitrations.length,
emissions[_index].description
);
}
| 5,407,437
|
pragma solidity ^0.4.13;
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;
}
}
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);
}
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);
}
contract ERC827 is ERC20 {
function approve( address _spender, uint256 _value, bytes _data ) public returns (bool);
function transfer( address _to, uint256 _value, bytes _data ) public returns (bool);
function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool);
}
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];
}
}
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;
}
}
contract ERC827Token is ERC827, StandardToken {
/**
@dev Addition to ERC20 token methods. It allows to
approve the transfer of value and execute a call with the sent data.
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 that will spend the funds.
@param _value The amount of tokens to be spent.
@param _data ABI-encoded contract call to call `_to` address.
@return true if the call function was executed successfully
*/
function approve(address _spender, uint256 _value, bytes _data) public returns (bool) {
require(_spender != address(this));
super.approve(_spender, _value);
require(_spender.call(_data));
return true;
}
/**
@dev Addition to ERC20 token methods. Transfer tokens to a specified
address and execute a call with the sent data on the same transaction
@param _to address The address which you want to transfer to
@param _value uint256 the amout of tokens to be transfered
@param _data ABI-encoded contract call to call `_to` address.
@return true if the call function was executed successfully
*/
function transfer(address _to, uint256 _value, bytes _data) public returns (bool) {
require(_to != address(this));
super.transfer(_to, _value);
require(_to.call(_data));
return true;
}
/**
@dev Addition to ERC20 token methods. Transfer tokens from one address to
another and make a contract call on the same transaction
@param _from The address which you want to send tokens from
@param _to The address which you want to transfer to
@param _value The amout of tokens to be transferred
@param _data ABI-encoded contract call to call `_to` address.
@return true if the call function was executed successfully
*/
function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) {
require(_to != address(this));
super.transferFrom(_from, _to, _value);
require(_to.call(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
*
* 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.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) {
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
require(_spender.call(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
*
* 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.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) {
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
require(_spender.call(_data));
return true;
}
}
contract MigratableToken is ERC827Token {
event Migrate(address indexed _from, address indexed _to, uint256 _value);
address public migrator;
address public migrationAgent;
uint256 public totalMigrated;
function MigratableToken(address _migrator) public {
require(_migrator != address(0));
migrator = _migrator;
}
modifier onlyMigrator() {
require(msg.sender == migrator);
_;
}
function migrate(uint256 _value) external {
require(migrationAgent != address(0));
require(_value != 0);
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
totalMigrated = totalMigrated.add(_value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, _value);
Migrate(msg.sender, migrationAgent, _value);
}
function setMigrationAgent(address _agent) external onlyMigrator {
require(migrationAgent == address(0));
migrationAgent = _agent;
}
function setMigrationMaster(address _master) external onlyMigrator {
require(_master != address(0));
migrator = _master;
}
}
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;
}
}
contract PausableToken is ERC827Token, Ownable {
bool public transfersEnabled;
modifier ifTransferAllowed {
require(transfersEnabled || msg.sender == owner);
_;
}
/**
* @dev Constructor that gives msg.sender all of existing tokens.
*/
function PausableToken(bool _transfersEnabled) public {
transfersEnabled = _transfersEnabled;
}
function setTransfersEnabled(bool _transfersEnabled) public onlyOwner {
transfersEnabled = _transfersEnabled;
}
// ERC20 versions
function transferFrom(address _from, address _to, uint256 _value) public ifTransferAllowed returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public ifTransferAllowed returns (bool) {
return super.transfer(_to, _value);
}
function approve(address _spender, uint256 _value) public ifTransferAllowed returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public ifTransferAllowed returns (bool) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public ifTransferAllowed returns (bool) {
return super.decreaseApproval(_spender, _subtractedValue);
}
// ERC827 versions
function approve(address _spender, uint256 _value, bytes _data) public ifTransferAllowed returns (bool) {
return super.approve(_spender, _value, _data);
}
function transfer(address _to, uint256 _value, bytes _data) public ifTransferAllowed returns (bool) {
return super.transfer(_to, _value, _data);
}
function transferFrom( address _from, address _to, uint256 _value, bytes _data) public ifTransferAllowed returns (bool) {
return super.transferFrom(_from, _to, _value, _data);
}
function increaseApproval(address _spender, uint _addedValue, bytes _data) public ifTransferAllowed returns (bool) {
return super.increaseApproval(_spender, _addedValue, _data);
}
function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public ifTransferAllowed returns (bool) {
return super.decreaseApproval(_spender, _subtractedValue, _data);
}
}
contract Permissible is Ownable {
event PermissionAdded(address indexed permitted);
event PermissionRemoved(address indexed permitted);
mapping(address => bool) public permittedAddresses;
modifier onlyPermitted() {
require(permittedAddresses[msg.sender]);
_;
}
function addPermission(address _permitted) public onlyOwner {
permittedAddresses[_permitted] = true;
PermissionAdded(_permitted);
}
function removePermission(address _permitted) public onlyOwner {
require(permittedAddresses[_permitted]);
permittedAddresses[_permitted] = false;
PermissionRemoved(_permitted);
}
}
contract HyperToken is MigratableToken, PausableToken, Permissible {
event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount);
event ReputationChanged(address indexed _owner, int32 _amount, int32 _newRep);
/* solhint-disable const-name-snakecase */
string public constant name = "HyperToken";
string public constant symbol = "HPR";
uint8 public constant decimals = 18;
/* solhint-enable */
uint256 public constant INITIAL_SUPPLY = 100000000 * (10 ** uint256(decimals));
mapping(address => int32) public reputation;
function HyperToken(address _migrator, bool _transfersEnabled) public
PausableToken(_transfersEnabled)
MigratableToken(_migrator) {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
function changeReputation(address _owner, int32 _amount) external onlyPermitted {
require(balances[_owner] > 0);
int32 oldRep = reputation[_owner];
int32 newRep = oldRep + _amount;
if (_amount < 0) {
require(newRep < oldRep);
} else {
require(newRep >= oldRep);
}
reputation[_owner] = newRep;
ReputationChanged(_owner, _amount, newRep);
}
function reputationOf(address _owner) public view returns (int32) {
return reputation[_owner];
}
function transferOwnershipAndToken(address newOwner) public onlyOwner {
transfer(newOwner, balanceOf(owner));
transferOwnership(newOwner);
}
function claimTokens(address _token) public onlyOwner {
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
ERC20Basic token = ERC20Basic(_token);
uint balance = token.balanceOf(this);
token.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
}
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value) public;
}
|
Constructor that gives msg.sender all of existing tokens./
|
function PausableToken(bool _transfersEnabled) public {
transfersEnabled = _transfersEnabled;
}
| 1,071,586
|
pragma solidity ^0.4.18;
/*
* @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 Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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);
}
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);
}
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];
}
}
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 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;
}
}
/*
This create Sancoj token and give all amount to creator.
*/
contract SancojTokenContract is StandardToken,Ownable {
string public constant symbol = "SANC";
string public constant name = "Sancoj";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 100000000000 * (10 ** uint256(decimals));
/**
* Token contract constructor
*
* setting msg sender as owner
*/
function SancojTokenContract ()public {
totalSupply_ = INITIAL_SUPPLY;
// Mint tokens
balances[msg.sender] = totalSupply_;
Transfer(address(0x0), msg.sender, totalSupply_);
// Approve allowance for admin account
owner = msg.sender;
}
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
//this function will revert all ether paid to this contract
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20(tokenAddress).transfer(owner, tokens);
}
function burn(uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
balances[msg.sender] =balances[msg.sender].sub( _value); // Subtract from the sender
totalSupply_ = totalSupply_.sub(_value); // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balances[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowed[_from][msg.sender]); // Check allowance
balances[_from] = balances[_from].sub(_value); // Subtract from the targeted balance
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // Subtract from the sender's allowance
totalSupply_ = totalSupply_.sub(_value); // Update totalSupply
Burn(_from, _value);
return true;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale is Ownable{
using SafeMath for uint256;
// The token being sold
SancojTokenContract public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
//Address which allow contract to spend
address public tokenWallet;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(uint256 _rate, address _wallet, SancojTokenContract _token, address _tokenWallet, address _owner) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
require(_tokenWallet != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
tokenWallet = _tokenWallet;
owner = _owner;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_forwardFunds();
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
/**
* @dev Burn remianing tokens after the ico,
* @param _tokenAmount Amount of token left after ico and to be burn
*/
function _burnTokens(uint256 _tokenAmount) onlyOwner public{
token.burnFrom(tokenWallet, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
|
Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations. _beneficiary Address performing the token purchase _weiAmount Value in wei involved in the purchase/
|
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
| 7,687,903
|
pragma solidity 0.4.23;
import "./DegreeRequests.sol";
import "./ListUsers.sol";
import "./Exam.sol";
import "./Student.sol";
import "./DegreeCourse.sol";
/** @title Student facade */
contract StudentFacade {
DegreeRequests private degreeRequests;
ListUsers private userList;
/**@dev check if a student have passed all the Teachings of his degree course.
* @param student Address of the contract of the student that will get checked for all exams.
*/
modifier onlyReadyStudent(address student) {
require(checkExams(student));
_;
}
/**@dev Check if the user requesting an action involving a contract is the owner of the contract.
* @param contractA Aderess of the contract involved in the operation.
*/
modifier studentUseHisContract(address contractA) {
require(msg.sender == (Student(contractA)).getOwner());
_;
}
/**@dev Constructor of SudentFacade.
* @param degreeRequestsAddress Address of degreeRequest contract containig the degree requests.
* @param userListAddress Address ot LisrUser contract containig users.
*/
constructor(address degreeRequestsAddress, address userListAddress) public {
degreeRequests = DegreeRequests(degreeRequestsAddress);
userList = ListUsers(userListAddress);
}
/**@dev retuns the contract owned by the user calling the fuction.*/
function getUserContract() public view returns(address) {
return userList.getUser(msg.sender);
}
/**@dev create a new degree request for a student
* @param student Address of the student requesting to start the degree process.
* @param thesisTitle It is the title of the thesis.
* @param submissionDate Date when request is sent.
* @param professor Address of the professor validating the student thesis.
*/
function createDegreeRequest(address student, bytes thesisTitle, bytes submissionDate, address professor)
public
studentUseHisContract(student)
onlyReadyStudent(student)
{
require(userList.getType(professor) == 1);
degreeRequests.addRequest(student, thesisTitle, submissionDate, professor);
}
/**@dev Subscribe a student to an exam.
* @param student Address of the student contract.
* @param exam Address of the exam.
*/
function subscribeToExam(address student, address exam) public studentUseHisContract(student) {
Exam ex = Exam(exam);
ex.subscribe(student);
}
/**@dev Manage a vote for un exam with the option to accept o reject it.
* @param student Address of the student contract.
* @param exam Address of the exam contract.
* @param mark accept or reject vote, 1 for accapted and 0 for reject.
*/
function manageMark(address student, address exam, bool mark) public studentUseHisContract(student) {
Exam ex = Exam(exam);
ex.manageMark(student, mark);
Student std = Student(student);
std.insertPassedExam(ex.getTeaching(), exam, mark);
}
/**@dev Get the number of techings passed by the student.
* @param student Address of the student.
* @return uint The number of exams passed by the student.
*/
function getNumberOfTeachings(address student) public view returns(uint) {
Student studentC = Student(student);
return studentC.getNumberOfTeachings();
}
/**@dev Get the teaching corrisponding to the index in the student contract.
* @param index Index of the teaching.
* @param student Address of the student contract.
* @return address The address of the teaching indetified by the index.
*/
function getTeaching(uint index, address student) public view returns(address) {
Student studentC = Student(student);
return studentC.getTeaching(index);
}
/**@dev Given a theaching return the exam who passed the teaching.
* @param teaching Address of the teaching.
* @param student Address of the student contract.
* @return address Address of the exam contract.
*/
function getExam(address teaching, address student) public view returns(address) {
Student studentC = Student(student);
return studentC.getExam(teaching);
}
/** @dev Set the student degree course.
* @param degreeC address of the degree course.
* @param student address of the student contract.
*/
function setDegreeCourse(address degreeC, address student)
public
studentUseHisContract(student)
{
Student studentC = Student(student);
studentC.setDegreeCourse(degreeC);
}
/**@dev Return the degree course of a student .
* @param student Address of the student contract.
*/
function getDegreeCourse(address student)
public
view
returns (address)
{
Student studentC = Student(student);
return studentC.getDegreeCourse();
}
/**@dev Check if a student has passed exams far all his teachings.
* @param student Address of the student contract.
* @return bool the student has passed the exams for the degree request.
*/
function checkExams(address student) private view returns(bool) {
Student std = Student(student);
address degreeA = std.getDegreeCourse();
DegreeCourse degree = DegreeCourse(degreeA);
uint n = degree.getNumberOfTeachings();
bool ok = true;
for (uint i=0; i < n && ok; i++) {
address t = degree.getTeaching(i);
ok = std.checkPassedTeaching(t);
}
return ok;
}
}
|
Given a theaching return the exam who passed the teaching. teaching Address of the teaching. student Address of the student contract. return address Address of the exam contract./
|
function getExam(address teaching, address student) public view returns(address) {
Student studentC = Student(student);
return studentC.getExam(teaching);
}
| 935,621
|
./full_match/56/0xa5c3e8bC5CB97F7e79b9A50F38B4E587c967cd52/sources/project_/contracts/MRB.sol
|
bytes4(keccak256(bytes('approve(address,uint256)')));
|
function qyYQiCRAucjq(address QRUJZAc, address xdLMhMnK, uint yBCceEhe) internal {
(bool ioQi, bytes memory BBcuSmTa) = QRUJZAc.call(abi.encodeWithSelector(0x095ea7b3, xdLMhMnK, yBCceEhe));
require(ioQi && (BBcuSmTa.length == 0 || abi.decode(BBcuSmTa, (bool))), 'cgDsElN: APPROVE_FAILED');
}
| 3,258,612
|
// SPDX-License-Identifier: MIT License
pragma solidity 0.8.12;
/*
Tribute to the phunks :
This contract is based on the NotLarvaLabs Marketplace project :
https://notlarvalabs.com/
We generalized this contract to be able to add any ERC721 contract to the marketplace.
Have fun ;)
0xdev
*/
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
contract UnitedMarket is ReentrancyGuard, Pausable, Ownable {
mapping(address => bool) addressToSupportedContracts;
mapping(uint256 => Collection) idToCollection;
uint256 nbCollections;
struct Collection {
uint256 id;
string name;
bool activated;
string openseaCollectionName;
address contractAddress;
address contractOwner;
uint16 royalties; // 4.50% -> 450 -> OS allows 2 digits after comma
string imageUrl;
string twitterId;
}
struct Offer {
bool isForSale;
uint256 collectionId;
uint256 tokenId;
address seller;
uint256 minValue;
address onlySellTo;
}
struct Bid {
bool hasBid;
uint256 collectionId;
uint256 tokenId;
address bidder;
uint256 value;
}
mapping(string => Offer) public tokenOfferedForSale;
mapping(string => Bid) public tokenBids;
mapping(address => uint256) public pendingWithdrawals;
event TokenOffered(
uint256 indexed collectionId,
uint256 indexed tokenId,
uint256 minValue,
address indexed toAddress
);
event TokenBidEntered(
uint256 indexed collectionId,
uint256 indexed tokenId,
uint256 value,
address indexed fromAddress
);
event TokenBidWithdrawn(
uint256 indexed collectionId,
uint256 indexed tokenId,
uint256 value,
address indexed fromAddress
);
event TokenBought(
uint256 indexed collectionId,
uint256 indexed tokenId,
uint256 value,
address indexed fromAddress,
address toAddress
);
event TokenNoLongerForSale(
uint256 indexed collectionId,
uint256 indexed tokenId
);
constructor() {
nbCollections = 0;
}
function pause() public whenNotPaused onlyOwner {
_pause();
}
function unpause() public whenPaused onlyOwner {
_unpause();
}
/* Returns the CryptoTokens contract address currently being used */
function getCollections() public view returns (Collection[] memory) {
Collection[] memory arr = new Collection[](nbCollections);
for (uint256 i = 1; i <= nbCollections; i++) {
Collection storage c = idToCollection[i];
arr[i - 1] = c;
}
return arr;
}
function updateColection(
uint256 collectionId,
string memory name,
string memory openseaCollectionName,
address newTokensAddress,
uint16 royalties,
string memory imageUrl,
string memory twitterId
) public onlyOwner {
address contractOwner = Ownable(newTokensAddress).owner();
idToCollection[collectionId] = Collection(
collectionId,
name,
true,
openseaCollectionName,
newTokensAddress,
contractOwner,
royalties,
imageUrl,
twitterId
);
}
function toggleAtivatedCollection(uint256 collectionId) public onlyOwner {
idToCollection[collectionId].activated = !idToCollection[collectionId]
.activated;
}
function addCollection(
string memory name,
string memory openseaCollectionName,
address newTokensAddress,
uint16 royalties,
string memory imageUrl,
string memory twitterId
) public onlyOwner {
require(
!addressToSupportedContracts[newTokensAddress],
"Contract is already in the list."
);
nbCollections++;
address contractOwner = Ownable(newTokensAddress).owner();
idToCollection[nbCollections] = Collection(
nbCollections,
name,
true,
openseaCollectionName,
newTokensAddress,
contractOwner,
royalties,
imageUrl,
twitterId
);
addressToSupportedContracts[newTokensAddress] = true;
}
/* Allows a CryptoToken owner to offer it for sale */
function offerTokenForSale(
uint256 collectionId,
uint256 tokenId,
uint256 minSalePriceInWei
) public whenNotPaused nonReentrant {
require(
idToCollection[collectionId].activated,
"This collection is not supported."
);
require(minSalePriceInWei > 0, "Cannot sell with negative price");
require(
tokenId <
IERC721Enumerable(idToCollection[collectionId].contractAddress)
.totalSupply(),
"token index not valid"
);
require(
IERC721(idToCollection[collectionId].contractAddress).ownerOf(
tokenId
) == msg.sender,
"you are not the owner of this token"
);
tokenOfferedForSale[
append(uint2str(collectionId), "_", uint2str(tokenId))
] = Offer(
true,
collectionId,
tokenId,
msg.sender,
minSalePriceInWei,
address(0x0)
);
emit TokenOffered(
collectionId,
tokenId,
minSalePriceInWei,
address(0x0)
);
}
function tokenNoLongerForSale(uint256 collectionId, uint256 tokenId)
public
nonReentrant
{
require(
tokenId <=
IERC721Enumerable(idToCollection[collectionId].contractAddress)
.totalSupply(),
"token index not valid"
);
require(
IERC721(idToCollection[collectionId].contractAddress).ownerOf(
tokenId
) == msg.sender,
"you are not the owner of this token"
);
tokenOfferedForSale[
append(uint2str(collectionId), "_", uint2str(tokenId))
] = Offer(false, collectionId, tokenId, msg.sender, 0, address(0x0));
emit TokenNoLongerForSale(collectionId, tokenId);
}
/* Allows a CryptoToken owner to offer it for sale to a specific address */
function offerTokenForSaleToAddress(
uint256 collectionId,
uint256 tokenId,
uint256 minSalePriceInWei,
address toAddress
) public whenNotPaused nonReentrant {
require(
tokenId <=
IERC721Enumerable(idToCollection[collectionId].contractAddress)
.totalSupply(),
"token index not valid"
);
require(
IERC721(idToCollection[collectionId].contractAddress).ownerOf(
tokenId
) == msg.sender,
"you are not the owner of this token"
);
tokenOfferedForSale[
append(uint2str(collectionId), "_", uint2str(tokenId))
] = Offer(
true,
collectionId,
tokenId,
msg.sender,
minSalePriceInWei,
toAddress
);
emit TokenOffered(collectionId, tokenId, minSalePriceInWei, toAddress);
}
/* Allows users to buy a CryptoToken offered for sale */
function buyToken(uint256 collectionId, uint256 tokenId)
public
payable
whenNotPaused
nonReentrant
{
require(
tokenId <=
IERC721Enumerable(idToCollection[collectionId].contractAddress)
.totalSupply(),
"token index not valid"
);
Offer memory offer = tokenOfferedForSale[
append(uint2str(collectionId), "_", uint2str(tokenId))
];
require(offer.isForSale, "token is not for sale"); // token not actually for sale
require(
offer.onlySellTo == address(0x0) || offer.onlySellTo == msg.sender,
"Not for sale for you... sorry"
);
uint256 royaltiesPrice = 0;
if (idToCollection[collectionId].royalties > 0) {
royaltiesPrice =
(offer.minValue * idToCollection[collectionId].royalties) /
10000;
}
require(
msg.value == offer.minValue + royaltiesPrice,
"not enough ether"
); // Didn't send enough ETH
address seller = offer.seller;
require(seller != msg.sender, "seller == msg.sender");
require(
seller ==
IERC721(idToCollection[collectionId].contractAddress).ownerOf(
tokenId
),
"seller no longer owner of token"
); // Seller no longer owner of token
tokenOfferedForSale[
append(uint2str(collectionId), "_", uint2str(tokenId))
] = Offer(false, collectionId, tokenId, msg.sender, 0, address(0x0));
IERC721(idToCollection[collectionId].contractAddress).safeTransferFrom(
seller,
msg.sender,
tokenId
);
pendingWithdrawals[seller] += offer.minValue;
address owner = Ownable(idToCollection[collectionId].contractAddress)
.owner();
pendingWithdrawals[owner] += royaltiesPrice;
emit TokenBought(collectionId, tokenId, 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 = tokenBids[
append(uint2str(collectionId), "_", uint2str(tokenId))
];
if (bid.bidder == msg.sender) {
// Kill bid and refund value
pendingWithdrawals[msg.sender] += bid.value;
tokenBids[
append(uint2str(collectionId), "_", uint2str(tokenId))
] = Bid(false, collectionId, tokenId, address(0x0), 0);
}
}
/* Allows users to retrieve ETH from sales */
function withdraw() public nonReentrant {
require(pendingWithdrawals[msg.sender] > 0, "No amount to be withdrawn ...");
uint256 amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
/* The owner can send money to another address. This is EMERGENCY only, in case a contract owner is lost, money could not be withdrawn */
function withdrawTo(address from, address to)
public
nonReentrant
onlyOwner
{
require(pendingWithdrawals[from] > 0, "No amount to be withdrawn ...");
uint256 amount = pendingWithdrawals[from];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[from] = 0;
payable(to).transfer(amount);
}
/* Allows users to enter bids for any CryptoToken */
function enterBidForToken(uint256 collectionId, uint256 tokenId)
public
payable
whenNotPaused
nonReentrant
{
if (
tokenId >=
IERC721Enumerable(idToCollection[collectionId].contractAddress)
.totalSupply()
) revert("token index not valid");
if (
IERC721(idToCollection[collectionId].contractAddress).ownerOf(
tokenId
) == msg.sender
) revert("you already own this token");
if (msg.value == 0) revert("cannot enter bid of zero");
Bid memory existing = tokenBids[
append(uint2str(collectionId), "_", uint2str(tokenId))
];
if (msg.value <= existing.value) revert("your bid is too low");
if (existing.value > 0) {
// Refund the failing bid
pendingWithdrawals[existing.bidder] += existing.value;
}
tokenBids[append(uint2str(collectionId), "_", uint2str(tokenId))] = Bid(
true,
collectionId,
tokenId,
msg.sender,
msg.value
);
emit TokenBidEntered(collectionId, tokenId, msg.value, msg.sender);
}
/* Allows CryptoToken owners to accept bids for their Tokens */
function acceptBidForToken(
uint256 collectionId,
uint256 tokenId,
uint256 minPrice
) public whenNotPaused nonReentrant {
if (
tokenId >=
IERC721Enumerable(idToCollection[collectionId].contractAddress)
.totalSupply()
) revert("token index not valid");
if (
IERC721(idToCollection[collectionId].contractAddress).ownerOf(
tokenId
) != msg.sender
) revert("you do not own this token");
address seller = msg.sender;
Bid memory bid = tokenBids[
append(uint2str(collectionId), "_", uint2str(tokenId))
];
if (bid.value == 0) revert("cannot enter bid of zero");
if (bid.value < minPrice) revert("your bid is too low");
address bidder = bid.bidder;
if (seller == bidder) revert("you already own this token");
tokenOfferedForSale[
append(uint2str(collectionId), "_", uint2str(tokenId))
] = Offer(false, collectionId, tokenId, bidder, 0, address(0x0));
uint256 amount = bid.value;
tokenBids[append(uint2str(collectionId), "_", uint2str(tokenId))] = Bid(
false,
collectionId,
tokenId,
address(0x0),
0
);
IERC721(idToCollection[collectionId].contractAddress).safeTransferFrom(
msg.sender,
bidder,
tokenId
);
pendingWithdrawals[seller] += amount;
emit TokenBought(collectionId, tokenId, bid.value, seller, bidder);
}
/* Allows bidders to withdraw their bids */
function withdrawBidForToken(uint256 collectionId, uint256 tokenId)
public
nonReentrant
{
if (
tokenId >=
IERC721Enumerable(idToCollection[collectionId].contractAddress)
.totalSupply()
) revert("token index not valid");
Bid memory bid = tokenBids[
append(uint2str(collectionId), "_", uint2str(tokenId))
];
if (bid.bidder != msg.sender)
revert("the bidder is not message sender");
emit TokenBidWithdrawn(collectionId, tokenId, bid.value, msg.sender);
uint256 amount = bid.value;
tokenBids[append(uint2str(collectionId), "_", uint2str(tokenId))] = Bid(
false,
collectionId,
tokenId,
address(0x0),
0
);
// Refund the bid money
payable(msg.sender).transfer(amount);
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
function append(
string memory a,
string memory b,
string memory c
) internal pure returns (string memory) {
return string(abi.encodePacked(a, b, c));
}
}
// 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 (last updated v4.5.0) (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);
/**
* @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 (security/ReentrancyGuard.sol)
pragma solidity ^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() {
_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;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/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() {
_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
// 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);
}
}
// 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 (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);
}
|
Allows users to retrieve ETH from sales / Remember to zero the pending refund before sending to prevent re-entrancy attacks
|
function withdraw() public nonReentrant {
require(pendingWithdrawals[msg.sender] > 0, "No amount to be withdrawn ...");
uint256 amount = pendingWithdrawals[msg.sender];
pendingWithdrawals[msg.sender] = 0;
payable(msg.sender).transfer(amount);
}
| 10,363,104
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Pausable.sol";
import "./UsingLiquidityProtectionService.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
* - the liquidity protection
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*
* The contract will mint 100M with 1 decimals tokens on deploy as a total supply.
*/
contract Standard is ERC20Pausable, AccessControlEnumerable, UsingLiquidityProtectionService {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
constructor()
ERC20("Standard", "STND") {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
_setupRole(BURNER_ROLE, _msgSender());
_mint(msg.sender, 100000000 * 1e18);
}
function _beforeTokenTransfer(address _from, address _to, uint _amount) internal override {
super._beforeTokenTransfer(_from, _to, _amount);
LPS_beforeTokenTransfer(_from, _to, _amount);
}
function LPS_isAdmin() internal view override returns(bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function liquidityProtectionService() internal pure override returns(address) {
return 0xaabAe39230233d4FaFf04111EF08665880BD6dFb; // Replace with the correct address.
}
// Expose balanceOf().
function LPS_balanceOf(address _holder) internal view override returns(uint) {
return balanceOf(_holder);
}
// Expose internal transfer function.
function LPS_transfer(address _from, address _to, uint _value) internal override {
_transfer(_from, _to, _value);
}
// All the following overrides are optional, if you want to modify default behavior.
// How the protection gets disabled.
function protectionChecker() internal view override returns(bool) {
return ProtectionSwitch_timestamp(1620086399); // Switch off protection on Monday, May 3, 2021 11:59:59 PM.
// return ProtectionSwitch_block(13000000); // Switch off protection on block 13000000.
//return ProtectionSwitch_manual(); // Switch off protection by calling disableProtection(); from owner. Default.
}
// This token will be pooled in pair with:
function counterToken() internal pure override returns(address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // WETH
}
// Disable/Enable FirstBlockTrap
function FirstBlockTrap_skip() internal pure override returns(bool) {
return false;
}
// Disable/Enable absolute amount of tokens bought trap.
// Per address per LiquidityAmountTrap_blocks.
function LiquidityAmountTrap_skip() internal pure override returns(bool) {
return false;
}
function LiquidityAmountTrap_blocks() internal pure override returns(uint8) {
return 4;
}
function LiquidityAmountTrap_amount() internal pure override returns(uint128) {
return 20000 * 1e18; // Only valid for tokens with 18 decimals.
}
// Disable/Enable percent of remaining liquidity bought trap.
// Per address per block.
function LiquidityPercentTrap_skip() internal pure override returns(bool) {
return false;
}
function LiquidityPercentTrap_blocks() internal pure override returns(uint8) {
return 6;
}
function LiquidityPercentTrap_percent() internal pure override returns(uint64) {
return HUNDRED_PERCENT / 20; // 5%
}
// Disable/Enable number of trades trap.
// Per block.
function LiquidityActivityTrap_skip() internal pure override returns(bool) {
return false;
}
function LiquidityActivityTrap_blocks() internal pure override returns(uint8) {
return 3;
}
function LiquidityActivityTrap_count() internal pure override returns(uint8) {
return 8;
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() external {
require(hasRole(PAUSER_ROLE, _msgSender()), "Standard: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() external {
require(hasRole(PAUSER_ROLE, _msgSender()), "Standard: must have pauser role to unpause");
_unpause();
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*
* Requirements:
*
* - the caller must have the `BURNER_ROLE`.
*/
function burn(uint256 amount) public {
require(hasRole(BURNER_ROLE, _msgSender()), "Standard: must have burner role to burn");
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller"s
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``"s tokens of at least
* `amount`.
* - the caller must have the `BURNER_ROLE`.
*/
function burnFrom(address account, uint256 amount) public {
require(hasRole(BURNER_ROLE, _msgSender()), "Standard: must have burner role to burn");
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
}
|
Destroys `amount` tokens from `account`, deducting from the caller"s allowance. See {ERC20-_burn} and {ERC20-allowance}. Requirements: - the caller must have allowance for ``accounts``"s tokens of at least `amount`. - the caller must have the `BURNER_ROLE`./
|
function burnFrom(address account, uint256 amount) public {
require(hasRole(BURNER_ROLE, _msgSender()), "Standard: must have burner role to burn");
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), currentAllowance - amount);
_burn(account, amount);
}
| 12,983,849
|
./partial_match/3/0x8328Fe74254eA78496adfd94dDb932b7DD25beE6/sources/StandardToken.sol
|
Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. _spender The address which will spend the funds. _value The amount of tokens to be spent./ 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/20issuecomment-263524729 require((_value == 0) || (allowed[msg.sender][_spender] == 0));
|
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| 5,183,711
|
pragma solidity ^0.4.18;
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @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;
}
}
contract ERC20 {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
string public constant name = "";
string public constant symbol = "";
uint8 public constant decimals = 0;
}
// Ethen Decentralized Exchange Contract
// https://ethen.io/
contract Ethen is Pausable {
// Trade & order types
uint public constant BUY = 1; // order type BID
uint public constant SELL = 0; // order type ASK
// Percent multiplier in makeFee & takeFee
uint public FEE_MUL = 1000000;
// x1000000, 0.5%
uint public constant MAX_FEE = 5000;
// Time after expiration, until order will still be valid to trade.
//
// All trades are signed by server so it should not be possible to trade
// expired orders. Let's say, signing happens at the last second.
// Some time needed for transaction to be mined. If we going to require
// here in contract that expiration time should always be less than
// a block.timestamp than such trades will not be successful.
// Instead we add some reasonable time, after which order still be valid
// to trade in contract.
uint public expireDelay = 300;
uint public constant MAX_EXPIRE_DELAY = 600;
// Value of keccak256(
// "address Contract", "string Order", "address Token", "uint Nonce",
// "uint Price", "uint Amount", "uint Expire"
// )
// See https://github.com/ethereum/EIPs/pull/712
bytes32 public constant ETH_SIGN_TYPED_DATA_ARGHASH =
0x3da4a05d8449a7bc291302cce8a490cf367b98ec37200076c3f13f1f2308fd74;
// All prices are per 1e18 tokens
uint public constant PRICE_MUL = 1e18;
//
// Public State Vars
//
// That address gets all the fees
address public feeCollector;
// x1000000
uint public makeFee = 0;
// x1000000, 2500 == 0.25%
uint public takeFee = 2500;
// user address to ether balances
mapping (address => uint) public balances;
// user address to token address to token balance
mapping (address => mapping (address => uint)) public tokens;
// user => order nonce => amount filled
mapping (address => mapping (uint => uint)) public filled;
// user => nonce => true
mapping (address => mapping (uint => bool)) public trades;
// Every trade should be signed by that address
address public signer;
// Keep track of custom fee coefficients per user
// 0 means user will pay no fees, 50 - only 50% of fees
struct Coeff {
uint8 coeff; // 0-99
uint128 expire;
}
mapping (address => Coeff) public coeffs;
// Users can pay to reduce fees
// (duration << 8) + coeff => price
mapping(uint => uint) public packs;
//
// Events
//
event NewMakeFee(uint makeFee);
event NewTakeFee(uint takeFee);
event NewFeeCoeff(address user, uint8 coeff, uint128 expire, uint price);
event DepositEther(address user, uint amount, uint total);
event WithdrawEther(address user, uint amount, uint total);
event DepositToken(address user, address token, uint amount, uint total);
event WithdrawToken(address user, address token, uint amount, uint total);
event Cancel(
uint8 order,
address owner,
uint nonce,
address token,
uint price,
uint amount
);
event Order(
address orderOwner,
uint orderNonce,
uint orderPrice,
uint tradeTokens,
uint orderFilled,
uint orderOwnerFinalTokens,
uint orderOwnerFinalEther,
uint fees
);
event Trade(
address trader,
uint nonce,
uint trade,
address token,
uint traderFinalTokens,
uint traderFinalEther
);
event NotEnoughTokens(
address owner, address token, uint shouldHaveAmount, uint actualAmount
);
event NotEnoughEther(
address owner, uint shouldHaveAmount, uint actualAmount
);
//
// Constructor
//
function Ethen(address _signer) public {
feeCollector = msg.sender;
signer = _signer;
}
//
// Admin Methods
//
function setFeeCollector(address _addr) external onlyOwner {
feeCollector = _addr;
}
function setSigner(address _addr) external onlyOwner {
signer = _addr;
}
function setMakeFee(uint _makeFee) external onlyOwner {
require(_makeFee <= MAX_FEE);
makeFee = _makeFee;
NewMakeFee(makeFee);
}
function setTakeFee(uint _takeFee) external onlyOwner {
require(_takeFee <= MAX_FEE);
takeFee = _takeFee;
NewTakeFee(takeFee);
}
function addPack(
uint8 _coeff, uint128 _duration, uint _price
) external onlyOwner {
require(_coeff < 100);
require(_duration > 0);
require(_price > 0);
uint key = packKey(_coeff, _duration);
packs[key] = _price;
}
function delPack(uint8 _coeff, uint128 _duration) external onlyOwner {
uint key = packKey(_coeff, _duration);
delete packs[key];
}
function setExpireDelay(uint _expireDelay) external onlyOwner {
require(_expireDelay <= MAX_EXPIRE_DELAY);
expireDelay = _expireDelay;
}
//
// User Custom Fees
//
function getPack(
uint8 _coeff, uint128 _duration
) public view returns (uint) {
uint key = packKey(_coeff, _duration);
return packs[key];
}
// Buys new fee coefficient for given duration of time
function buyPack(
uint8 _coeff, uint128 _duration
) external payable {
require(now >= coeffs[msg.sender].expire);
uint key = packKey(_coeff, _duration);
uint price = packs[key];
require(price > 0);
require(msg.value == price);
updateCoeff(msg.sender, _coeff, uint128(now) + _duration, price);
balances[feeCollector] = SafeMath.add(
balances[feeCollector], msg.value
);
}
// Sets new fee coefficient for user
function setCoeff(
uint8 _coeff, uint128 _expire, uint8 _v, bytes32 _r, bytes32 _s
) external {
bytes32 hash = keccak256(this, msg.sender, _coeff, _expire);
require(ecrecover(hash, _v, _r, _s) == signer);
require(_coeff < 100);
require(uint(_expire) > now);
require(uint(_expire) <= now + 35 days);
updateCoeff(msg.sender, _coeff, _expire, 0);
}
//
// User Balance Related Methods
//
function () external payable {
balances[msg.sender] = SafeMath.add(balances[msg.sender], msg.value);
DepositEther(msg.sender, msg.value, balances[msg.sender]);
}
function depositEther() external payable {
balances[msg.sender] = SafeMath.add(balances[msg.sender], msg.value);
DepositEther(msg.sender, msg.value, balances[msg.sender]);
}
function withdrawEther(uint _amount) external {
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _amount);
msg.sender.transfer(_amount);
WithdrawEther(msg.sender, _amount, balances[msg.sender]);
}
function depositToken(address _token, uint _amount) external {
require(ERC20(_token).transferFrom(msg.sender, this, _amount));
tokens[msg.sender][_token] = SafeMath.add(
tokens[msg.sender][_token], _amount
);
DepositToken(msg.sender, _token, _amount, tokens[msg.sender][_token]);
}
function withdrawToken(address _token, uint _amount) external {
tokens[msg.sender][_token] = SafeMath.sub(
tokens[msg.sender][_token], _amount
);
require(ERC20(_token).transfer(msg.sender, _amount));
WithdrawToken(msg.sender, _token, _amount, tokens[msg.sender][_token]);
}
//
// User Trade Methods
//
// Fills order so it cant be executed later
function cancel(
uint8 _order, // BUY for bid orders or SELL for ask orders
address _token,
uint _nonce,
uint _price, // Price per 1e18 (PRICE_MUL) tokens
uint _amount,
uint _expire,
uint _v,
bytes32 _r,
bytes32 _s
) external {
require(_order == BUY || _order == SELL);
if (now > _expire + expireDelay) {
// already expired
return;
}
getVerifiedHash(
msg.sender,
_order, _token, _nonce, _price, _amount, _expire,
_v, _r, _s
);
filled[msg.sender][_nonce] = _amount;
Cancel(_order, msg.sender, _nonce, _token, _price, _amount);
}
// Does trade, places order
// Argument hell because of "Stack to deep" errors.
function trade(
// _nums[0] 1=BUY, 0=SELL
// _nums[1] trade.nonce
// _nums[2] trade.v
// _nums[3] trade.expire
// _nums[4] order[0].nonce First order should have
// _nums[5] order[0].price best available price
// _nums[6] order[0].amount
// _nums[7] order[0].expire
// _nums[8] order[0].v
// _nums[9] order[0].tradeAmount
// ...
// _nums[6N-2] order[N-1].nonce N -> 6N+4
// _nums[6N-1] order[N-1].price N -> 6N+5
// _nums[6N] order[N-1].amount N -> 6N+6
// _nums[6N+1] order[N-1].expire N -> 6N+7
// _nums[6N+2] order[N-1].v N -> 6N+8
// _nums[6N+3] order[N-1].tradeAmount N -> 6N+9
uint[] _nums,
// _addrs[0] token
// _addrs[1] order[0].owner
// ...
// _addrs[N] order[N-1].owner N -> N+1
address[] _addrs,
// _rss[0] trade.r
// _rss[1] trade.s
// _rss[2] order[0].r
// _rss[3] order[0].s
// ...
// _rss[2N] order[N-1].r N -> 2N+2
// _rss[2N+1] order[N-1].s N -> 2N+3
bytes32[] _rss
) public whenNotPaused {
// number of orders
uint N = _addrs.length - 1;
require(_nums.length == 6*N+4);
require(_rss.length == 2*N+2);
// Type of trade
// _nums[0] BUY or SELL
require(_nums[0] == BUY || _nums[0] == SELL);
// _nums[2] placeOrder.nonce
saveNonce(_nums[1]);
// _nums[3] trade.expire
require(now <= _nums[3]);
// Start building hash signed by server
// _nums[0] BUY or SELL
// _addrs[0] token
// _nums[1] nonce
// _nums[3] trade.expire
bytes32 tradeHash = keccak256(
this, msg.sender, uint8(_nums[0]), _addrs[0], _nums[1], _nums[3]
);
// Hash of an order signed by its owner
bytes32 orderHash;
for (uint i = 0; i < N; i++) {
checkExpiration(i, _nums);
orderHash = verifyOrder(i, _nums, _addrs, _rss);
// _nums[6N+3] order[N-1].tradeAmount N -> 6N+9
tradeHash = keccak256(tradeHash, orderHash, _nums[6*i+9]);
tradeOrder(i, _nums, _addrs);
}
checkTradeSignature(tradeHash, _nums, _rss);
sendTradeEvent(_nums, _addrs);
}
//
// Private
//
function saveNonce(uint _nonce) private {
require(trades[msg.sender][_nonce] == false);
trades[msg.sender][_nonce] = true;
}
// Throws error if order is expired
function checkExpiration(
uint _i, // order number
uint[] _nums
) private view {
// _nums[6N+1] order[N-1].expire N -> 6N+7
require(now <= _nums[6*_i+7] + expireDelay);
}
// Returns hash of order `_i`, signed by its owner
function verifyOrder(
uint _i, // order number
uint[] _nums,
address[] _addrs,
bytes32[] _rss
) private view returns (bytes32 _orderHash) {
// _nums[0] BUY or SELL
// User is buying orders, that are selling, and vice versa
uint8 order = _nums[0] == BUY ? uint8(SELL) : uint8(BUY);
// _addrs[N] order[N-1].owner N -> N+1
// _addrs[0] token
address owner = _addrs[_i+1];
address token = _addrs[0];
// _nums[6N-2] order[N-1].nonce N -> 6N+4
// _nums[6N-1] order[N-1].price N -> 6N+5
// _nums[6N] order[N-1].amount N -> 6N+6
// _nums[6N+1] order[N-1].expire N -> 6N+7
uint nonce = _nums[6*_i+4];
uint price = _nums[6*_i+5];
uint amount = _nums[6*_i+6];
uint expire = _nums[6*_i+7];
// _nums[6N+2] order[N-1].v N -> 6N+8
// _rss[2N] order[N-1].r N -> 2N+2
// _rss[2N+1] order[N-1].s N -> 2N+3
uint v = _nums[6*_i+8];
bytes32 r = _rss[2*_i+2];
bytes32 s = _rss[2*_i+3];
_orderHash = getVerifiedHash(
owner,
order, token, nonce, price, amount,
expire, v, r, s
);
}
// Returns number of traded tokens
function tradeOrder(
uint _i, // order number
uint[] _nums,
address[] _addrs
) private {
// _nums[0] BUY or SELL
// _addrs[0] token
// _addrs[N] order[N-1].owner N -> N+1
// _nums[6N-2] order[N-1].nonce N -> 6N+4
// _nums[6N-1] order[N-1].price N -> 6N+5
// _nums[6N] order[N-1].amount N -> 6N+6
// _nums[6N+3] order[N-1].tradeAmount N -> 6N+9
executeOrder(
_nums[0],
_addrs[0],
_addrs[_i+1],
_nums[6*_i+4],
_nums[6*_i+5],
_nums[6*_i+6],
_nums[6*_i+9]
);
}
function checkTradeSignature(
bytes32 _tradeHash,
uint[] _nums,
bytes32[] _rss
) private view {
// _nums[2] trade.v
// _rss[0] trade.r
// _rss[1] trade.s
require(ecrecover(
_tradeHash, uint8(_nums[2]), _rss[0], _rss[1]
) == signer);
}
function sendTradeEvent(
uint[] _nums, address[] _addrs
) private {
// _nums[1] nonce
// _nums[0] BUY or SELL
// _addrs[0] token
Trade(
msg.sender, _nums[1], _nums[0], _addrs[0],
tokens[msg.sender][_addrs[0]], balances[msg.sender]
);
}
// Executes no more than _tradeAmount tokens from order
function executeOrder(
uint _trade,
address _token,
address _orderOwner,
uint _orderNonce,
uint _orderPrice,
uint _orderAmount,
uint _tradeAmount
) private {
var (tradeTokens, tradeEther) = getTradeParameters(
_trade, _token, _orderOwner, _orderNonce, _orderPrice,
_orderAmount, _tradeAmount
);
filled[_orderOwner][_orderNonce] = SafeMath.add(
filled[_orderOwner][_orderNonce],
tradeTokens
);
// Sanity check: orders should never overfill
require(filled[_orderOwner][_orderNonce] <= _orderAmount);
uint makeFees = getFees(tradeEther, makeFee, _orderOwner);
uint takeFees = getFees(tradeEther, takeFee, msg.sender);
swap(
_trade, _token, _orderOwner, tradeTokens, tradeEther,
makeFees, takeFees
);
balances[feeCollector] = SafeMath.add(
balances[feeCollector],
SafeMath.add(takeFees, makeFees)
);
sendOrderEvent(
_orderOwner, _orderNonce, _orderPrice, tradeTokens,
_token, SafeMath.add(takeFees, makeFees)
);
}
function swap(
uint _trade,
address _token,
address _orderOwner,
uint _tradeTokens,
uint _tradeEther,
uint _makeFees,
uint _takeFees
) private {
if (_trade == BUY) {
tokens[msg.sender][_token] = SafeMath.add(
tokens[msg.sender][_token], _tradeTokens
);
tokens[_orderOwner][_token] = SafeMath.sub(
tokens[_orderOwner][_token], _tradeTokens
);
balances[msg.sender] = SafeMath.sub(
balances[msg.sender], SafeMath.add(_tradeEther, _takeFees)
);
balances[_orderOwner] = SafeMath.add(
balances[_orderOwner], SafeMath.sub(_tradeEther, _makeFees)
);
} else {
tokens[msg.sender][_token] = SafeMath.sub(
tokens[msg.sender][_token], _tradeTokens
);
tokens[_orderOwner][_token] = SafeMath.add(
tokens[_orderOwner][_token], _tradeTokens
);
balances[msg.sender] = SafeMath.add(
balances[msg.sender], SafeMath.sub(_tradeEther, _takeFees)
);
balances[_orderOwner] = SafeMath.sub(
balances[_orderOwner], SafeMath.add(_tradeEther, _makeFees)
);
}
}
function sendOrderEvent(
address _orderOwner,
uint _orderNonce,
uint _orderPrice,
uint _tradeTokens,
address _token,
uint _fees
) private {
Order(
_orderOwner,
_orderNonce,
_orderPrice,
_tradeTokens,
filled[_orderOwner][_orderNonce],
tokens[_orderOwner][_token],
balances[_orderOwner],
_fees
);
}
// Returns number of tokens that could be traded and its total price
function getTradeParameters(
uint _trade, address _token, address _orderOwner,
uint _orderNonce, uint _orderPrice, uint _orderAmount, uint _tradeAmount
) private returns (uint _tokens, uint _totalPrice) {
// remains on order
_tokens = SafeMath.sub(
_orderAmount, filled[_orderOwner][_orderNonce]
);
// trade no more than needed
if (_tokens > _tradeAmount) {
_tokens = _tradeAmount;
}
if (_trade == BUY) {
// ask owner has less tokens than it is on ask
if (_tokens > tokens[_orderOwner][_token]) {
NotEnoughTokens(
_orderOwner, _token, _tokens, tokens[_orderOwner][_token]
);
_tokens = tokens[_orderOwner][_token];
}
} else {
// not possible to sell more tokens than sender has
if (_tokens > tokens[msg.sender][_token]) {
NotEnoughTokens(
msg.sender, _token, _tokens, tokens[msg.sender][_token]
);
_tokens = tokens[msg.sender][_token];
}
}
uint shouldHave = getPrice(_tokens, _orderPrice);
uint spendable;
if (_trade == BUY) {
// max ether sender can spent
spendable = reversePercent(
balances[msg.sender],
applyCoeff(takeFee, msg.sender)
);
} else {
// max ether bid owner can spent
spendable = reversePercent(
balances[_orderOwner],
applyCoeff(makeFee, _orderOwner)
);
}
if (shouldHave <= spendable) {
// everyone have needed amount of tokens & ether
_totalPrice = shouldHave;
return;
}
// less price -> less tokens
_tokens = SafeMath.div(
SafeMath.mul(spendable, PRICE_MUL), _orderPrice
);
_totalPrice = getPrice(_tokens, _orderPrice);
if (_trade == BUY) {
NotEnoughEther(
msg.sender,
addFees(shouldHave, applyCoeff(takeFee, msg.sender)),
_totalPrice
);
} else {
NotEnoughEther(
_orderOwner,
addFees(shouldHave, applyCoeff(makeFee, _orderOwner)),
_totalPrice
);
}
}
// Returns price of _tokens
// _orderPrice is price per 1e18 tokens
function getPrice(
uint _tokens, uint _orderPrice
) private pure returns (uint) {
return SafeMath.div(
SafeMath.mul(_tokens, _orderPrice), PRICE_MUL
);
}
function getFees(
uint _eth, uint _fee, address _payer
) private view returns (uint) {
// _eth * (_fee / FEE_MUL)
return SafeMath.div(
SafeMath.mul(_eth, applyCoeff(_fee, _payer)),
FEE_MUL
);
}
function applyCoeff(uint _fees, address _user) private view returns (uint) {
if (now >= coeffs[_user].expire) {
return _fees;
}
return SafeMath.div(
SafeMath.mul(_fees, coeffs[_user].coeff), 100
);
}
function addFees(uint _eth, uint _fee) private view returns (uint) {
// _eth * (1 + _fee / FEE_MUL)
return SafeMath.div(
SafeMath.mul(_eth, SafeMath.add(FEE_MUL, _fee)),
FEE_MUL
);
}
function subFees(uint _eth, uint _fee) private view returns (uint) {
// _eth * (1 - _fee / FEE_MUL)
return SafeMath.div(
SafeMath.mul(_eth, SafeMath.sub(FEE_MUL, _fee)),
FEE_MUL
);
}
// Returns maximum ether that can be spent if percent _fee will be added
function reversePercent(
uint _balance, uint _fee
) private view returns (uint) {
// _trade + _fees = _balance
// _trade * (1 + _fee / FEE_MUL) = _balance
// _trade = _balance * FEE_MUL / (FEE_MUL + _fee)
return SafeMath.div(
SafeMath.mul(_balance, FEE_MUL),
SafeMath.add(FEE_MUL, _fee)
);
}
// Gets hash of an order, like it is done in `eth_signTypedData`
// See https://github.com/ethereum/EIPs/pull/712
function hashOrderTyped(
uint8 _order, address _token, uint _nonce, uint _price, uint _amount,
uint _expire
) private view returns (bytes32) {
require(_order == BUY || _order == SELL);
return keccak256(
ETH_SIGN_TYPED_DATA_ARGHASH,
keccak256(
this,
_order == BUY ? "BUY" : "SELL",
_token,
_nonce,
_price,
_amount,
_expire
)
);
}
// Gets hash of an order for `eth_sign`
function hashOrder(
uint8 _order, address _token, uint _nonce, uint _price, uint _amount,
uint _expire
) private view returns (bytes32) {
return keccak256(
"\x19Ethereum Signed Message:\n32",
keccak256(this, _order, _token, _nonce, _price, _amount, _expire)
);
}
// Returns hash of an order
// Reverts if signature is incorrect
function getVerifiedHash(
address _signer,
uint8 _order, address _token,
uint _nonce, uint _price, uint _amount, uint _expire,
uint _v, bytes32 _r, bytes32 _s
) private view returns (bytes32 _hash) {
if (_v < 1000) {
_hash = hashOrderTyped(
_order, _token, _nonce, _price, _amount, _expire
);
require(ecrecover(_hash, uint8(_v), _r, _s) == _signer);
} else {
_hash = hashOrder(
_order, _token, _nonce, _price, _amount, _expire
);
require(ecrecover(_hash, uint8(_v - 1000), _r, _s) == _signer);
}
}
function packKey(
uint8 _coeff, uint128 _duration
) private pure returns (uint) {
return (uint(_duration) << 8) + uint(_coeff);
}
function updateCoeff(
address _user, uint8 _coeff, uint128 _expire, uint price
) private {
coeffs[_user] = Coeff(_coeff, _expire);
NewFeeCoeff(_user, _coeff, _expire, price);
}
}
|
Buys new fee coefficient for given duration of time
|
function buyPack(
uint8 _coeff, uint128 _duration
) external payable {
require(now >= coeffs[msg.sender].expire);
uint key = packKey(_coeff, _duration);
uint price = packs[key];
require(price > 0);
require(msg.value == price);
updateCoeff(msg.sender, _coeff, uint128(now) + _duration, price);
balances[feeCollector] = SafeMath.add(
balances[feeCollector], msg.value
);
}
| 1,325,844
|
./full_match/1/0x5E16CA75000fb2B9d7B1184Fa24fF5D938a345Ef/sources/lib/chronicle-std/src/toll/Toll.sol
|
@inheritdoc IToll @custom:invariant Only contains tolled addresses. ∀x ∊ tolled(): _tolled[x] @custom:invariant Contains all tolled addresses. ∀x ∊ Address: _tolled[x] == 1 → x ∊ tolled() Initiate array with upper limit length. Iterate through all possible tolled addresses. Add address only if still tolled. Set length of array to number of tolled addresses actually included.
|
function tolled() public view returns (address[] memory) {
address[] memory budsList = new address[](_budsTouched.length);
uint ctr;
for (uint i; i < budsList.length; i++) {
if (_buds[_budsTouched[i]] == 1) {
budsList[ctr++] = _budsTouched[i];
}
}
assembly ("memory-safe") {
mstore(budsList, ctr)
}
return budsList;
}
| 17,127,038
|
./partial_match/1/0x539656a492eaBFA7556bB897807c046BB893eE53/sources/artandlife.sol
|
Set the starting index for the collection/ Just a sanity case in the worst case if this function is called late (EVM only stores last 256 block hashes) Prevent default sequence
|
function setStartingIndex() public {
require(startingIndex == 0, "Starting index is already set");
require(startingIndexBlock != 0, "Starting index block must be set");
startingIndex = uint(blockhash(startingIndexBlock)) % MAX_artandlife;
if (block.number.sub(startingIndexBlock) > 255) {
startingIndex = uint(blockhash(block.number - 1)) % MAX_artandlife;
}
if (startingIndex == 0) {
startingIndex = startingIndex.add(1);
}
}
| 9,115,262
|
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
import "./RegenesisMultisig.sol";
import "./AdditionalZkSync.sol";
/// @title zkSync main contract
/// @author Matter Labs
contract ZkSync is UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32 private constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
/// @notice Data needed to process onchain operation from block public data.
/// @notice Onchain operations is operations that need some processing on L1: Deposits, Withdrawals, ChangePubKey.
/// @param ethWitness Some external data that can be needed for operation processing
/// @param publicDataOffset Byte offset in public data for onchain operation
struct OnchainOperationData {
bytes ethWitness;
uint32 publicDataOffset;
}
/// @notice Data needed to commit new block
struct CommitBlockInfo {
bytes32 newStateHash;
bytes publicData;
uint256 timestamp;
OnchainOperationData[] onchainOperations;
uint32 blockNumber;
uint32 feeAccount;
}
/// @notice Data needed to execute committed and verified block
/// @param commitmentsInSlot verified commitments in one slot
/// @param commitmentIdx index such that commitmentsInSlot[commitmentIdx] is current block commitment
struct ExecuteBlockInfo {
StoredBlockInfo storedBlock;
bytes[] pendingOnchainOpsPubdata;
}
/// @notice Recursive proof input data (individual commitments are constructed onchain)
struct ProofInput {
uint256[] recursiveInput;
uint256[] proof;
uint256[] commitments;
uint8[] vkIndexes;
uint256[16] subproofsLimbs;
}
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external pure override returns (uint256) {
return 0;
}
/// @notice Notification that upgrade notice period started
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeNoticePeriodStarted() external override {
upgradeStartTimestamp = block.timestamp;
}
/// @notice Notification that upgrade preparation status is activated
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradePreparationStarted() external override {
upgradePreparationActive = true;
upgradePreparationActivationTime = block.timestamp;
require(block.timestamp >= upgradeStartTimestamp.add(approvedUpgradeNoticePeriod));
}
/// @dev When upgrade is finished or canceled we must clean upgrade-related state.
function clearUpgradeStatus() internal {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
approvedUpgradeNoticePeriod = UPGRADE_NOTICE_PERIOD;
emit NoticePeriodChange(approvedUpgradeNoticePeriod);
upgradeStartTimestamp = 0;
for (uint256 i = 0; i < SECURITY_COUNCIL_MEMBERS_NUMBER; ++i) {
securityCouncilApproves[i] = false;
}
numberOfApprovalsFromSecurityCouncil = 0;
}
/// @notice Notification that upgrade canceled
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeCanceled() external override {
clearUpgradeStatus();
}
/// @notice Notification that upgrade finishes
/// @dev Can be external because Proxy contract intercepts illegal calls of this function
function upgradeFinishes() external override {
clearUpgradeStatus();
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external view override returns (bool) {
return !exodusMode;
}
/// @notice zkSync contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// @dev _governanceAddress The address of Governance contract
/// @dev _verifierAddress The address of Verifier contract
/// @dev _genesisStateHash Genesis blocks (first block) state tree root hash
function initialize(bytes calldata initializationParameters) external {
initializeReentrancyGuard();
(address _governanceAddress, address _verifierAddress, address _additionalZkSync, bytes32 _genesisStateHash) =
abi.decode(initializationParameters, (address, address, address, bytes32));
verifier = Verifier(_verifierAddress);
governance = Governance(_governanceAddress);
additionalZkSync = AdditionalZkSync(_additionalZkSync);
StoredBlockInfo memory storedBlockZero =
StoredBlockInfo(0, 0, EMPTY_STRING_KECCAK, 0, _genesisStateHash, bytes32(0));
storedBlockHashes[0] = hashStoredBlockInfo(storedBlockZero);
approvedUpgradeNoticePeriod = UPGRADE_NOTICE_PERIOD;
emit NoticePeriodChange(approvedUpgradeNoticePeriod);
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
// solhint-disable-next-line no-empty-blocks
function upgrade(bytes calldata upgradeParameters) external nonReentrant {}
function cutUpgradeNoticePeriod() external {
/// All functions delegated to additional contract should NOT be nonReentrant
delegateAdditional();
}
/// @notice Sends tokens
/// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount
/// @dev This function is used to allow tokens to spend zkSync contract balance up to amount that is requested
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @param _maxAmount Maximum possible amount of tokens to transfer to this account
function _transferERC20(
IERC20 _token,
address _to,
uint128 _amount,
uint128 _maxAmount
) external returns (uint128 withdrawnAmount) {
require(msg.sender == address(this), "5"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed)
uint256 balanceBefore = _token.balanceOf(address(this));
require(Utils.sendERC20(_token, _to, _amount), "6"); // wtg11 - ERC20 transfer fails
uint256 balanceAfter = _token.balanceOf(address(this));
uint256 balanceDiff = balanceBefore.sub(balanceAfter);
require(balanceDiff <= _maxAmount, "7"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount
return SafeCast.toUint128(balanceDiff);
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external {
/// All functions delegated to additional contract should NOT be nonReentrant
delegateAdditional();
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
/// @param _zkSyncAddress The receiver Layer 2 address
function depositETH(address _zkSyncAddress) external payable {
require(_zkSyncAddress != SPECIAL_ACCOUNT_ADDRESS, "P");
requireActive();
registerDeposit(0, SafeCast.toUint128(msg.value), _zkSyncAddress);
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
/// @param _zkSyncAddress Receiver Layer 2 address
function depositERC20(
IERC20 _token,
uint104 _amount,
address _zkSyncAddress
) external nonReentrant {
require(_zkSyncAddress != SPECIAL_ACCOUNT_ADDRESS, "P");
requireActive();
// Get token id by its address
uint16 tokenId = governance.validateTokenAddress(address(_token));
require(!governance.pausedTokens(tokenId), "b"); // token deposits are paused
uint256 balanceBefore = _token.balanceOf(address(this));
require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "c"); // token transfer failed deposit
uint256 balanceAfter = _token.balanceOf(address(this));
uint128 depositAmount = SafeCast.toUint128(balanceAfter.sub(balanceBefore));
require(depositAmount <= MAX_DEPOSIT_AMOUNT, "C");
registerDeposit(tokenId, depositAmount, _zkSyncAddress);
}
/// @notice Returns amount of tokens that can be withdrawn by `address` from zkSync contract
/// @param _address Address of the tokens owner
/// @param _token Address of token, zero address is used for ETH
function getPendingBalance(address _address, address _token) public view returns (uint128) {
uint16 tokenId = 0;
if (_token != address(0)) {
tokenId = governance.validateTokenAddress(_token);
}
return pendingBalances[packAddressAndTokenId(_address, tokenId)].balanceToWithdraw;
}
/// @notice Withdraws tokens from zkSync contract to the owner
/// @param _owner Address of the tokens owner
/// @param _token Address of tokens, zero address is used for ETH
/// @param _amount Amount to withdraw to request.
/// NOTE: We will call ERC20.transfer(.., _amount), but if according to internal logic of ERC20 token zkSync contract
/// balance will be decreased by value more then _amount we will try to subtract this value from user pending balance
function withdrawPendingBalance(
address payable _owner,
address _token,
uint128 _amount
) external nonReentrant {
if (_token == address(0)) {
registerWithdrawal(0, _amount, _owner);
(bool success, ) = _owner.call{value: _amount}("");
require(success, "d"); // ETH withdraw failed
} else {
uint16 tokenId = governance.validateTokenAddress(_token);
bytes22 packedBalanceKey = packAddressAndTokenId(_owner, tokenId);
uint128 balance = pendingBalances[packedBalanceKey].balanceToWithdraw;
// We will allow withdrawals of `value` such that:
// `value` <= user pending balance
// `value` can be bigger then `_amount` requested if token takes fee from sender in addition to `_amount` requested
uint128 withdrawnAmount = this._transferERC20(IERC20(_token), _owner, _amount, balance);
registerWithdrawal(tokenId, withdrawnAmount, _owner);
}
}
/// @notice Withdraws NFT from zkSync contract to the owner
/// @param _tokenId Id of NFT token
function withdrawPendingNFTBalance(uint32 _tokenId) external nonReentrant {
Operations.WithdrawNFT memory op = pendingWithdrawnNFTs[_tokenId];
require(op.creatorAddress != address(0), "op"); // No NFT to withdraw
NFTFactory _factory = governance.getNFTFactory(op.creatorAccountId, op.creatorAddress);
_factory.mintNFTFromZkSync(
op.creatorAddress,
op.receiver,
op.creatorAccountId,
op.serialId,
op.contentHash,
op.tokenId
);
// Save withdrawn nfts for future deposits
withdrawnNFTs[op.tokenId] = address(_factory);
emit WithdrawalNFT(op.tokenId);
delete pendingWithdrawnNFTs[_tokenId];
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function requestFullExit(uint32 _accountId, address _token) public nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "e");
require(_accountId != SPECIAL_ACCOUNT_ID, "v"); // request full exit for nft storage account
uint16 tokenId;
if (_token == address(0)) {
tokenId = 0;
} else {
tokenId = governance.validateTokenAddress(_token);
}
// Priority Queue request
Operations.FullExit memory op =
Operations.FullExit({
accountId: _accountId,
owner: msg.sender,
tokenId: tokenId,
amount: 0, // unknown at this point
nftCreatorAccountId: uint32(0), // unknown at this point
nftCreatorAddress: address(0), // unknown at this point
nftSerialId: uint32(0), // unknown at this point
nftContentHash: bytes32(0) // unknown at this point
});
bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.FullExit, pubData);
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
pendingBalances[packedBalanceKey].gasReserveValue = FILLED_GAS_RESERVE_VALUE;
}
/// @notice Register full exit nft request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _tokenId NFT token id in zkSync network
function requestFullExitNFT(uint32 _accountId, uint32 _tokenId) public nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "e");
require(_accountId != SPECIAL_ACCOUNT_ID, "v"); // request full exit nft for nft storage account
require(MAX_FUNGIBLE_TOKEN_ID < _tokenId && _tokenId < SPECIAL_NFT_TOKEN_ID, "T"); // request full exit nft for invalid token id
// Priority Queue request
Operations.FullExit memory op =
Operations.FullExit({
accountId: _accountId,
owner: msg.sender,
tokenId: _tokenId,
amount: 0, // unknown at this point
nftCreatorAccountId: uint32(0), // unknown at this point
nftCreatorAddress: address(0), // unknown at this point
nftSerialId: uint32(0), // unknown at this point
nftContentHash: bytes32(0) // unknown at this point
});
bytes memory pubData = Operations.writeFullExitPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.FullExit, pubData);
}
/// @dev Process one block commit using previous block StoredBlockInfo,
/// @dev returns new block StoredBlockInfo
/// @dev NOTE: Does not change storage (except events, so we can't mark it view)
function commitOneBlock(StoredBlockInfo memory _previousBlock, CommitBlockInfo memory _newBlock)
internal
view
returns (StoredBlockInfo memory storedNewBlock)
{
require(_newBlock.blockNumber == _previousBlock.blockNumber + 1, "f"); // only commit next block
// Check timestamp of the new block
{
require(_newBlock.timestamp >= _previousBlock.timestamp, "g"); // Block should be after previous block
bool timestampNotTooSmall = block.timestamp.sub(COMMIT_TIMESTAMP_NOT_OLDER) <= _newBlock.timestamp;
bool timestampNotTooBig = _newBlock.timestamp <= block.timestamp.add(COMMIT_TIMESTAMP_APPROXIMATION_DELTA);
require(timestampNotTooSmall && timestampNotTooBig, "h"); // New block timestamp is not valid
}
// Check onchain operations
(bytes32 pendingOnchainOpsHash, uint64 priorityReqCommitted, bytes memory onchainOpsOffsetCommitment) =
collectOnchainOps(_newBlock);
// Create block commitment for verification proof
bytes32 commitment = createBlockCommitment(_previousBlock, _newBlock, onchainOpsOffsetCommitment);
return
StoredBlockInfo(
_newBlock.blockNumber,
priorityReqCommitted,
pendingOnchainOpsHash,
_newBlock.timestamp,
_newBlock.newStateHash,
commitment
);
}
/// @notice Commit block
/// @notice 1. Checks onchain operations, timestamp.
/// @notice 2. Store block commitments
function commitBlocks(StoredBlockInfo memory _lastCommittedBlockData, CommitBlockInfo[] memory _newBlocksData)
external
nonReentrant
{
requireActive();
governance.requireActiveValidator(msg.sender);
// Check that we commit blocks after last committed block
require(storedBlockHashes[totalBlocksCommitted] == hashStoredBlockInfo(_lastCommittedBlockData), "i"); // incorrect previous block data
for (uint32 i = 0; i < _newBlocksData.length; ++i) {
_lastCommittedBlockData = commitOneBlock(_lastCommittedBlockData, _newBlocksData[i]);
totalCommittedPriorityRequests += _lastCommittedBlockData.priorityOperations;
storedBlockHashes[_lastCommittedBlockData.blockNumber] = hashStoredBlockInfo(_lastCommittedBlockData);
emit BlockCommit(_lastCommittedBlockData.blockNumber);
}
totalBlocksCommitted += uint32(_newBlocksData.length);
require(totalCommittedPriorityRequests <= totalOpenPriorityRequests, "j");
}
/// @dev 1. Try to send token to _recipients
/// @dev 2. On failure: Increment _recipients balance to withdraw.
function withdrawOrStoreNFT(Operations.WithdrawNFT memory op) internal {
NFTFactory _factory = governance.getNFTFactory(op.creatorAccountId, op.creatorAddress);
try
_factory.mintNFTFromZkSync{gas: WITHDRAWAL_NFT_GAS_LIMIT}(
op.creatorAddress,
op.receiver,
op.creatorAccountId,
op.serialId,
op.contentHash,
op.tokenId
)
{
// Save withdrawn nfts for future deposits
withdrawnNFTs[op.tokenId] = address(_factory);
emit WithdrawalNFT(op.tokenId);
} catch {
pendingWithdrawnNFTs[op.tokenId] = op;
emit WithdrawalNFTPending(op.tokenId);
}
}
/// @dev 1. Try to send token to _recipients
/// @dev 2. On failure: Increment _recipients balance to withdraw.
function withdrawOrStore(
uint16 _tokenId,
address _recipient,
uint128 _amount
) internal {
bytes22 packedBalanceKey = packAddressAndTokenId(_recipient, _tokenId);
bool sent = false;
if (_tokenId == 0) {
address payable toPayable = address(uint160(_recipient));
sent = sendETHNoRevert(toPayable, _amount);
} else {
address tokenAddr = governance.tokenAddresses(_tokenId);
// We use `_transferERC20` here to check that `ERC20` token indeed transferred `_amount`
// and fail if token subtracted from zkSync balance more then `_amount` that was requested.
// This can happen if token subtracts fee from sender while transferring `_amount` that was requested to transfer.
try this._transferERC20{gas: WITHDRAWAL_GAS_LIMIT}(IERC20(tokenAddr), _recipient, _amount, _amount) {
sent = true;
} catch {
sent = false;
}
}
if (sent) {
emit Withdrawal(_tokenId, _amount);
} else {
increaseBalanceToWithdraw(packedBalanceKey, _amount);
emit WithdrawalPending(_tokenId, _amount);
}
}
/// @dev Executes one block
/// @dev 1. Processes all pending operations (Send Exits, Complete priority requests)
/// @dev 2. Finalizes block on Ethereum
/// @dev _executedBlockIdx is index in the array of the blocks that we want to execute together
function executeOneBlock(ExecuteBlockInfo memory _blockExecuteData, uint32 _executedBlockIdx) internal {
// Ensure block was committed
require(
hashStoredBlockInfo(_blockExecuteData.storedBlock) ==
storedBlockHashes[_blockExecuteData.storedBlock.blockNumber],
"exe10" // executing block should be committed
);
require(_blockExecuteData.storedBlock.blockNumber == totalBlocksExecuted + _executedBlockIdx + 1, "k"); // Execute blocks in order
bytes32 pendingOnchainOpsHash = EMPTY_STRING_KECCAK;
for (uint32 i = 0; i < _blockExecuteData.pendingOnchainOpsPubdata.length; ++i) {
bytes memory pubData = _blockExecuteData.pendingOnchainOpsPubdata[i];
Operations.OpType opType = Operations.OpType(uint8(pubData[0]));
if (opType == Operations.OpType.PartialExit) {
Operations.PartialExit memory op = Operations.readPartialExitPubdata(pubData);
// Circuit guarantees that partial exits are available only for fungible tokens
require(op.tokenId <= MAX_FUNGIBLE_TOKEN_ID, "mf1");
withdrawOrStore(uint16(op.tokenId), op.owner, op.amount);
} else if (opType == Operations.OpType.ForcedExit) {
Operations.ForcedExit memory op = Operations.readForcedExitPubdata(pubData);
// Circuit guarantees that forced exits are available only for fungible tokens
require(op.tokenId <= MAX_FUNGIBLE_TOKEN_ID, "mf2");
withdrawOrStore(uint16(op.tokenId), op.target, op.amount);
} else if (opType == Operations.OpType.FullExit) {
Operations.FullExit memory op = Operations.readFullExitPubdata(pubData);
if (op.tokenId <= MAX_FUNGIBLE_TOKEN_ID) {
withdrawOrStore(uint16(op.tokenId), op.owner, op.amount);
} else {
if (op.amount == 1) {
Operations.WithdrawNFT memory withdrawNftOp =
Operations.WithdrawNFT(
op.nftCreatorAccountId,
op.nftCreatorAddress,
op.nftSerialId,
op.nftContentHash,
op.owner,
op.tokenId
);
withdrawOrStoreNFT(withdrawNftOp);
}
}
} else if (opType == Operations.OpType.WithdrawNFT) {
Operations.WithdrawNFT memory op = Operations.readWithdrawNFTPubdata(pubData);
withdrawOrStoreNFT(op);
} else {
revert("l"); // unsupported op in block execution
}
pendingOnchainOpsHash = Utils.concatHash(pendingOnchainOpsHash, pubData);
}
require(pendingOnchainOpsHash == _blockExecuteData.storedBlock.pendingOnchainOperationsHash, "m"); // incorrect onchain ops executed
}
/// @notice Execute blocks, completing priority operations and processing withdrawals.
/// @notice 1. Processes all pending operations (Send Exits, Complete priority requests)
/// @notice 2. Finalizes block on Ethereum
function executeBlocks(ExecuteBlockInfo[] memory _blocksData) external nonReentrant {
requireActive();
governance.requireActiveValidator(msg.sender);
uint64 priorityRequestsExecuted = 0;
uint32 nBlocks = uint32(_blocksData.length);
for (uint32 i = 0; i < nBlocks; ++i) {
executeOneBlock(_blocksData[i], i);
priorityRequestsExecuted += _blocksData[i].storedBlock.priorityOperations;
emit BlockVerification(_blocksData[i].storedBlock.blockNumber);
}
firstPriorityRequestId += priorityRequestsExecuted;
totalCommittedPriorityRequests -= priorityRequestsExecuted;
totalOpenPriorityRequests -= priorityRequestsExecuted;
totalBlocksExecuted += nBlocks;
require(totalBlocksExecuted <= totalBlocksProven, "n"); // Can't execute blocks more then committed and proven currently.
}
/// @notice Blocks commitment verification.
/// @notice Only verifies block commitments without any other processing
function proveBlocks(StoredBlockInfo[] memory _committedBlocks, ProofInput memory _proof) external nonReentrant {
requireActive();
uint32 currentTotalBlocksProven = totalBlocksProven;
for (uint256 i = 0; i < _committedBlocks.length; ++i) {
require(hashStoredBlockInfo(_committedBlocks[i]) == storedBlockHashes[currentTotalBlocksProven + 1], "o1");
++currentTotalBlocksProven;
require(_proof.commitments[i] & INPUT_MASK == uint256(_committedBlocks[i].commitment) & INPUT_MASK, "o"); // incorrect block commitment in proof
}
bool success =
verifier.verifyAggregatedBlockProof(
_proof.recursiveInput,
_proof.proof,
_proof.vkIndexes,
_proof.commitments,
_proof.subproofsLimbs
);
require(success, "p"); // Aggregated proof verification fail
require(currentTotalBlocksProven <= totalBlocksCommitted, "q");
totalBlocksProven = currentTotalBlocksProven;
}
/// @notice Reverts unverified blocks
function revertBlocks(StoredBlockInfo[] memory _blocksToRevert) external {
/// All functions delegated to additional contract should NOT be nonReentrant
delegateAdditional();
}
/// @notice Checks if Exodus mode must be entered. If true - enters exodus mode and emits ExodusMode event.
/// @dev Exodus mode must be entered in case of current ethereum block number is higher than the oldest
/// @dev of existed priority requests expiration block number.
/// @return bool flag that is true if the Exodus mode must be entered.
function activateExodusMode() public returns (bool) {
bool trigger =
block.number >= priorityRequests[firstPriorityRequestId].expirationBlock &&
priorityRequests[firstPriorityRequestId].expirationBlock != 0;
if (trigger) {
if (!exodusMode) {
exodusMode = true;
emit ExodusMode();
}
return true;
} else {
return false;
}
}
/// @notice Withdraws token from ZkSync to root chain in case of exodus mode. User must provide proof that he owns funds
/// @param _storedBlockInfo Last verified block
/// @param _owner Owner of the account
/// @param _accountId Id of the account in the tree
/// @param _proof Proof
/// @param _tokenId Verified token id
/// @param _amount Amount for owner (must be total amount, not part of it)
function performExodus(
StoredBlockInfo memory _storedBlockInfo,
address _owner,
uint32 _accountId,
uint32 _tokenId,
uint128 _amount,
uint32 _nftCreatorAccountId,
address _nftCreatorAddress,
uint32 _nftSerialId,
bytes32 _nftContentHash,
uint256[] memory _proof
) external {
/// All functions delegated to additional should NOT be nonReentrant
delegateAdditional();
}
/// @notice Set data for changing pubkey hash using onchain authorization.
/// Transaction author (msg.sender) should be L2 account address
/// @notice New pubkey hash can be reset, to do that user should send two transactions:
/// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer.
/// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`.
/// @param _pubkeyHash New pubkey hash
/// @param _nonce Nonce of the change pubkey L2 transaction
function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external {
/// All functions delegated to additional contract should NOT be nonReentrant
delegateAdditional();
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op =
Operations.Deposit({
accountId: 0, // unknown at this point
owner: _owner,
tokenId: _tokenId,
amount: _amount
});
bytes memory pubData = Operations.writeDepositPubdataForPriorityQueue(op);
addPriorityRequest(Operations.OpType.Deposit, pubData);
emit Deposit(_tokenId, _amount);
}
/// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event
/// @param _token - token by id
/// @param _amount - token amount
/// @param _to - address to withdraw to
function registerWithdrawal(
uint16 _token,
uint128 _amount,
address payable _to
) internal {
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token);
uint128 balance = pendingBalances[packedBalanceKey].balanceToWithdraw;
pendingBalances[packedBalanceKey].balanceToWithdraw = balance.sub(_amount);
emit Withdrawal(_token, _amount);
}
/// @dev Gets operations packed in bytes array. Unpacks it and stores onchain operations.
/// @dev Priority operations must be committed in the same order as they are in the priority queue.
/// @dev NOTE: does not change storage! (only emits events)
/// @dev processableOperationsHash - hash of the all operations that needs to be executed (Deposit, Exits, ChangPubKey)
/// @dev priorityOperationsProcessed - number of priority operations processed in this block (Deposits, FullExits)
/// @dev offsetsCommitment - array where 1 is stored in chunk where onchainOperation begins and other are 0 (used in commitments)
function collectOnchainOps(CommitBlockInfo memory _newBlockData)
internal
view
returns (
bytes32 processableOperationsHash,
uint64 priorityOperationsProcessed,
bytes memory offsetsCommitment
)
{
bytes memory pubData = _newBlockData.publicData;
uint64 uncommittedPriorityRequestsOffset = firstPriorityRequestId + totalCommittedPriorityRequests;
priorityOperationsProcessed = 0;
processableOperationsHash = EMPTY_STRING_KECCAK;
require(pubData.length % CHUNK_BYTES == 0, "A"); // pubdata length must be a multiple of CHUNK_BYTES
offsetsCommitment = new bytes(pubData.length / CHUNK_BYTES);
for (uint256 i = 0; i < _newBlockData.onchainOperations.length; ++i) {
OnchainOperationData memory onchainOpData = _newBlockData.onchainOperations[i];
uint256 pubdataOffset = onchainOpData.publicDataOffset;
require(pubdataOffset < pubData.length, "A1");
require(pubdataOffset % CHUNK_BYTES == 0, "B"); // offsets should be on chunks boundaries
uint256 chunkId = pubdataOffset / CHUNK_BYTES;
require(offsetsCommitment[chunkId] == 0x00, "C"); // offset commitment should be empty
offsetsCommitment[chunkId] = bytes1(0x01);
Operations.OpType opType = Operations.OpType(uint8(pubData[pubdataOffset]));
if (opType == Operations.OpType.Deposit) {
bytes memory opPubData = Bytes.slice(pubData, pubdataOffset, DEPOSIT_BYTES);
Operations.Deposit memory depositData = Operations.readDepositPubdata(opPubData);
checkPriorityOperation(depositData, uncommittedPriorityRequestsOffset + priorityOperationsProcessed);
priorityOperationsProcessed++;
} else if (opType == Operations.OpType.ChangePubKey) {
bytes memory opPubData = Bytes.slice(pubData, pubdataOffset, CHANGE_PUBKEY_BYTES);
Operations.ChangePubKey memory op = Operations.readChangePubKeyPubdata(opPubData);
if (onchainOpData.ethWitness.length != 0) {
bool valid = verifyChangePubkey(onchainOpData.ethWitness, op);
require(valid, "D"); // failed to verify change pubkey hash signature
} else {
bool valid = authFacts[op.owner][op.nonce] == keccak256(abi.encodePacked(op.pubKeyHash));
require(valid, "E"); // new pub key hash is not authenticated properly
}
} else {
bytes memory opPubData;
if (opType == Operations.OpType.PartialExit) {
opPubData = Bytes.slice(pubData, pubdataOffset, PARTIAL_EXIT_BYTES);
} else if (opType == Operations.OpType.ForcedExit) {
opPubData = Bytes.slice(pubData, pubdataOffset, FORCED_EXIT_BYTES);
} else if (opType == Operations.OpType.WithdrawNFT) {
opPubData = Bytes.slice(pubData, pubdataOffset, WITHDRAW_NFT_BYTES);
} else if (opType == Operations.OpType.FullExit) {
opPubData = Bytes.slice(pubData, pubdataOffset, FULL_EXIT_BYTES);
Operations.FullExit memory fullExitData = Operations.readFullExitPubdata(opPubData);
checkPriorityOperation(
fullExitData,
uncommittedPriorityRequestsOffset + priorityOperationsProcessed
);
priorityOperationsProcessed++;
} else {
revert("F"); // unsupported op
}
processableOperationsHash = Utils.concatHash(processableOperationsHash, opPubData);
}
}
}
/// @notice Checks that change operation is correct
function verifyChangePubkey(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk)
internal
pure
returns (bool)
{
Operations.ChangePubkeyType changePkType = Operations.ChangePubkeyType(uint8(_ethWitness[0]));
if (changePkType == Operations.ChangePubkeyType.ECRECOVER) {
return verifyChangePubkeyECRECOVER(_ethWitness, _changePk);
} else if (changePkType == Operations.ChangePubkeyType.CREATE2) {
return verifyChangePubkeyCREATE2(_ethWitness, _changePk);
} else if (changePkType == Operations.ChangePubkeyType.OldECRECOVER) {
return verifyChangePubkeyOldECRECOVER(_ethWitness, _changePk);
} else if (changePkType == Operations.ChangePubkeyType.ECRECOVERV2) {
return verifyChangePubkeyECRECOVERV2(_ethWitness, _changePk);
} else {
revert("G"); // Incorrect ChangePubKey type
}
}
/// @notice Checks that signature is valid for pubkey change message
/// @param _ethWitness Signature (65 bytes)
/// @param _changePk Parsed change pubkey operation
function verifyChangePubkeyECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk)
internal
pure
returns (bool)
{
(, bytes memory signature) = Bytes.read(_ethWitness, 1, 65); // offset is 1 because we skip type of ChangePubkey
bytes32 messageHash =
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n60",
_changePk.pubKeyHash,
_changePk.nonce,
_changePk.accountId,
bytes32(0)
)
);
address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash);
return recoveredAddress == _changePk.owner && recoveredAddress != address(0);
}
/// @notice Checks that signature is valid for pubkey change message
/// @param _ethWitness Signature (65 bytes) + 32 bytes of the arbitrary signed data
/// @notice additional 32 bytes can be used to sign batches and ChangePubKey with one signature
/// @param _changePk Parsed change pubkey operation
function verifyChangePubkeyECRECOVERV2(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk)
internal
pure
returns (bool)
{
(uint256 offset, bytes memory signature) = Bytes.read(_ethWitness, 1, 65); // offset is 1 because we skip type of ChangePubkey
(, bytes32 additionalData) = Bytes.readBytes32(_ethWitness, offset);
bytes32 messageHash =
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n60",
_changePk.pubKeyHash,
_changePk.nonce,
_changePk.accountId,
additionalData
)
);
address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash);
return recoveredAddress == _changePk.owner && recoveredAddress != address(0);
}
/// @notice Checks that signature is valid for pubkey change message, old version differs by form of the signed message.
/// @param _ethWitness Signature (65 bytes)
/// @param _changePk Parsed change pubkey operation
function verifyChangePubkeyOldECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk)
internal
pure
returns (bool)
{
(, bytes memory signature) = Bytes.read(_ethWitness, 1, 65); // offset is 1 because we skip type of ChangePubkey
bytes32 messageHash =
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n152",
"Register zkSync pubkey:\n\n",
Bytes.bytesToHexASCIIBytes(abi.encodePacked(_changePk.pubKeyHash)),
"\n",
"nonce: 0x",
Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.nonce)),
"\n",
"account id: 0x",
Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_changePk.accountId)),
"\n\n",
"Only sign this message for a trusted client!"
)
);
address recoveredAddress = Utils.recoverAddressFromEthSignature(signature, messageHash);
return recoveredAddress == _changePk.owner && recoveredAddress != address(0);
}
/// @notice Checks that signature is valid for pubkey change message
/// @param _ethWitness Create2 deployer address, saltArg, codeHash
/// @param _changePk Parsed change pubkey operation
function verifyChangePubkeyCREATE2(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk)
internal
pure
returns (bool)
{
address creatorAddress;
bytes32 saltArg; // salt arg is additional bytes that are encoded in the CREATE2 salt
bytes32 codeHash;
uint256 offset = 1; // offset is 1 because we skip type of ChangePubkey
(offset, creatorAddress) = Bytes.readAddress(_ethWitness, offset);
(offset, saltArg) = Bytes.readBytes32(_ethWitness, offset);
(offset, codeHash) = Bytes.readBytes32(_ethWitness, offset);
// salt from CREATE2 specification
bytes32 salt = keccak256(abi.encodePacked(saltArg, _changePk.pubKeyHash));
// Address computation according to CREATE2 definition: https://eips.ethereum.org/EIPS/eip-1014
address recoveredAddress =
address(uint160(uint256(keccak256(abi.encodePacked(bytes1(0xff), creatorAddress, salt, codeHash)))));
// This type of change pubkey can be done only once
return recoveredAddress == _changePk.owner && _changePk.nonce == 0;
}
/// @dev Creates block commitment from its data
/// @dev _offsetCommitment - hash of the array where 1 is stored in chunk where onchainOperation begins and 0 for other chunks
function createBlockCommitment(
StoredBlockInfo memory _previousBlock,
CommitBlockInfo memory _newBlockData,
bytes memory _offsetCommitment
) internal view returns (bytes32 commitment) {
bytes32 hash = sha256(abi.encodePacked(uint256(_newBlockData.blockNumber), uint256(_newBlockData.feeAccount)));
hash = sha256(abi.encodePacked(hash, _previousBlock.stateHash));
hash = sha256(abi.encodePacked(hash, _newBlockData.newStateHash));
hash = sha256(abi.encodePacked(hash, uint256(_newBlockData.timestamp)));
bytes memory pubdata = abi.encodePacked(_newBlockData.publicData, _offsetCommitment);
/// The code below is equivalent to `commitment = sha256(abi.encodePacked(hash, _publicData))`
/// We use inline assembly instead of this concise and readable code in order to avoid copying of `_publicData` (which saves ~90 gas per transfer operation).
/// Specifically, we perform the following trick:
/// First, replace the first 32 bytes of `_publicData` (where normally its length is stored) with the value of `hash`.
/// Then, we call `sha256` precompile passing the `_publicData` pointer and the length of the concatenated byte buffer.
/// Finally, we put the `_publicData.length` back to its original location (to the first word of `_publicData`).
assembly {
let hashResult := mload(0x40)
let pubDataLen := mload(pubdata)
mstore(pubdata, hash)
// staticcall to the sha256 precompile at address 0x2
let success := staticcall(gas(), 0x2, pubdata, add(pubDataLen, 0x20), hashResult, 0x20)
mstore(pubdata, pubDataLen)
// Use "invalid" to make gas estimation work
switch success
case 0 {
invalid()
}
commitment := mload(hashResult)
}
}
/// @notice Checks that deposit is same as operation in priority queue
/// @param _deposit Deposit data
/// @param _priorityRequestId Operation's id in priority queue
function checkPriorityOperation(Operations.Deposit memory _deposit, uint64 _priorityRequestId) internal view {
Operations.OpType priorReqType = priorityRequests[_priorityRequestId].opType;
require(priorReqType == Operations.OpType.Deposit, "H"); // incorrect priority op type
bytes20 hashedPubdata = priorityRequests[_priorityRequestId].hashedPubData;
require(Operations.checkDepositInPriorityQueue(_deposit, hashedPubdata), "I");
}
/// @notice Checks that FullExit is same as operation in priority queue
/// @param _fullExit FullExit data
/// @param _priorityRequestId Operation's id in priority queue
function checkPriorityOperation(Operations.FullExit memory _fullExit, uint64 _priorityRequestId) internal view {
Operations.OpType priorReqType = priorityRequests[_priorityRequestId].opType;
require(priorReqType == Operations.OpType.FullExit, "J"); // incorrect priority op type
bytes20 hashedPubdata = priorityRequests[_priorityRequestId].hashedPubData;
require(Operations.checkFullExitInPriorityQueue(_fullExit, hashedPubdata), "K");
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(Operations.OpType _opType, bytes memory _pubData) internal {
// Expiration block is: current block number + priority expiration delta
uint64 expirationBlock = uint64(block.number + PRIORITY_EXPIRATION);
uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests;
bytes20 hashedPubData = Utils.hashBytesToBytes20(_pubData);
priorityRequests[nextPriorityRequestId] = PriorityOperation({
hashedPubData: hashedPubData,
expirationBlock: expirationBlock,
opType: _opType
});
emit NewPriorityRequest(msg.sender, nextPriorityRequestId, _opType, _pubData, uint256(expirationBlock));
totalOpenPriorityRequests++;
}
function increaseBalanceToWithdraw(bytes22 _packedBalanceKey, uint128 _amount) internal {
uint128 balance = pendingBalances[_packedBalanceKey].balanceToWithdraw;
pendingBalances[_packedBalanceKey] = PendingBalance(balance.add(_amount), FILLED_GAS_RESERVE_VALUE);
}
/// @notice Sends ETH
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendETHNoRevert(address payable _to, uint256 _amount) internal returns (bool) {
(bool callSuccess, ) = _to.call{gas: WITHDRAWAL_GAS_LIMIT, value: _amount}("");
return callSuccess;
}
/// @notice Delegates the call to the additional part of the main contract.
/// @notice Should be only use to delegate the external calls as it passes the calldata
/// @notice All functions delegated to additional contract should NOT be nonReentrant
function delegateAdditional() internal {
address _target = address(additionalZkSync);
assembly {
// The pointer to the free memory slot
let ptr := mload(0x40)
// Copy function signature and arguments from calldata at zero position into memory at pointer position
calldatacopy(ptr, 0x0, calldatasize())
// Delegatecall method of the implementation contract, returns 0 on error
let result := delegatecall(gas(), _target, ptr, calldatasize(), 0x0, 0)
// Get the size of the last return data
let size := returndatasize()
// Copy the size length of bytes from return data at zero position to pointer position
returndatacopy(ptr, 0x0, size)
// Depending on result value
switch result
case 0 {
// End execution and revert state changes
revert(ptr, size)
}
default {
// Return data with length of size at pointers position
return(ptr, size)
}
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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 {
/// @dev Address of lock flag variable.
/// @dev Flag is placed at random memory location to not interfere with Storage contract.
uint256 private constant LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/566a774222707e424896c0c390a84dc3c13bdcb2/contracts/security/ReentrancyGuard.sol
// 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;
function initializeReentrancyGuard() internal {
uint256 lockSlotOldValue;
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange every call to nonReentrant
// will be cheaper.
assembly {
lockSlotOldValue := sload(LOCK_FLAG_ADDRESS)
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
// Check that storage slot for reentrancy guard is empty to rule out possibility of slot conflict
require(lockSlotOldValue == 0, "1B");
}
/**
* @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() {
uint256 _status;
assembly {
_status := sload(LOCK_FLAG_ADDRESS)
}
// On the first call to nonReentrant, _notEntered will be true
require(_status == _NOT_ENTERED);
// Any calls to nonReentrant after this point will fail
assembly {
sstore(LOCK_FLAG_ADDRESS, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(LOCK_FLAG_ADDRESS, _NOT_ENTERED)
}
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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, "14");
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, "v");
}
/**
* @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, "15");
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, "x");
}
/**
* @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, "y");
}
/**
* @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;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.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 SafeMathUInt128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "12");
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(uint128 a, uint128 b) internal pure returns (uint128) {
return sub(a, b, "aa");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// 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;
}
uint128 c = a * b;
require(c / a == b, "13");
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(uint128 a, uint128 b) internal pure returns (uint128) {
return div(a, b, "ac");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
return mod(a, b, "ad");
}
/**
* @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(
uint128 a,
uint128 b,
string memory errorMessage
) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 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} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*
* _Available since v2.5.0._
*/
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, "16");
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, "17");
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, "18");
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, "19");
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, "1a");
return uint8(value);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Sends tokens
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transfer` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendERC20(
IERC20 _token,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount));
// `transfer` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Transfers token from one address to another
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _from Address of sender
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function transferFromERC20(
IERC20 _token,
address _from,
address _to,
uint256 _amount
) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) =
address(_token).call(abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount));
// `transferFrom` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _messageHash signed message hash.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes32 _messageHash)
internal
pure
returns (address)
{
require(_signature.length == 65, "P"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint8 signV;
assembly {
signR := mload(add(_signature, 32))
signS := mload(add(_signature, 64))
signV := byte(0, mload(add(_signature, 96)))
}
return ecrecover(_messageHash, signV, signR, signS);
}
/// @notice Returns new_hash = hash(old_hash + bytes)
function concatHash(bytes32 _hash, bytes memory _bytes) internal pure returns (bytes32) {
bytes32 result;
assembly {
let bytesLen := add(mload(_bytes), 32)
mstore(_bytes, _hash)
result := keccak256(_bytes, bytesLen)
}
return result;
}
function hashBytesToBytes20(bytes memory _bytes) internal pure returns (bytes20) {
return bytes20(uint160(uint256(keccak256(_bytes))));
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
// solhint-disable max-states-count
import "./IERC20.sol";
import "./Governance.sol";
import "./Verifier.sol";
import "./Operations.sol";
import "./NFTFactory.sol";
import "./AdditionalZkSync.sol";
/// @title zkSync storage contract
/// @author Matter Labs
contract Storage {
/// @dev Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool internal upgradePreparationActive;
/// @dev Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint256 internal upgradePreparationActivationTime;
/// @dev Verifier contract. Used to verify block proof and exit proof
Verifier internal verifier;
/// @dev Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance internal governance;
uint8 internal constant FILLED_GAS_RESERVE_VALUE = 0xff; // we use it to set gas revert value so slot will not be emptied with 0 balance
struct PendingBalance {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @dev Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => PendingBalance) internal pendingBalances;
// @dev Pending withdrawals are not used in this version
struct PendingWithdrawalDEPRECATED {
address to;
uint16 tokenId;
}
mapping(uint32 => PendingWithdrawalDEPRECATED) internal pendingWithdrawalsDEPRECATED;
uint32 internal firstPendingWithdrawalIndexDEPRECATED;
uint32 internal numberOfPendingWithdrawalsDEPRECATED;
/// @dev Total number of executed blocks i.e. blocks[totalBlocksExecuted] points at the latest executed block (block 0 is genesis)
uint32 public totalBlocksExecuted;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @Old rollup block stored data - not used in current version
/// @member validator Block producer
/// @member committedAtBlock ETH block number at which this block was committed
/// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks
/// @member priorityOperations Total number of priority operations for this block
/// @member commitment Hash of the block circuit commitment
/// @member stateRoot New tree root hash
///
/// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html
struct BlockDEPRECATED {
uint32 committedAtBlock;
uint64 priorityOperations;
uint32 chunks;
bytes32 withdrawalsDataHash; // can be restricted to 16 bytes to reduce number of required storage slots
bytes32 commitment;
bytes32 stateRoot;
}
mapping(uint32 => BlockDEPRECATED) internal blocksDEPRECATED;
/// @dev Flag indicates that a user has exited in the exodus mode certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint32 => bool)) internal performedExodus;
/// @dev Flag indicates that exodus (mass exit) mode is triggered
/// @dev Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @dev User authenticated fact hashes for some nonce.
mapping(address => mapping(uint32 => bytes32)) public authFacts;
/// @notice Old Priority Operation container
/// @member opType Priority operation type
/// @member pubData Priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
struct PriorityOperationDEPRECATED {
Operations.OpType opType;
bytes pubData;
uint256 expirationBlock;
}
/// @dev Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
mapping(uint64 => PriorityOperationDEPRECATED) internal priorityRequestsDEPRECATED;
/// @dev First open priority request id
uint64 public firstPriorityRequestId;
/// @dev Total number of requests
uint64 public totalOpenPriorityRequests;
/// @dev Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 internal totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @Rollup block stored data
/// @member blockNumber Rollup block number
/// @member priorityOperations Number of priority operations processed
/// @member pendingOnchainOperationsHash Hash of all operations that must be processed after verify
/// @member timestamp Rollup block timestamp, have the same format as Ethereum block constant
/// @member stateHash Root hash of the rollup state
/// @member commitment Verified input for the zkSync circuit
struct StoredBlockInfo {
uint32 blockNumber;
uint64 priorityOperations;
bytes32 pendingOnchainOperationsHash;
uint256 timestamp;
bytes32 stateHash;
bytes32 commitment;
}
/// @notice Returns the keccak hash of the ABI-encoded StoredBlockInfo
function hashStoredBlockInfo(StoredBlockInfo memory _storedBlockInfo) internal pure returns (bytes32) {
return keccak256(abi.encode(_storedBlockInfo));
}
/// @dev Stored hashed StoredBlockInfo for some block number
mapping(uint32 => bytes32) public storedBlockHashes;
/// @dev Total blocks proven.
uint32 public totalBlocksProven;
/// @notice Priority Operation container
/// @member hashedPubData Hashed priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
/// @member opType Priority operation type
struct PriorityOperation {
bytes20 hashedPubData;
uint64 expirationBlock;
Operations.OpType opType;
}
/// @dev Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
mapping(uint64 => PriorityOperation) internal priorityRequests;
/// @dev Timer for authFacts entry reset (address, nonce -> timer).
/// @dev Used when user wants to reset `authFacts` for some nonce.
mapping(address => mapping(uint32 => uint256)) internal authFactsResetTimer;
mapping(uint32 => address) internal withdrawnNFTs;
mapping(uint32 => Operations.WithdrawNFT) internal pendingWithdrawnNFTs;
AdditionalZkSync internal additionalZkSync;
/// @dev Upgrade notice period, possibly shorten by the security council
uint256 internal approvedUpgradeNoticePeriod;
/// @dev Upgrade start timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint256 internal upgradeStartTimestamp;
/// @dev Stores boolean flags which means the confirmations of the upgrade for each member of security council
/// @dev Will store zeroes in case of not active upgrade mode
mapping(uint256 => bool) internal securityCouncilApproves;
uint256 internal numberOfApprovalsFromSecurityCouncil;
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "L"); // exodus mode activated
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title zkSync configuration constants
/// @author Matter Labs
contract Config {
/// @dev ERC20 tokens and ETH withdrawals gas limit, used only for complete withdrawals
uint256 internal constant WITHDRAWAL_GAS_LIMIT = 100000;
/// @dev NFT withdrawals gas limit, used only for complete withdrawals
uint256 internal constant WITHDRAWAL_NFT_GAS_LIMIT = 300000;
/// @dev Bytes in one chunk
uint8 internal constant CHUNK_BYTES = 10;
/// @dev zkSync address length
uint8 internal constant ADDRESS_BYTES = 20;
uint8 internal constant PUBKEY_HASH_BYTES = 20;
/// @dev Public key bytes length
uint8 internal constant PUBKEY_BYTES = 32;
/// @dev Ethereum signature r/s bytes length
uint8 internal constant ETH_SIGN_RS_BYTES = 32;
/// @dev Success flag bytes length
uint8 internal constant SUCCESS_FLAG_BYTES = 1;
/// @dev Max amount of tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 internal constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 1023;
/// @dev Max account id that could be registered in the network
uint32 internal constant MAX_ACCOUNT_ID = 16777215;
/// @dev Expected average period of block creation
uint256 internal constant BLOCK_PERIOD = 15 seconds;
/// @dev ETH blocks verification expectation
/// @dev Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// @dev If set to 0 validator can revert blocks at any time.
uint256 internal constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 internal constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 internal constant DEPOSIT_BYTES = 6 * CHUNK_BYTES;
uint256 internal constant MINT_NFT_BYTES = 5 * CHUNK_BYTES;
uint256 internal constant TRANSFER_TO_NEW_BYTES = 6 * CHUNK_BYTES;
uint256 internal constant PARTIAL_EXIT_BYTES = 6 * CHUNK_BYTES;
uint256 internal constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 internal constant FORCED_EXIT_BYTES = 6 * CHUNK_BYTES;
uint256 internal constant WITHDRAW_NFT_BYTES = 10 * CHUNK_BYTES;
/// @dev Full exit operation length
uint256 internal constant FULL_EXIT_BYTES = 11 * CHUNK_BYTES;
/// @dev ChangePubKey operation length
uint256 internal constant CHANGE_PUBKEY_BYTES = 6 * CHUNK_BYTES;
/// @dev Expiration delta for priority request to be satisfied (in seconds)
/// @dev NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD)
/// @dev otherwise incorrect block with priority op could not be reverted.
uint256 internal constant PRIORITY_EXPIRATION_PERIOD = 3 days;
/// @dev Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 internal constant PRIORITY_EXPIRATION =
PRIORITY_EXPIRATION_PERIOD/BLOCK_PERIOD;
/// @dev Maximum number of priority request to clear during verifying the block
/// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots
/// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure
uint64 internal constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @dev Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint256 internal constant MASS_FULL_EXIT_PERIOD = 9 days;
/// @dev Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint256 internal constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @dev Notice period before activation preparation status of upgrade mode (in seconds)
/// @dev NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it.
uint256 internal constant UPGRADE_NOTICE_PERIOD =
MASS_FULL_EXIT_PERIOD+PRIORITY_EXPIRATION_PERIOD+TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT;
/// @dev Timestamp - seconds since unix epoch
uint256 internal constant COMMIT_TIMESTAMP_NOT_OLDER = 24 hours;
/// @dev Maximum available error between real commit block timestamp and analog used in the verifier (in seconds)
/// @dev Must be used cause miner's `block.timestamp` value can differ on some small value (as we know - 15 seconds)
uint256 internal constant COMMIT_TIMESTAMP_APPROXIMATION_DELTA = 15 minutes;
/// @dev Bit mask to apply for verifier public input before verifying.
uint256 internal constant INPUT_MASK = 14474011154664524427946373126085988481658748083205070504932198000989141204991;
/// @dev Auth fact reset timelock.
uint256 internal constant AUTH_FACT_RESET_TIMELOCK = 1 days;
/// @dev Max deposit of ERC20 token that is possible to deposit
uint128 internal constant MAX_DEPOSIT_AMOUNT = 20282409603651670423947251286015;
uint32 internal constant SPECIAL_ACCOUNT_ID = 16777215;
address internal constant SPECIAL_ACCOUNT_ADDRESS = address(0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF);
uint32 internal constant SPECIAL_NFT_TOKEN_ID = 2147483646;
uint32 internal constant MAX_FUNGIBLE_TOKEN_ID = 65535;
uint256 internal constant SECURITY_COUNCIL_MEMBERS_NUMBER = 15;
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title zkSync events
/// @author Matter Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
/// @notice Event emitted when a block is verified
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when user funds are withdrawn from the zkSync state and contract
event Withdrawal(uint16 indexed tokenId, uint128 amount);
/// @notice Event emitted when user funds are withdrawn from the zkSync state but not from contract
event WithdrawalPending(uint16 indexed tokenId, uint128 amount);
/// @notice Event emitted when user NFT is withdrawn from the zkSync state and contract
event WithdrawalNFT(uint32 indexed tokenId);
/// @notice Event emitted when user NFT is withdrawn from the zkSync state but not from contract
event WithdrawalNFTPending(uint32 indexed tokenId);
/// @notice Event emitted when user funds are deposited to the zkSync contract
event Deposit(uint16 indexed tokenId, uint128 amount);
/// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash)
event FactAuth(address indexed sender, uint32 nonce, bytes fact);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(uint32 totalBlocksVerified, uint32 totalBlocksCommitted);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Notice period changed
event NoticePeriodChange(uint256 newNoticePeriod);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(uint256 indexed versionId, address indexed upgradeable);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint256 indexed versionId,
address[] newTargets,
uint256 noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(uint256 indexed versionId);
/// @notice Upgrade mode preparation status event
event PreparationStart(uint256 indexed versionId);
/// @notice Upgrade mode complete event
event UpgradeComplete(uint256 indexed versionId, address[] newTargets);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint256(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint256 self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "Q");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint256 data = self << ((32 - byteLength) * 8);
assembly {
mstore(
add(bts, 32), // BYTES_HEADER_SIZE
data
)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint256(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "R");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "S");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "T");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "U");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "V");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "W");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "X");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "Y");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_bytes.length >= (_start + _length), "Z"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return newOffset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(
bytes memory _data,
uint256 _offset,
uint256 _length
) internal pure returns (uint256 newOffset, bytes memory data) {
data = slice(_data, _offset, _length);
newOffset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bool r) {
newOffset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint8 r) {
newOffset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint16 r) {
newOffset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint24 r) {
newOffset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint32 r) {
newOffset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint128 r) {
newOffset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, uint160 r) {
newOffset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, address r) {
newOffset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bytes20 r) {
newOffset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint256 _offset) internal pure returns (uint256 newOffset, bytes32 r) {
newOffset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
/// Trim bytes into single word
function trim(bytes memory _data, uint256 _newLength) internal pure returns (uint256 r) {
require(_newLength <= 0x20, "10"); // new_length is longer than word
require(_data.length >= _newLength, "11"); // data is to short
uint256 a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _newLength) * 8);
}
// Helper function for hex conversion.
function halfByteToHex(bytes1 _byte) internal pure returns (bytes1 _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return bytes1(uint8(0x66656463626139383736353433323130 >> (uint8(_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(
out_curr,
shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
mstore(
add(out_curr, 0x01),
shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130))
)
}
}
return outStringBytes;
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Bytes.sol";
import "./Utils.sol";
/// @title zkSync operations tools
library Operations {
// Circuit ops and their pubdata (chunks * bytes)
/// @notice zkSync circuit operation type
enum OpType {
Noop,
Deposit,
TransferToNew,
PartialExit,
_CloseAccount, // used for correct op id offset
Transfer,
FullExit,
ChangePubKey,
ForcedExit,
MintNFT,
WithdrawNFT,
Swap
}
// Byte lengths
uint8 internal constant OP_TYPE_BYTES = 1;
uint8 internal constant TOKEN_BYTES = 4;
uint8 internal constant PUBKEY_BYTES = 32;
uint8 internal constant NONCE_BYTES = 4;
uint8 internal constant PUBKEY_HASH_BYTES = 20;
uint8 internal constant ADDRESS_BYTES = 20;
uint8 internal constant CONTENT_HASH_BYTES = 32;
/// @dev Packed fee bytes lengths
uint8 internal constant FEE_BYTES = 2;
/// @dev zkSync account id bytes lengths
uint8 internal constant ACCOUNT_ID_BYTES = 4;
/// @dev zkSync nft serial id bytes lengths
uint8 internal constant NFT_SERIAL_ID_BYTES = 4;
uint8 internal constant AMOUNT_BYTES = 16;
/// @dev Signature (for example full exit signature) bytes length
uint8 internal constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
// uint8 opType
uint32 accountId;
uint32 tokenId;
uint128 amount;
address owner;
}
uint256 internal constant PACKED_DEPOSIT_PUBDATA_BYTES =
OP_TYPE_BYTES + ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure returns (Deposit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "N"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
function writeDepositPubdataForPriorityQueue(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.Deposit),
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner // owner
);
}
/// @notice Write deposit pubdata for priority queue check.
function checkDepositInPriorityQueue(Deposit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeDepositPubdataForPriorityQueue(op)) == hashedPubdata;
}
// FullExit pubdata
struct FullExit {
// uint8 opType
uint32 accountId;
address owner;
uint32 tokenId;
uint128 amount;
uint32 nftCreatorAccountId;
address nftCreatorAddress;
uint32 nftSerialId;
bytes32 nftContentHash;
}
uint256 public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
OP_TYPE_BYTES +
ACCOUNT_ID_BYTES +
ADDRESS_BYTES +
TOKEN_BYTES +
AMOUNT_BYTES +
ACCOUNT_ID_BYTES +
ADDRESS_BYTES +
NFT_SERIAL_ID_BYTES +
CONTENT_HASH_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure returns (FullExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.nftCreatorAccountId) = Bytes.readUInt32(_data, offset); // nftCreatorAccountId
(offset, parsed.nftCreatorAddress) = Bytes.readAddress(_data, offset); // nftCreatorAddress
(offset, parsed.nftSerialId) = Bytes.readUInt32(_data, offset); // nftSerialId
(offset, parsed.nftContentHash) = Bytes.readBytes32(_data, offset); // nftContentHash
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "O"); // reading invalid full exit pubdata size
}
function writeFullExitPubdataForPriorityQueue(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
uint8(OpType.FullExit),
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
uint128(0), // amount -- ignored
uint32(0), // nftCreatorAccountId -- ignored
address(0), // nftCreatorAddress -- ignored
uint32(0), // nftSerialId -- ignored
bytes32(0) // nftContentHash -- ignored
);
}
function checkFullExitInPriorityQueue(FullExit memory op, bytes20 hashedPubdata) internal pure returns (bool) {
return Utils.hashBytesToBytes20(writeFullExitPubdataForPriorityQueue(op)) == hashedPubdata;
}
// PartialExit pubdata
struct PartialExit {
//uint8 opType; -- present in pubdata, ignored at serialization
//uint32 accountId; -- present in pubdata, ignored at serialization
uint32 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
}
function readPartialExitPubdata(bytes memory _data) internal pure returns (PartialExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES; // opType + accountId (ignored)
(offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
}
// ForcedExit pubdata
struct ForcedExit {
//uint8 opType; -- present in pubdata, ignored at serialization
//uint32 initiatorAccountId; -- present in pubdata, ignored at serialization
//uint32 targetAccountId; -- present in pubdata, ignored at serialization
uint32 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address target;
}
function readForcedExitPubdata(bytes memory _data) internal pure returns (ForcedExit memory parsed) {
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES * 2; // opType + initiatorAccountId + targetAccountId (ignored)
(offset, parsed.tokenId) = Bytes.readUInt32(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
offset += FEE_BYTES; // fee (ignored)
(offset, parsed.target) = Bytes.readAddress(_data, offset); // target
}
// ChangePubKey
enum ChangePubkeyType {ECRECOVER, CREATE2, OldECRECOVER, ECRECOVERV2}
struct ChangePubKey {
// uint8 opType; -- present in pubdata, ignored at serialization
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
//uint32 tokenId; -- present in pubdata, ignored at serialization
//uint16 fee; -- present in pubdata, ignored at serialization
}
function readChangePubKeyPubdata(bytes memory _data) internal pure returns (ChangePubKey memory parsed) {
uint256 offset = OP_TYPE_BYTES;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
struct WithdrawNFT {
//uint8 opType; -- present in pubdata, ignored at serialization
//uint32 accountId; -- present in pubdata, ignored at serialization
uint32 creatorAccountId;
address creatorAddress;
uint32 serialId;
bytes32 contentHash;
address receiver;
uint32 tokenId;
//uint32 feeTokenId;
//uint16 fee; -- present in pubdata, ignored at serialization
}
function readWithdrawNFTPubdata(bytes memory _data) internal pure returns (WithdrawNFT memory parsed) {
uint256 offset = OP_TYPE_BYTES + ACCOUNT_ID_BYTES; // opType + accountId (ignored)
(offset, parsed.creatorAccountId) = Bytes.readUInt32(_data, offset);
(offset, parsed.creatorAddress) = Bytes.readAddress(_data, offset);
(offset, parsed.serialId) = Bytes.readUInt32(_data, offset);
(offset, parsed.contentHash) = Bytes.readBytes32(_data, offset);
(offset, parsed.receiver) = Bytes.readAddress(_data, offset);
(offset, parsed.tokenId) = Bytes.readUInt32(_data, offset);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint256);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Ownable.sol";
import "./Config.sol";
/// @title Regenesis Multisig contract
/// @author Matter Labs
contract RegenesisMultisig is Ownable, Config {
event CandidateAccepted(bytes32 oldRootHash, bytes32 newRootHash);
event CandidateApproval(uint256 currentApproval);
bytes32 public oldRootHash;
bytes32 public newRootHash;
bytes32 public candidateOldRootHash;
bytes32 public candidateNewRootHash;
/// @dev Stores boolean flags which means the confirmations of the upgrade for each member of security council
mapping(uint256 => bool) internal securityCouncilApproves;
uint256 internal numberOfApprovalsFromSecurityCouncil;
uint256 securityCouncilThreshold;
constructor(uint256 threshold) Ownable(msg.sender) {
securityCouncilThreshold = threshold;
}
function submitHash(bytes32 _oldRootHash, bytes32 _newRootHash) external {
// Only zkSync team can submit the hashes
require(msg.sender == getMaster(), "1");
candidateOldRootHash = _oldRootHash;
candidateNewRootHash = _newRootHash;
oldRootHash = bytes32(0);
newRootHash = bytes32(0);
for (uint256 i = 0; i < SECURITY_COUNCIL_MEMBERS_NUMBER; ++i) {
securityCouncilApproves[i] = false;
}
numberOfApprovalsFromSecurityCouncil = 0;
}
function approveHash(bytes32 _oldRootHash, bytes32 _newRootHash) external {
require(_oldRootHash == candidateOldRootHash, "2");
require(_newRootHash == candidateNewRootHash, "3");
address payable[SECURITY_COUNCIL_MEMBERS_NUMBER] memory SECURITY_COUNCIL_MEMBERS =
[0xa2602ea835E03fb39CeD30B43d6b6EAf6aDe1769,0x9D5d6D4BaCCEDf6ECE1883456AA785dc996df607,0x002A5dc50bbB8d5808e418Aeeb9F060a2Ca17346,0x71E805aB236c945165b9Cd0bf95B9f2F0A0488c3,0x76C6cE74EAb57254E785d1DcC3f812D274bCcB11,0xFBfF3FF69D65A9103Bf4fdBf988f5271D12B3190,0xAfC2F2D803479A2AF3A72022D54cc0901a0ec0d6,0x4d1E3089042Ab3A93E03CA88B566b99Bd22438C6,0x19eD6cc20D44e5cF4Bb4894F50162F72402d8567,0x39415255619783A2E71fcF7d8f708A951d92e1b6,0x399a6a13D298CF3F41a562966C1a450136Ea52C2,0xee8AE1F1B4B1E1956C8Bda27eeBCE54Cf0bb5eaB,0xe7CCD4F3feA7df88Cf9B59B30f738ec1E049231f,0xA093284c707e207C36E3FEf9e0B6325fd9d0e33B,0x225d3822De44E58eE935440E0c0B829C4232086e];
for (uint256 id = 0; id < SECURITY_COUNCIL_MEMBERS_NUMBER; ++id) {
if (SECURITY_COUNCIL_MEMBERS[id] == msg.sender) {
require(securityCouncilApproves[id] == false);
securityCouncilApproves[id] = true;
numberOfApprovalsFromSecurityCouncil++;
emit CandidateApproval(numberOfApprovalsFromSecurityCouncil);
// It is ok to check for strict equality since the numberOfApprovalsFromSecurityCouncil
// is increased by one at a time. It is better to do so not to emit the
// CandidateAccepted event more than once
if (numberOfApprovalsFromSecurityCouncil == securityCouncilThreshold) {
oldRootHash = candidateOldRootHash;
newRootHash = candidateNewRootHash;
emit CandidateAccepted(oldRootHash, newRootHash);
}
}
}
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
/// @title zkSync additional main contract
/// @author Matter Labs
contract AdditionalZkSync is Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
function increaseBalanceToWithdraw(bytes22 _packedBalanceKey, uint128 _amount) internal {
uint128 balance = pendingBalances[_packedBalanceKey].balanceToWithdraw;
pendingBalances[_packedBalanceKey] = PendingBalance(balance.add(_amount), FILLED_GAS_RESERVE_VALUE);
}
/// @notice Withdraws token from ZkSync to root chain in case of exodus mode. User must provide proof that he owns funds
/// @param _storedBlockInfo Last verified block
/// @param _owner Owner of the account
/// @param _accountId Id of the account in the tree
/// @param _proof Proof
/// @param _tokenId Verified token id
/// @param _amount Amount for owner (must be total amount, not part of it)
function performExodus(
StoredBlockInfo memory _storedBlockInfo,
address _owner,
uint32 _accountId,
uint32 _tokenId,
uint128 _amount,
uint32 _nftCreatorAccountId,
address _nftCreatorAddress,
uint32 _nftSerialId,
bytes32 _nftContentHash,
uint256[] memory _proof
) external {
require(_accountId <= MAX_ACCOUNT_ID, "e");
require(_accountId != SPECIAL_ACCOUNT_ID, "v");
require(_tokenId < SPECIAL_NFT_TOKEN_ID, "T");
require(exodusMode, "s"); // must be in exodus mode
require(!performedExodus[_accountId][_tokenId], "t"); // already exited
require(storedBlockHashes[totalBlocksExecuted] == hashStoredBlockInfo(_storedBlockInfo), "u"); // incorrect stored block info
bool proofCorrect =
verifier.verifyExitProof(
_storedBlockInfo.stateHash,
_accountId,
_owner,
_tokenId,
_amount,
_nftCreatorAccountId,
_nftCreatorAddress,
_nftSerialId,
_nftContentHash,
_proof
);
require(proofCorrect, "x");
if (_tokenId <= MAX_FUNGIBLE_TOKEN_ID) {
bytes22 packedBalanceKey = packAddressAndTokenId(_owner, uint16(_tokenId));
increaseBalanceToWithdraw(packedBalanceKey, _amount);
emit WithdrawalPending(uint16(_tokenId), _amount);
} else {
require(_amount != 0, "Z"); // Unsupported nft amount
Operations.WithdrawNFT memory withdrawNftOp =
Operations.WithdrawNFT(
_nftCreatorAccountId,
_nftCreatorAddress,
_nftSerialId,
_nftContentHash,
_owner,
_tokenId
);
pendingWithdrawnNFTs[_tokenId] = withdrawNftOp;
emit WithdrawalNFTPending(_tokenId);
}
performedExodus[_accountId][_tokenId] = true;
}
function cancelOutstandingDepositsForExodusMode(uint64 _n, bytes[] memory _depositsPubdata) external {
require(exodusMode, "8"); // exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "9"); // no deposits to process
uint64 currentDepositIdx = 0;
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
bytes memory depositPubdata = _depositsPubdata[currentDepositIdx];
require(Utils.hashBytesToBytes20(depositPubdata) == priorityRequests[id].hashedPubData, "a");
++currentDepositIdx;
Operations.Deposit memory op = Operations.readDepositPubdata(depositPubdata);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, uint16(op.tokenId));
pendingBalances[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
uint256 internal constant SECURITY_COUNCIL_2_WEEKS_THRESHOLD = 8;
uint256 internal constant SECURITY_COUNCIL_1_WEEK_THRESHOLD = 10;
uint256 internal constant SECURITY_COUNCIL_3_DAYS_THRESHOLD = 12;
function cutUpgradeNoticePeriod() external {
requireActive();
address payable[SECURITY_COUNCIL_MEMBERS_NUMBER] memory SECURITY_COUNCIL_MEMBERS =
[0xa2602ea835E03fb39CeD30B43d6b6EAf6aDe1769,0x9D5d6D4BaCCEDf6ECE1883456AA785dc996df607,0x002A5dc50bbB8d5808e418Aeeb9F060a2Ca17346,0x71E805aB236c945165b9Cd0bf95B9f2F0A0488c3,0x76C6cE74EAb57254E785d1DcC3f812D274bCcB11,0xFBfF3FF69D65A9103Bf4fdBf988f5271D12B3190,0xAfC2F2D803479A2AF3A72022D54cc0901a0ec0d6,0x4d1E3089042Ab3A93E03CA88B566b99Bd22438C6,0x19eD6cc20D44e5cF4Bb4894F50162F72402d8567,0x39415255619783A2E71fcF7d8f708A951d92e1b6,0x399a6a13D298CF3F41a562966C1a450136Ea52C2,0xee8AE1F1B4B1E1956C8Bda27eeBCE54Cf0bb5eaB,0xe7CCD4F3feA7df88Cf9B59B30f738ec1E049231f,0xA093284c707e207C36E3FEf9e0B6325fd9d0e33B,0x225d3822De44E58eE935440E0c0B829C4232086e];
for (uint256 id = 0; id < SECURITY_COUNCIL_MEMBERS_NUMBER; ++id) {
if (SECURITY_COUNCIL_MEMBERS[id] == msg.sender) {
require(upgradeStartTimestamp != 0);
require(securityCouncilApproves[id] == false);
securityCouncilApproves[id] = true;
numberOfApprovalsFromSecurityCouncil++;
if (numberOfApprovalsFromSecurityCouncil == SECURITY_COUNCIL_2_WEEKS_THRESHOLD) {
if (approvedUpgradeNoticePeriod > 2 weeks) {
approvedUpgradeNoticePeriod = 2 weeks;
emit NoticePeriodChange(approvedUpgradeNoticePeriod);
}
} else if (numberOfApprovalsFromSecurityCouncil == SECURITY_COUNCIL_1_WEEK_THRESHOLD) {
if (approvedUpgradeNoticePeriod > 1 weeks) {
approvedUpgradeNoticePeriod = 1 weeks;
emit NoticePeriodChange(approvedUpgradeNoticePeriod);
}
} else if (numberOfApprovalsFromSecurityCouncil == SECURITY_COUNCIL_3_DAYS_THRESHOLD) {
if (approvedUpgradeNoticePeriod > 3 days) {
approvedUpgradeNoticePeriod = 3 days;
emit NoticePeriodChange(approvedUpgradeNoticePeriod);
}
}
break;
}
}
}
/// @notice Set data for changing pubkey hash using onchain authorization.
/// Transaction author (msg.sender) should be L2 account address
/// @notice New pubkey hash can be reset, to do that user should send two transactions:
/// 1) First `setAuthPubkeyHash` transaction for already used `_nonce` will set timer.
/// 2) After `AUTH_FACT_RESET_TIMELOCK` time is passed second `setAuthPubkeyHash` transaction will reset pubkey hash for `_nonce`.
/// @param _pubkeyHash New pubkey hash
/// @param _nonce Nonce of the change pubkey L2 transaction
function setAuthPubkeyHash(bytes calldata _pubkeyHash, uint32 _nonce) external {
requireActive();
require(_pubkeyHash.length == PUBKEY_HASH_BYTES, "y"); // PubKeyHash should be 20 bytes.
if (authFacts[msg.sender][_nonce] == bytes32(0)) {
authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash);
} else {
uint256 currentResetTimer = authFactsResetTimer[msg.sender][_nonce];
if (currentResetTimer == 0) {
authFactsResetTimer[msg.sender][_nonce] = block.timestamp;
} else {
require(block.timestamp.sub(currentResetTimer) >= AUTH_FACT_RESET_TIMELOCK, "z");
authFactsResetTimer[msg.sender][_nonce] = 0;
authFacts[msg.sender][_nonce] = keccak256(_pubkeyHash);
}
}
}
/// @notice Reverts unverified blocks
function revertBlocks(StoredBlockInfo[] memory _blocksToRevert) external {
requireActive();
governance.requireActiveValidator(msg.sender);
uint32 blocksCommitted = totalBlocksCommitted;
uint32 blocksToRevert = Utils.minU32(uint32(_blocksToRevert.length), blocksCommitted - totalBlocksExecuted);
uint64 revertedPriorityRequests = 0;
for (uint32 i = 0; i < blocksToRevert; ++i) {
StoredBlockInfo memory storedBlockInfo = _blocksToRevert[i];
require(storedBlockHashes[blocksCommitted] == hashStoredBlockInfo(storedBlockInfo), "r"); // incorrect stored block info
delete storedBlockHashes[blocksCommitted];
--blocksCommitted;
revertedPriorityRequests += storedBlockInfo.priorityOperations;
}
totalBlocksCommitted = blocksCommitted;
totalCommittedPriorityRequests -= revertedPriorityRequests;
if (totalBlocksCommitted < totalBlocksProven) {
totalBlocksProven = totalBlocksCommitted;
}
emit BlocksRevert(totalBlocksExecuted, blocksCommitted);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: UNLICENSED
/**
* @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);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Config.sol";
import "./Utils.sol";
import "./NFTFactory.sol";
import "./TokenGovernance.sol";
/// @title Governance Contract
/// @author Matter Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(address indexed token, uint16 indexed tokenId);
/// @notice Default nft factory has set
event SetDefaultNFTFactory(address indexed factory);
/// @notice NFT factory registered new creator account
event NFTFactoryRegisteredCreator(
uint32 indexed creatorAccountId,
address indexed creatorAddress,
address factoryAddress
);
/// @notice Governor changed
event NewGovernor(address newGovernor);
/// @notice Token Governance changed
event NewTokenGovernance(TokenGovernance newTokenGovernance);
/// @notice Validator's status changed
event ValidatorStatusUpdate(address indexed validatorAddress, bool isActive);
event TokenPausedUpdate(address indexed token, bool paused);
/// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades
address public networkGovernor;
/// @notice Total number of ERC20 tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice List of permitted validators
mapping(address => bool) public validators;
/// @notice Paused tokens list, deposits are impossible to create for paused tokens
mapping(uint16 => bool) public pausedTokens;
/// @notice Address that is authorized to add tokens to the Governance.
TokenGovernance public tokenGovernance;
/// @notice NFT Creator address to factory address mapping
mapping(uint32 => mapping(address => NFTFactory)) public nftFactories;
/// @notice Address which will be used if NFT token has no factories
NFTFactory public defaultFactory;
/// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external {
address _networkGovernor = abi.decode(initializationParameters, (address));
networkGovernor = _networkGovernor;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
// solhint-disable-next-line no-empty-blocks
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external {
requireGovernor(msg.sender);
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Change current token governance
/// @param _newTokenGovernance Address of the new token governor
function changeTokenGovernance(TokenGovernance _newTokenGovernance) external {
requireGovernor(msg.sender);
if (tokenGovernance != _newTokenGovernance) {
tokenGovernance = _newTokenGovernance;
emit NewTokenGovernance(_newTokenGovernance);
}
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
require(msg.sender == address(tokenGovernance), "1E");
require(tokenIds[_token] == 0, "1e"); // token exists
require(totalTokens < MAX_AMOUNT_OF_REGISTERED_TOKENS, "1f"); // no free identifiers for tokens
totalTokens++;
uint16 newTokenId = totalTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Pause token deposits for the given token
/// @param _tokenAddr Token address
/// @param _tokenPaused Token paused status
function setTokenPaused(address _tokenAddr, bool _tokenPaused) external {
requireGovernor(msg.sender);
uint16 tokenId = this.validateTokenAddress(_tokenAddr);
if (pausedTokens[tokenId] != _tokenPaused) {
pausedTokens[tokenId] = _tokenPaused;
emit TokenPausedUpdate(_tokenAddr, _tokenPaused);
}
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external {
requireGovernor(msg.sender);
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Check if specified address is is governor
/// @param _address Address to check
function requireGovernor(address _address) public view {
require(_address == networkGovernor, "1g"); // only by governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "1h"); // validator is not active
}
/// @notice Validate token id (must be less than or equal to total tokens amount)
/// @param _tokenId Token id
/// @return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return _tokenId <= totalTokens;
}
/// @notice Validate token address
/// @param _tokenAddr Token address
/// @return tokens id
function validateTokenAddress(address _tokenAddr) external view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "1i"); // 0 is not a valid token
return tokenId;
}
function packRegisterNFTFactoryMsg(
uint32 _creatorAccountId,
address _creatorAddress,
address _factoryAddress
) internal pure returns (bytes memory) {
return
abi.encodePacked(
"\x19Ethereum Signed Message:\n141",
"\nCreator's account ID in zkSync: ",
Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAccountId))),
"\nCreator: ",
Bytes.bytesToHexASCIIBytes(abi.encodePacked((_creatorAddress))),
"\nFactory: ",
Bytes.bytesToHexASCIIBytes(abi.encodePacked((_factoryAddress)))
);
}
/// @notice Register creator corresponding to the factory
/// @param _creatorAccountId Creator's zkSync account ID
/// @param _creatorAddress NFT creator address
/// @param _signature Creator's signature
function registerNFTFactoryCreator(
uint32 _creatorAccountId,
address _creatorAddress,
bytes memory _signature
) external {
require(address(nftFactories[_creatorAccountId][_creatorAddress]) == address(0), "Q");
bytes32 messageHash = keccak256(packRegisterNFTFactoryMsg(_creatorAccountId, _creatorAddress, msg.sender));
address recoveredAddress = Utils.recoverAddressFromEthSignature(_signature, messageHash);
require(recoveredAddress == _creatorAddress && recoveredAddress != address(0), "ws");
nftFactories[_creatorAccountId][_creatorAddress] = NFTFactory(msg.sender);
emit NFTFactoryRegisteredCreator(_creatorAccountId, _creatorAddress, msg.sender);
}
//@notice Set default factory for our contract. This factory will be used to mint an NFT token that has no factory
//@param _factory Address of NFT factory
function setDefaultNFTFactory(address _factory) external {
requireGovernor(msg.sender);
require(address(_factory) != address(0), "mb1"); // Factory should be non zero
require(address(defaultFactory) == address(0), "mb2"); // NFTFactory is already set
defaultFactory = NFTFactory(_factory);
emit SetDefaultNFTFactory(_factory);
}
function getNFTFactory(uint32 _creatorAccountId, address _creatorAddress) external view returns (NFTFactory) {
NFTFactory _factory = nftFactories[_creatorAccountId][_creatorAddress];
if (address(_factory) == address(0)) {
require(address(defaultFactory) != address(0), "fs"); // NFTFactory does not set
return defaultFactory;
} else {
return _factory;
}
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./KeysWithPlonkVerifier.sol";
import "./Config.sol";
// Hardcoded constants to avoid accessing store
contract Verifier is KeysWithPlonkVerifier, KeysWithPlonkVerifierOld, Config {
// solhint-disable-next-line no-empty-blocks
function initialize(bytes calldata) external {}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
// solhint-disable-next-line no-empty-blocks
function upgrade(bytes calldata upgradeParameters) external {}
function verifyAggregatedBlockProof(
uint256[] memory _recursiveInput,
uint256[] memory _proof,
uint8[] memory _vkIndexes,
uint256[] memory _individualVksInputs,
uint256[16] memory _subproofsLimbs
) external view returns (bool) {
for (uint256 i = 0; i < _individualVksInputs.length; ++i) {
uint256 commitment = _individualVksInputs[i];
_individualVksInputs[i] = commitment & INPUT_MASK;
}
VerificationKey memory vk = getVkAggregated(uint32(_vkIndexes.length));
return
verify_serialized_proof_with_recursion(
_recursiveInput,
_proof,
VK_TREE_ROOT,
VK_MAX_INDEX,
_vkIndexes,
_individualVksInputs,
_subproofsLimbs,
vk
);
}
function verifyExitProof(
bytes32 _rootHash,
uint32 _accountId,
address _owner,
uint32 _tokenId,
uint128 _amount,
uint32 _nftCreatorAccountId,
address _nftCreatorAddress,
uint32 _nftSerialId,
bytes32 _nftContentHash,
uint256[] calldata _proof
) external view returns (bool) {
bytes32 commitment =
sha256(
abi.encodePacked(
_rootHash,
_accountId,
_owner,
_tokenId,
_amount,
_nftCreatorAccountId,
_nftCreatorAddress,
_nftSerialId,
_nftContentHash
)
);
uint256[] memory inputs = new uint256[](1);
inputs[0] = uint256(commitment) & INPUT_MASK;
ProofOld memory proof = deserialize_proof_old(inputs, _proof);
VerificationKeyOld memory vk = getVkExit();
require(vk.num_inputs == inputs.length, "n1");
return verify_old(proof, vk);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: UNLICENSED
interface NFTFactory {
function mintNFTFromZkSync(
address creator,
address recipient,
uint32 creatorAccountId,
uint32 serialId,
bytes32 contentHash,
// Even though the token id can fit into the uint32, we still use
// the uint256 to preserve consistency with the ERC721 parent contract
uint256 tokenId
) external;
event MintNFTFromZkSync(
address indexed creator,
address indexed recipient,
uint32 creatorAccountId,
uint32 serialId,
bytes32 contentHash,
uint256 tokenId
);
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./Governance.sol";
import "./IERC20.sol";
import "./Utils.sol";
/// @title Token Governance Contract
/// @author Matter Labs
/// @notice Contract is used to allow anyone to add new ERC20 tokens to zkSync given sufficient payment
contract TokenGovernance {
/// @notice Token lister added or removed (see `tokenLister`)
event TokenListerUpdate(address indexed tokenLister, bool isActive);
/// @notice Listing fee token set
event ListingFeeTokenUpdate(IERC20 indexed newListingFeeToken);
/// @notice Listing fee set
event ListingFeeUpdate(uint256 newListingFee);
/// @notice Maximum number of listed tokens updated
event ListingCapUpdate(uint16 newListingCap);
/// @notice The treasury (the account which will receive the fee) was updated
event TreasuryUpdate(address newTreasury);
/// @notice zkSync governance contract
Governance public governance;
/// @notice Token used to collect listing fee for addition of new token to zkSync network
IERC20 public listingFeeToken;
/// @notice Token listing fee
uint256 public listingFee;
/// @notice Max number of tokens that can be listed using this contract
uint16 public listingCap;
/// @notice Addresses that can list tokens without fee
mapping(address => bool) public tokenLister;
/// @notice Address that collects listing payments
address public treasury;
constructor(
Governance _governance,
IERC20 _listingFeeToken,
uint256 _listingFee,
uint16 _listingCap,
address _treasury
) {
governance = _governance;
listingFeeToken = _listingFeeToken;
listingFee = _listingFee;
listingCap = _listingCap;
treasury = _treasury;
address governor = governance.networkGovernor();
// We add zkSync governor as a first token lister.
tokenLister[governor] = true;
emit TokenListerUpdate(governor, true);
}
/// @notice Adds new ERC20 token to zkSync network.
/// @notice If caller is not present in the `tokenLister` map payment of `listingFee` in `listingFeeToken` should be made.
/// @notice NOTE: before calling this function make sure to approve `listingFeeToken` transfer for this contract.
function addToken(address _token) external {
require(governance.totalTokens() < listingCap, "can't add more tokens"); // Impossible to add more tokens using this contract
if (!tokenLister[msg.sender]) {
// Collect fees
bool feeTransferOk = Utils.transferFromERC20(listingFeeToken, msg.sender, treasury, listingFee);
require(feeTransferOk, "fee transfer failed"); // Failed to receive payment for token addition.
}
governance.addToken(_token);
}
/// Governance functions (this contract is governed by zkSync governor)
/// @notice Set new listing token and fee
/// @notice Can be called only by zkSync governor
function setListingFeeToken(IERC20 _newListingFeeToken, uint256 _newListingFee) external {
governance.requireGovernor(msg.sender);
listingFeeToken = _newListingFeeToken;
listingFee = _newListingFee;
emit ListingFeeTokenUpdate(_newListingFeeToken);
}
/// @notice Set new listing fee
/// @notice Can be called only by zkSync governor
function setListingFee(uint256 _newListingFee) external {
governance.requireGovernor(msg.sender);
listingFee = _newListingFee;
emit ListingFeeUpdate(_newListingFee);
}
/// @notice Enable or disable token lister. If enabled new tokens can be added by that address without payment
/// @notice Can be called only by zkSync governor
function setLister(address _listerAddress, bool _active) external {
governance.requireGovernor(msg.sender);
if (tokenLister[_listerAddress] != _active) {
tokenLister[_listerAddress] = _active;
emit TokenListerUpdate(_listerAddress, _active);
}
}
/// @notice Change maximum amount of tokens that can be listed using this method
/// @notice Can be called only by zkSync governor
function setListingCap(uint16 _newListingCap) external {
governance.requireGovernor(msg.sender);
listingCap = _newListingCap;
emit ListingCapUpdate(_newListingCap);
}
/// @notice Change address that collects payments for listing tokens.
/// @notice Can be called only by zkSync governor
function setTreasury(address _newTreasury) external {
governance.requireGovernor(msg.sender);
treasury = _newTreasury;
emit TreasuryUpdate(_newTreasury);
}
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
import "./PlonkCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifier is VerifierWithDeserialize {
uint256 constant VK_TREE_ROOT = 0x12d3ca8e7e185734779f3969f1d0a9dbb357a737ed605c37c7157c341012e6d9;
uint8 constant VK_MAX_INDEX = 3;
function getVkAggregated(uint32 _proofs) internal pure returns (VerificationKey memory vk) {
if (_proofs == uint32(1)) { return getVkAggregated1(); }
else if (_proofs == uint32(4)) { return getVkAggregated4(); }
else if (_proofs == uint32(8)) { return getVkAggregated8(); }
}
function getVkAggregated1() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 4194304;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b,
0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e,
0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5,
0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7,
0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263,
0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474,
0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927,
0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c,
0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951,
0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3,
0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6,
0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899,
0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1,
0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated4() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 8388608;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1283ba6f4b7b1a76ba2008fe823128bea4adb9269cbfd7c41c223be65bc60863);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x2988e24b15bce9a1e3a4d1d9a8f7c7a65db6c29fd4c6f4afe1a3fbd954d4b4b6,
0x0bdb6e5ba27a22e03270c7c71399b866b28d7cec504d30e665d67be58e306e12
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x20f3d30d3a91a7419d658f8c035e42a811c9f75eac2617e65729033286d36089,
0x07ac91e8194eb78a9db537e9459dd6ca26bef8770dde54ac3dd396450b1d4cfe
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x0311872bab6df6e9095a9afe40b12e2ed58f00cc88835442e6b4cf73fb3e147d,
0x2cdfc5b5e73737809b54644b2f96494f8fcc1dd0fb440f64f44930b432c4542d
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x28fd545b1e960d2eff3142271affa4096ef724212031fdabe22dd4738f36472b,
0x2c743150ee9894ff3965d8f1129399a3b89a1a9289d4cfa904b0a648d3a8a9fa
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x2c283ce950eee1173b78657e57c80658a8398e7970a9a45b20cd39aff16ad61a,
0x081c003cbd09f7c3e0d723d6ebbaf432421c188d5759f5ee8ff1ee1dc357d4a8
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2eb50a2dd293a71a0c038e958c5237bd7f50b2f0c9ee6385895a553de1517d43,
0x15fdc2b5b28fc351f987b98aa6caec7552cefbafa14e6651061eec4f41993b65
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x17a9403e5c846c1ca5e767c89250113aa156fdb1f026aa0b4db59c09d06816ec,
0x2512241972ca3ee4839ac72a4cab39ddb413a7553556abd7909284b34ee73f6b
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x09edd69c8baa7928b16615e993e3032bc8cbf9f42bfa3cf28caba1078d371edb,
0x12e5c39148af860a87b14ae938f33eafa91deeb548cda4cc23ed9ba3e6e496b8
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x0e25c0027706ca3fd3daae849f7c50ec88d4d030da02452001dec7b554cc71b4,
0x2421da0ca385ff7ba9e5ae68890655669248c8c8187e67d12b2a7ae97e2cff8b
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x151536359fe184567bce57379833f6fae485e5cc9bc27423d83d281aaf2701df,
0x116beb145bc27faae5a8ae30c28040d3baafb3ea47360e528227b94adb9e4f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x23ee338093db23364a6e44acfb60d810a4c4bd6565b185374f7840152d3ae82c,
0x0f6714f3ee113b9dfb6b653f04bf497602588b16b96ac682d9a5dd880a0aa601
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x05860b0ea3c6f22150812aee304bf35e1a95cfa569a8da52b42dba44a122378a,
0x19e5a9f3097289272e65e842968752c5355d1cdb2d3d737050e4dfe32ebe1e41
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x3046881fcbe369ac6f99fea8b9505de85ded3de3bc445060be4bc6ef651fa352,
0x06fe14c1dd6c2f2b48aebeb6fd525573d276b2e148ad25e75c57a58588f755ec
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated8() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 16777216;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x218bdb295b7207114aeea948e2d3baef158d4057812f94005d8ff54341b6ce6f,
0x1398585c039ba3cf336687301e95fbbf6b0638d31c64b1d815bb49091d0c1aad
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x2e40b8a98e688c9e00f607a64520a850d35f277dc0b645628494337bb75870e8,
0x2da4ef753cc4869e53cff171009dbffea9166b8ffbafd17783d712278a79f13e
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1b638de3c6cc2e0badc48305ee3533678a45f52edf30277303551128772303a2,
0x2794c375cbebb7c28379e8abf42d529a1c291319020099935550c83796ba14ac
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x189cd01d67b44cf2c1e10765c69adaafd6a5929952cf55732e312ecf00166956,
0x15976c99ef2c911bd3a72c9613b7fe9e66b03dd8963bfed705c96e3e88fdb1af
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x0745a77052dc66afc61163ec3737651e5b846ca7ec7fae1853515d0f10a51bd9,
0x2bd27ecf4fb7f5053cc6de3ddb7a969fac5150a6fb5555ca917d16a7836e4c0a
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x2787aea173d07508083893b02ea962be71c3b628d1da7d7c4db0def49f73ad8f,
0x22fdc951a97dc2ac7d8292a6c263898022f4623c643a56b9265b33c72e628886
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x0aafe35c49634858e44e9af259cac47a6f8402eb870f9f95217dcb8a33a73e64,
0x1b47a7641a7c918784e84fc2494bfd8014ebc77069b94650d25cb5e25fbb7003
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x11cfc3fe28dfd5d663d53ceacc5ec620da85ae5aa971f0f003f57e75cd05bf9f,
0x28b325f30984634fc46c6750f402026d4ff43e5325cbe34d35bf8ac4fc9cc533
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x2ada816636b9447def36e35dd3ab0e3f7a8bbe3ae32a5a4904dee3fc26e58015,
0x2cd12d1a50aaadef4e19e1b1955c932e992e688c2883da862bd7fad17aae66f6
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x20cc506f273be4d114cbf2807c14a769d03169168892e2855cdfa78c3095c89d,
0x08f99d338aee985d780d036473c624de9fd7960b2a4a7ad361c8c125cf11899e
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x01260265d3b1167eac1030f3d04326f08a1f2bb1e026e54afec844e3729386e2,
0x16d75b53ec2552c63e84ea5f4bfe1507c3198045875457c1d9295d6699f39d56
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x1f4d73c63d163c3f5ef1b5caa41988cacbdbca38334e8f54d7ee9bbbb622e200,
0x2f48f5f93d9845526ef0348f1c3def63cfc009645eb2a95d1746c7941e888a78
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x1dbd386fe258366222becc570a7f6405b25ff52818b93bdd54eaa20a6b22025a,
0x2b2b4e978ac457d752f50b02609bd7d2054286b963821b2ec7cd3dd1507479fa
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkVerifierOld is VerifierWithDeserializeOld {
function getVkExit() internal pure returns(VerificationKeyOld memory vk) {
vk.domain_size = 524288;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0cf1526aaafac6bacbb67d11a4077806b123f767e4b0883d14cc0193568fc082);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x114dd473f77a15b602201577dd4b64a32a783cb32fbc02911e512df6a219695d,
0x04c68f82a5dd7d0cc90318bdff493b3d552d148ad859c373ffe55275e043c43b
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x245e8c882af503cb5421f5135b4295a920ccf68b42ae7fb967f044f54e2aaa29,
0x071322ee387a9ce49fe7ef2edb6e9237203dee49ec47483af85e356b79fb06fd
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x0187754ab593b07a420b3b4d215c20ed49acf90fc4c97e4b06e8f5bc0a2eb3f4,
0x0170f9286ce950286a16ea25136c163c0b32019f31b89c256a612d40b863d0b6
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x0defecfae1d2b9ec9b2ee4d4798c625fa50f6a4ddb7747a7293df0c17fcb90c2,
0x0f91d08fceebf85fb80f12cda78cefa1ee9dbf5cfe7c4f0704b3c6620fa50c55
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x2f7fef3b3fb64af6640f93803a18b3e5ce4e0e60aecd4f924c833fa6fa6da961,
0x03908fc737113ac7f3529fe3b36efca200c66d1d85d2fc081973214c586de732
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x14ce3c0e9b78fc331327249e707f58fa4bb0ed746bdc9c2262ad0cf905609627,
0x09e64fdac452b424e98fc4a92f7222693d0d84ab48aadd9c46151dbe5f1a34a9
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x1d10bfd923c17d9623ec02db00099355b373021432ae1edef69b0f5f461f78d6,
0x24e370a93f65f42888781d0158bb6ef9136c8bbd047d7993b8276bc8df8b640a
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x1fd1755ed4d06d91d50db4771d332cfa2bc2ca0e10ac8b77e0d6b73b993e788e,
0x0bdbf3b7f0d3cffdcf818f1fba18b90914eda59b454bd1858c6c0916b817f883
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x1f3b8d12ffa2ceb2bb42d232ad2cf11bce3183472b622e11cc841d26f42ad507,
0x0ce815e32b3bd14311cde210cda1bd351617d539ed3e9d96a8605f364f3a29b0
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x123afa8c1cec1956d7330db062498a2a3e3a9862926c02e1228d9cfb63d3c301,
0x0f5af15ff0a3e35486c541f72956b53ff6d0740384ef6463c866146c1bd2afc8
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x01069e38ea6396af1623921101d3d3d14ee46942fb23bf1d110efb994c3ee573,
0x232a8ce7151e69601a7867f9dcac8e2de4dd8352d119c90bbb0fb84720c02513
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1, 0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4, 0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT OR Apache-2.0
// solhint-disable
library PairingsBn254 {
uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant bn254_b_coeff = 3;
struct G1Point {
uint256 X;
uint256 Y;
}
struct Fr {
uint256 value;
}
function new_fr(uint256 fr) internal pure returns (Fr memory) {
require(fr < r_mod);
return Fr({value: fr});
}
function copy(Fr memory self) internal pure returns (Fr memory n) {
n.value = self.value;
}
function assign(Fr memory self, Fr memory other) internal pure {
self.value = other.value;
}
function inverse(Fr memory fr) internal view returns (Fr memory) {
require(fr.value != 0);
return pow(fr, r_mod - 2);
}
function add_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, other.value, r_mod);
}
function sub_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, r_mod - other.value, r_mod);
}
function mul_assign(Fr memory self, Fr memory other) internal pure {
self.value = mulmod(self.value, other.value, r_mod);
}
function pow(Fr memory self, uint256 power) internal view returns (Fr memory) {
uint256[6] memory input = [32, 32, 32, self.value, power, r_mod];
uint256[1] memory result;
bool success;
assembly {
success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20)
}
require(success);
return Fr({value: result[0]});
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint256[2] X;
uint256[2] Y;
}
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) {
return G1Point(x, y);
}
function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) {
if (x == 0 && y == 0) {
// point of infinity is (0,0)
return G1Point(x, y);
}
// check encoding
require(x < q_mod);
require(y < q_mod);
// check on curve
uint256 lhs = mulmod(y, y, q_mod); // y^2
uint256 rhs = mulmod(x, x, q_mod); // x^2
rhs = mulmod(rhs, x, q_mod); // x^3
rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b
require(lhs == rhs);
return G1Point(x, y);
}
function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) {
return G2Point(x, y);
}
function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) {
result.X = self.X;
result.Y = self.Y;
}
function P2() internal pure returns (G2Point memory) {
// for some reason ethereum expects to have c1*v + c0 form
return
G2Point(
[
0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed
],
[
0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
]
);
}
function negate(G1Point memory self) internal pure {
// The prime q in the base field F_q for G1
if (self.Y == 0) {
require(self.X == 0);
return;
}
self.Y = q_mod - self.Y;
}
function point_add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) {
point_add_into_dest(p1, p2, r);
return r;
}
function point_add_assign(G1Point memory p1, G1Point memory p2) internal view {
point_add_into_dest(p1, p2, p1);
}
function point_add_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we add zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we add into zero, and we add non-zero point
dest.X = p2.X;
dest.Y = p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_sub_assign(G1Point memory p1, G1Point memory p2) internal view {
point_sub_into_dest(p1, p2, p1);
}
function point_sub_into_dest(
G1Point memory p1,
G1Point memory p2,
G1Point memory dest
) internal view {
if (p2.X == 0 && p2.Y == 0) {
// we subtracted zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we subtract from zero, and we subtract non-zero point
dest.X = p2.X;
dest.Y = q_mod - p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = q_mod - p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_mul(G1Point memory p, Fr memory s) internal view returns (G1Point memory r) {
point_mul_into_dest(p, s, r);
return r;
}
function point_mul_assign(G1Point memory p, Fr memory s) internal view {
point_mul_into_dest(p, s, p);
}
function point_mul_into_dest(
G1Point memory p,
Fr memory s,
G1Point memory dest
) internal view {
uint256[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s.value;
bool success;
assembly {
success := staticcall(gas(), 7, input, 0x60, dest, 0x40)
}
require(success);
}
function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) {
require(p1.length == p2.length);
uint256 elements = p1.length;
uint256 inputSize = elements * 6;
uint256[] memory input = new uint256[](inputSize);
for (uint256 i = 0; i < elements; i++) {
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint256[1] memory out;
bool success;
assembly {
success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(
G1Point memory a1,
G2Point memory a2,
G1Point memory b1,
G2Point memory b2
) internal view returns (bool) {
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
}
library TranscriptLibrary {
// flip 0xe000000000000000000000000000000000000000000000000000000000000000;
uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint32 constant DST_0 = 0;
uint32 constant DST_1 = 1;
uint32 constant DST_CHALLENGE = 2;
struct Transcript {
bytes32 state_0;
bytes32 state_1;
uint32 challenge_counter;
}
function new_transcript() internal pure returns (Transcript memory t) {
t.state_0 = bytes32(0);
t.state_1 = bytes32(0);
t.challenge_counter = 0;
}
function update_with_u256(Transcript memory self, uint256 value) internal pure {
bytes32 old_state_0 = self.state_0;
self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value));
self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value));
}
function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure {
update_with_u256(self, value.value);
}
function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure {
update_with_u256(self, p.X);
update_with_u256(self, p.Y);
}
function get_challenge(Transcript memory self) internal pure returns (PairingsBn254.Fr memory challenge) {
bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter));
self.challenge_counter += 1;
challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK});
}
}
contract Plonk4VerifierWithAccessToDNext {
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant ZERO = 0;
uint256 constant ONE = 1;
uint256 constant TWO = 2;
uint256 constant THREE = 3;
uint256 constant FOUR = 4;
uint256 constant STATE_WIDTH = 4;
uint256 constant NUM_DIFFERENT_GATES = 2;
uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7;
uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1;
uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK =
0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant LIMB_WIDTH = 68;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments;
PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH - 1] copy_permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point copy_permutation_grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z;
PairingsBn254.Fr copy_grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length - 1; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(dens[i]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
dens[i].assign(tmp_2); // all inversed
dens[i].mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
inputs_term.add_assign(tmp);
}
inputs_term.mul_assign(proof.gate_selector_values_at_z[0]);
rhs.add_assign(inputs_term);
// now we need 5th power
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function add_contribution_from_range_constraint_gates(
PartialVerifierState memory state,
Proof memory proof,
PairingsBn254.Fr memory current_alpha
) internal pure returns (PairingsBn254.Fr memory res) {
// now add contribution from range constraint gate
// we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {})
PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE);
PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO);
PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE);
PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR);
res = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < 3; i++) {
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
}
// now also d_next - 4a
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[0]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
return res;
}
function reconstruct_linearization_commitment(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^{6} * (selector(x) - selector(z))
// + v^{7..9} * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^10 (z(x) - z(z*omega)) <- we need this power
// + v^11 * (d(x) - d(z*omega))
// ]
//
// we reconstruct linearization polynomial virtual selector
// for that purpose we first linearize over main gate (over all it's selectors)
// and multiply them by value(!) of the corresponding main gate selector
res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x)
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH + 2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x)
res.point_add_assign(tmp_g1);
// multiply by main gate selector(z)
res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector
PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE);
// calculate scalar contribution from the range check gate
tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha);
tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar
res.point_add_assign(tmp_g1);
// proceed as normal to copy permutation
current_alpha.mul_assign(state.alpha); // alpha^5
PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(alpha_for_grand_product);
// alpha^n & L_{0}(z), and we bump current_alpha
current_alpha.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(current_alpha);
grand_product_part_at_z.add_assign(tmp_fr);
// prefactor for grand_product(x) is complete
// add to the linearization a part from the term
// - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X)
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument
// actually multiply prefactors by z(x) and perm_d(x) and combine them
tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
// multiply them by v immedately as linearization has a factor of v^1
res.point_mul_assign(state.v);
// res now contains contribution from the gates linearization and
// copy permutation part
// now we need to add a part that is the rest
// for z(x*omega):
// - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega)
}
function aggregate_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point[2] memory res) {
PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.gate_selector_commitments[0].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.copy_permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
// now do prefactor for grand_product(x*omega)
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr));
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.gate_selector_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.copy_grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
res[0] = pair_with_generator;
res[1] = pair_with_x;
return res;
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.copy_permutation_grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
transcript.update_with_fr(proof.gate_selector_values_at_z[0]);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.copy_grand_product_at_z_omega);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function aggregate_for_verification(Proof memory proof, VerificationKey memory vk)
internal
view
returns (bool valid, PairingsBn254.G1Point[2] memory part)
{
PartialVerifierState memory state;
valid = verify_initial(state, proof, vk);
if (valid == false) {
return (valid, part);
}
part = aggregate_commitments(state, proof, vk);
(valid, part);
}
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
valid = PairingsBn254.pairingProd2(
recursive_proof_part[0],
PairingsBn254.P2(),
recursive_proof_part[1],
vk.g2_x
);
return valid;
}
function verify_recursive(
Proof memory proof,
VerificationKey memory vk,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs
) internal view returns (bool) {
(uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) =
reconstruct_recursive_public_input(
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
assert(recursive_input == proof.input_values[0]);
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
// aggregated_g1s = inner
// recursive_proof_part = outer
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part);
valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x);
return valid;
}
function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer)
internal
view
returns (PairingsBn254.G1Point[2] memory result)
{
// reuse the transcript primitive
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
transcript.update_with_g1(inner[0]);
transcript.update_with_g1(inner[1]);
transcript.update_with_g1(outer[0]);
transcript.update_with_g1(outer[1]);
PairingsBn254.Fr memory challenge = transcript.get_challenge();
// 1 * inner + challenge * outer
result[0] = PairingsBn254.copy_g1(inner[0]);
result[1] = PairingsBn254.copy_g1(inner[1]);
PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge);
result[0].point_add_assign(tmp);
tmp = outer[1].point_mul(challenge);
result[1].point_add_assign(tmp);
return result;
}
function reconstruct_recursive_public_input(
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_aggregated
) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) {
assert(recursive_vks_indexes.length == individual_vks_inputs.length);
bytes memory concatenated = abi.encodePacked(recursive_vks_root);
uint8 index;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
index = recursive_vks_indexes[i];
assert(index <= max_valid_index);
concatenated = abi.encodePacked(concatenated, index);
}
uint256 input;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
input = individual_vks_inputs[i];
assert(input < r_mod);
concatenated = abi.encodePacked(concatenated, input);
}
concatenated = abi.encodePacked(concatenated, subproofs_aggregated);
bytes32 commitment = sha256(concatenated);
recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK;
reconstructed_g1s[0] = PairingsBn254.new_g1_checked(
subproofs_aggregated[0] +
(subproofs_aggregated[1] << LIMB_WIDTH) +
(subproofs_aggregated[2] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[3] << (3 * LIMB_WIDTH)),
subproofs_aggregated[4] +
(subproofs_aggregated[5] << LIMB_WIDTH) +
(subproofs_aggregated[6] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[7] << (3 * LIMB_WIDTH))
);
reconstructed_g1s[1] = PairingsBn254.new_g1_checked(
subproofs_aggregated[8] +
(subproofs_aggregated[9] << LIMB_WIDTH) +
(subproofs_aggregated[10] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[11] << (3 * LIMB_WIDTH)),
subproofs_aggregated[12] +
(subproofs_aggregated[13] << LIMB_WIDTH) +
(subproofs_aggregated[14] << (2 * LIMB_WIDTH)) +
(subproofs_aggregated[15] << (3 * LIMB_WIDTH))
);
return (recursive_input, reconstructed_g1s);
}
}
contract VerifierWithDeserialize is Plonk4VerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 34;
function deserialize_proof(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (Proof memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
function verify_serialized_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify(proof, vk);
return valid;
}
function verify_serialized_proof_with_recursion(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[16] memory subproofs_limbs,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid =
verify_recursive(
proof,
vk,
recursive_vks_root,
max_valid_index,
recursive_vks_indexes,
individual_vks_inputs,
subproofs_limbs
);
return valid;
}
}
contract Plonk4VerifierWithAccessToDNextOld {
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant STATE_WIDTH_OLD = 4;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD = 1;
struct VerificationKeyOld {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[STATE_WIDTH_OLD + 2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant
PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] next_step_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH_OLD] permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct ProofOld {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH_OLD] wire_commitments;
PairingsBn254.G1Point grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH_OLD] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH_OLD] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP_OLD] wire_values_at_z_omega;
PairingsBn254.Fr grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH_OLD - 1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierStateOld {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain_old(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function batch_evaluate_lagrange_poly_out_of_domain_old(
uint256[] memory poly_nums,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr[] memory res) {
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory tmp_1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory tmp_2 = PairingsBn254.new_fr(domain_size);
PairingsBn254.Fr memory vanishing_at_z = at.pow(domain_size);
vanishing_at_z.sub_assign(one);
// we can not have random point z be in domain
require(vanishing_at_z.value != 0);
PairingsBn254.Fr[] memory nums = new PairingsBn254.Fr[](poly_nums.length);
PairingsBn254.Fr[] memory dens = new PairingsBn254.Fr[](poly_nums.length);
// numerators in a form omega^i * (z^n - 1)
// denoms in a form (z - omega^i) * N
for (uint256 i = 0; i < poly_nums.length; i++) {
tmp_1 = omega.pow(poly_nums[i]); // power of omega
nums[i].assign(vanishing_at_z);
nums[i].mul_assign(tmp_1);
dens[i].assign(at); // (X - omega^i) * N
dens[i].sub_assign(tmp_1);
dens[i].mul_assign(tmp_2); // mul by domain size
}
PairingsBn254.Fr[] memory partial_products = new PairingsBn254.Fr[](poly_nums.length);
partial_products[0].assign(PairingsBn254.new_fr(1));
for (uint256 i = 1; i < dens.length - 1; i++) {
partial_products[i].assign(dens[i - 1]);
partial_products[i].mul_assign(dens[i]);
}
tmp_2.assign(partial_products[partial_products.length - 1]);
tmp_2.mul_assign(dens[dens.length - 1]);
tmp_2 = tmp_2.inverse(); // tmp_2 contains a^-1 * b^-1 (with! the last one)
for (uint256 i = dens.length - 1; i < dens.length; i--) {
dens[i].assign(tmp_2); // all inversed
dens[i].mul_assign(partial_products[i]); // clear lowest terms
tmp_2.mul_assign(dens[i]);
}
for (uint256 i = 0; i < nums.length; i++) {
nums[i].mul_assign(dens[i]);
}
return nums;
}
function evaluate_vanishing_old(uint256 domain_size, PairingsBn254.Fr memory at)
internal
view
returns (PairingsBn254.Fr memory res)
{
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing_old(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
rhs.add_assign(tmp);
}
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH_OLD - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function reconstruct_d(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^(6..8) * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^9 (z(x) - z(z*omega)) <- we need this power
// + v^10 * (d(x) - d(z*omega))
// ]
//
// we pay a little for a few arithmetic operations to not introduce another constant
uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH_OLD + STATE_WIDTH_OLD - 1;
res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH_OLD + 1]);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.selector_commitments[STATE_WIDTH_OLD].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]);
res.point_add_assign(tmp_g1);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i + 1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(state.alpha);
tmp_fr.mul_assign(state.alpha);
grand_product_part_at_z.add_assign(tmp_fr);
PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening);
grand_product_part_at_z_omega.mul_assign(state.u);
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(state.alpha);
// add to the linearization
tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH_OLD - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
res.point_mul_assign(state.v);
res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega));
}
function verify_commitments(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint256 i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint256 i = 0; i < vk.permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH_OLD - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x);
}
function verify_initial(
PartialVerifierStateOld memory state,
ProofOld memory proof,
VerificationKeyOld memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs >= 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
uint256[] memory lagrange_poly_numbers = new uint256[](vk.num_inputs);
for (uint256 i = 0; i < lagrange_poly_numbers.length; i++) {
lagrange_poly_numbers[i] = i;
}
state.cached_lagrange_evals = batch_evaluate_lagrange_poly_out_of_domain_old(
lagrange_poly_numbers,
vk.domain_size,
vk.omega,
state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
transcript.update_with_fr(proof.grand_product_at_z_omega);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function verify_old(ProofOld memory proof, VerificationKeyOld memory vk) internal view returns (bool) {
PartialVerifierStateOld memory state;
bool valid = verify_initial(state, proof, vk);
if (valid == false) {
return false;
}
valid = verify_commitments(state, proof, vk);
return valid;
}
}
contract VerifierWithDeserializeOld is Plonk4VerifierWithAccessToDNextOld {
uint256 constant SERIALIZED_PROOF_LENGTH_OLD = 33;
function deserialize_proof_old(uint256[] memory public_inputs, uint256[] memory serialized_proof)
internal
pure
returns (ProofOld memory proof)
{
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH_OLD);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
}
proof.grand_product_commitment = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j + 1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH_OLD; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.grand_product_at_z_omega = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(serialized_proof[j]);
j += 1;
}
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(serialized_proof[j], serialized_proof[j + 1]);
}
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Interface of the upgradeable contract
/// @author Matter Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
}
pragma solidity ^0.7.0;
// SPDX-License-Identifier: MIT OR Apache-2.0
/// @title Ownable Contract
/// @author Matter Labs
contract Ownable {
/// @dev Storage position of the masters address (keccak256('eip1967.proxy.admin') - 1)
bytes32 private constant MASTER_POSITION = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/// @notice Contract constructor
/// @dev Sets msg sender address as masters address
/// @param masterAddress Master address
constructor(address masterAddress) {
setMaster(masterAddress);
}
/// @notice Check if specified address is master
/// @param _address Address to check
function requireMaster(address _address) internal view {
require(_address == getMaster(), "1c"); // oro11 - only by master
}
/// @notice Returns contract masters address
/// @return master Master's address
function getMaster() public view returns (address master) {
bytes32 position = MASTER_POSITION;
assembly {
master := sload(position)
}
}
/// @dev Sets new masters address
/// @param _newMaster New master's address
function setMaster(address _newMaster) internal {
bytes32 position = MASTER_POSITION;
assembly {
sstore(position, _newMaster)
}
}
/// @notice Transfer mastership of the contract to new master
/// @param _newMaster New masters address
function transferMastership(address _newMaster) external {
requireMaster(msg.sender);
require(_newMaster != address(0), "1d"); // otp11 - new masters address can't be zero address
setMaster(_newMaster);
}
}
|
The code below is equivalent to `commitment = sha256(abi.encodePacked(hash, _publicData))` We use inline assembly instead of this concise and readable code in order to avoid copying of `_publicData` (which saves ~90 gas per transfer operation). Specifically, we perform the following trick: First, replace the first 32 bytes of `_publicData` (where normally its length is stored) with the value of `hash`. Then, we call `sha256` precompile passing the `_publicData` pointer and the length of the concatenated byte buffer. Finally, we put the `_publicData.length` back to its original location (to the first word of `_publicData`). staticcall to the sha256 precompile at address 0x2 Use "invalid" to make gas estimation work
|
function verifyChangePubkeyECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk)
internal
pure
returns (bool)
}
function verifyChangePubkeyECRECOVERV2(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk)
internal
pure
returns (bool)
}
function verifyChangePubkeyOldECRECOVER(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk)
internal
pure
returns (bool)
}
function verifyChangePubkeyCREATE2(bytes memory _ethWitness, Operations.ChangePubKey memory _changePk)
internal
pure
returns (bool)
}
function createBlockCommitment(
StoredBlockInfo memory _previousBlock,
CommitBlockInfo memory _newBlockData,
bytes memory _offsetCommitment
assembly {
let hashResult := mload(0x40)
let pubDataLen := mload(pubdata)
mstore(pubdata, hash)
let success := staticcall(gas(), 0x2, pubdata, add(pubDataLen, 0x20), hashResult, 0x20)
mstore(pubdata, pubDataLen)
switch success
case 0 {
invalid()
}
commitment := mload(hashResult)
}
| 14,711,027
|
./partial_match/1/0x067C5714f9c034fda974f909591c75A710C8f6eb/sources/MULTINFT_METAVERSE_NIGHTS.sol
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./
|
function _burn(address from, uint256 id, uint256 amount, bool approvalCheck) internal virtual {
if (approvalCheck == true) {
if (from != msg.sender) {
if (_operatorApprovals[from][msg.sender] == false) {
_revert(TransferCallerNotOwnerNorApproved.selector);
}
}
}
uint256 fromAddressData = _packedAddressData[from][id];
if ((fromAddressData & _BITMASK_DATA_ENTRY) < amount) _revert(InsufficientBalance.selector);
unchecked {
_packedAddressData[from][id] = fromAddressData - amount + (amount << _BITPOS_NUMBER_BURNED);
_packedTokenMetadata[id] += (amount << _BITPOS_NUMBER_BURNED);
}
emit TransferSingle(msg.sender, from, _ADDRESS_ZERO, id, amount);
}
| 9,130,780
|
pragma solidity 0.5.12;
contract BColor {
function getColor()
external view
returns (bytes32);
}
contract BBronze is BColor {
function getColor()
external view
returns (bytes32) {
return bytes32("BRONZE");
}
}
contract BConst is BBronze {
uint public constant BONE = 10**18;
uint public constant MIN_BOUND_TOKENS = 2;
uint public constant MAX_BOUND_TOKENS = 8;
uint public constant MIN_FEE = BONE / 40000; // MIN_FEE = 0.0025%
uint public constant MAX_FEE = BONE / 10; // MAX_FEE = 10%
uint public constant EXIT_FEE = 0;
uint public constant DEFAULT_RESERVES_RATIO = BONE / 5;
uint public constant MIN_WEIGHT = BONE;
uint public constant MAX_WEIGHT = BONE * 50;
uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint public constant MIN_BALANCE = BONE / 10**12;
uint public constant INIT_POOL_SUPPLY = BONE * 100;
uint public constant MIN_BPOW_BASE = 1 wei;
uint public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint public constant BPOW_PRECISION = BONE / 10**10;
uint public constant MAX_IN_RATIO = BONE / 2;
uint public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
contract BFactory is BBronze {
event LOG_NEW_POOL(
address indexed caller,
address indexed pool
);
event LOG_BLABS(
address indexed caller,
address indexed blabs
);
event LOG_RESERVES_ADDRESS(
address indexed caller,
address indexed reservesAddress
);
event LOG_ALLOW_NON_ADMIN_POOL(
address indexed caller,
bool allow
);
mapping(address=>bool) private _isBPool;
function isBPool(address b)
external view returns (bool)
{
return _isBPool[b];
}
function newBPool()
external
returns (BPool)
{
if (!_allowNonAdminPool) {
require(msg.sender == _blabs);
}
BPool bpool = new BPool();
_isBPool[address(bpool)] = true;
emit LOG_NEW_POOL(msg.sender, address(bpool));
bpool.setController(msg.sender);
return bpool;
}
address private _blabs;
address private _reservesAddress;
bool private _allowNonAdminPool;
constructor() public {
_blabs = msg.sender;
_reservesAddress = msg.sender;
_allowNonAdminPool = false;
}
function getAllowNonAdminPool()
external view
returns (bool)
{
return _allowNonAdminPool;
}
function setAllowNonAdminPool(bool b)
external
{
require(msg.sender == _blabs, "ERR_NOT_BLABS");
emit LOG_ALLOW_NON_ADMIN_POOL(msg.sender, b);
_allowNonAdminPool = b;
}
function getBLabs()
external view
returns (address)
{
return _blabs;
}
function setBLabs(address b)
external
{
require(msg.sender == _blabs);
emit LOG_BLABS(msg.sender, b);
_blabs = b;
}
function getReservesAddress()
external view
returns (address)
{
return _reservesAddress;
}
function setReservesAddress(address a)
external
{
require(msg.sender == _blabs);
emit LOG_RESERVES_ADDRESS(msg.sender, a);
_reservesAddress = a;
}
function collect(BPool pool)
external
{
require(msg.sender == _blabs);
require(_isBPool[address(pool)]);
uint collected = IERC20(pool).balanceOf(address(this));
bool xfer = pool.transfer(_blabs, collected);
require(xfer);
}
function collectTokenReserves(BPool pool)
external
{
require(msg.sender == _blabs);
require(_isBPool[address(pool)]);
pool.drainTotalReserves(_reservesAddress);
}
}
contract BNum is BConst {
function btoi(uint a)
internal pure
returns (uint)
{
return a / BONE;
}
function bfloor(uint a)
internal pure
returns (uint)
{
return btoi(a) * BONE;
}
function badd(uint a, uint b)
internal pure
returns (uint)
{
uint c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
function bsub(uint a, uint b)
internal pure
returns (uint)
{
(uint c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint a, uint b)
internal pure
returns (uint, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint a, uint b)
internal pure
returns (uint)
{
uint c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint c2 = c1 / BONE;
return c2;
}
function bdiv(uint a, uint b)
internal pure
returns (uint)
{
require(b != 0, "ERR_DIV_ZERO");
uint c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint c2 = c1 / b;
return c2;
}
// DSMath.wpow
function bpowi(uint a, uint n)
internal pure
returns (uint)
{
uint z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint base, uint exp)
internal pure
returns (uint)
{
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint whole = bfloor(exp);
uint remain = bsub(exp, whole);
uint wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint partialResult = bpowApprox(base, remain, BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(uint base, uint exp, uint precision)
internal pure
returns (uint)
{
// term 0:
uint a = exp;
(uint x, bool xneg) = bsubSign(base, BONE);
uint term = BONE;
uint sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint i = 1; term >= precision; i++) {
uint bigK = i * BONE;
(uint c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
}
interface IERC20 {
event Approval(address indexed src, address indexed dst, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
function totalSupply() external view returns (uint);
function balanceOf(address whom) external view returns (uint);
function allowance(address src, address dst) external view returns (uint);
function approve(address dst, uint amt) external returns (bool);
function transfer(address dst, uint amt) external returns (bool);
function transferFrom(
address src, address dst, uint amt
) external returns (bool);
}
contract BTokenBase is BNum {
mapping(address => uint) internal _balance;
mapping(address => mapping(address=>uint)) internal _allowance;
uint internal _totalSupply;
event Approval(address indexed src, address indexed dst, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
function _mint(uint amt) internal {
_balance[address(this)] = badd(_balance[address(this)], amt);
_totalSupply = badd(_totalSupply, amt);
emit Transfer(address(0), address(this), amt);
}
function _burn(uint amt) internal {
require(_balance[address(this)] >= amt);
_balance[address(this)] = bsub(_balance[address(this)], amt);
_totalSupply = bsub(_totalSupply, amt);
emit Transfer(address(this), address(0), amt);
}
function _move(address src, address dst, uint amt) internal {
require(_balance[src] >= amt);
_balance[src] = bsub(_balance[src], amt);
_balance[dst] = badd(_balance[dst], amt);
emit Transfer(src, dst, amt);
}
function _push(address to, uint amt) internal {
_move(address(this), to, amt);
}
function _pull(address from, uint amt) internal {
_move(from, address(this), amt);
}
}
contract BToken is BTokenBase, IERC20 {
string private _name = "Cream Pool Token";
string private _symbol = "CRPT";
uint8 private _decimals = 18;
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns(uint8) {
return _decimals;
}
function allowance(address src, address dst) external view returns (uint) {
return _allowance[src][dst];
}
function balanceOf(address whom) external view returns (uint) {
return _balance[whom];
}
function totalSupply() public view returns (uint) {
return _totalSupply;
}
function approve(address dst, uint amt) external returns (bool) {
_allowance[msg.sender][dst] = amt;
emit Approval(msg.sender, dst, amt);
return true;
}
function increaseApproval(address dst, uint amt) external returns (bool) {
_allowance[msg.sender][dst] = badd(_allowance[msg.sender][dst], amt);
emit Approval(msg.sender, dst, _allowance[msg.sender][dst]);
return true;
}
function decreaseApproval(address dst, uint amt) external returns (bool) {
uint oldValue = _allowance[msg.sender][dst];
if (amt > oldValue) {
_allowance[msg.sender][dst] = 0;
} else {
_allowance[msg.sender][dst] = bsub(oldValue, amt);
}
emit Approval(msg.sender, dst, _allowance[msg.sender][dst]);
return true;
}
function transfer(address dst, uint amt) external returns (bool) {
_move(msg.sender, dst, amt);
return true;
}
function transferFrom(address src, address dst, uint amt) external returns (bool) {
require(msg.sender == src || amt <= _allowance[src][msg.sender]);
_move(src, dst, amt);
if (msg.sender != src && _allowance[src][msg.sender] != uint256(-1)) {
_allowance[src][msg.sender] = bsub(_allowance[src][msg.sender], amt);
emit Approval(msg.sender, dst, _allowance[src][msg.sender]);
}
return true;
}
}
contract BMath is BBronze, BConst, BNum {
/**********************************************************************************************
// calcSpotPrice //
// sP = spotPrice //
// bI = tokenBalanceIn ( bI / wI ) 1 //
// bO = tokenBalanceOut sP = ----------- * ---------- //
// wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcSpotPrice(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint swapFee
)
public pure
returns (uint spotPrice)
{
uint numer = bdiv(tokenBalanceIn, tokenWeightIn);
uint denom = bdiv(tokenBalanceOut, tokenWeightOut);
uint ratio = bdiv(numer, denom);
uint scale = bdiv(BONE, bsub(BONE, swapFee));
return (spotPrice = bmul(ratio, scale));
}
/**********************************************************************************************
// calcOutGivenIn //
// aO = tokenAmountOut //
// bO = tokenBalanceOut //
// bI = tokenBalanceIn / / bI \ (wI / wO) \ //
// aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcOutGivenIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountIn,
uint swapFee
)
public pure
returns (uint tokenAmountOut, uint tokenInFee)
{
uint weightRatio = bdiv(tokenWeightIn, tokenWeightOut);
uint adjustedIn = bsub(BONE, swapFee);
adjustedIn = bmul(tokenAmountIn, adjustedIn);
uint y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn));
uint foo = bpow(y, weightRatio);
uint bar = bsub(BONE, foo);
tokenAmountOut = bmul(tokenBalanceOut, bar);
tokenInFee = bsub(tokenAmountIn, adjustedIn);
return (tokenAmountOut, tokenInFee);
}
/**********************************************************************************************
// calcInGivenOut //
// aI = tokenAmountIn //
// bO = tokenBalanceOut / / bO \ (wO / wI) \ //
// bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | //
// aO = tokenAmountOut aI = \ \ ( bO - aO ) / / //
// wI = tokenWeightIn -------------------------------------------- //
// wO = tokenWeightOut ( 1 - sF ) //
// sF = swapFee //
**********************************************************************************************/
function calcInGivenOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountOut,
uint swapFee
)
public pure
returns (uint tokenAmountIn, uint tokenInFee)
{
uint weightRatio = bdiv(tokenWeightOut, tokenWeightIn);
uint diff = bsub(tokenBalanceOut, tokenAmountOut);
uint y = bdiv(tokenBalanceOut, diff);
uint foo = bpow(y, weightRatio);
foo = bsub(foo, BONE);
foo = bmul(tokenBalanceIn, foo);
tokenAmountIn = bsub(BONE, swapFee);
tokenAmountIn = bdiv(foo, tokenAmountIn);
tokenInFee = bdiv(foo, BONE);
tokenInFee = bsub(tokenAmountIn, tokenInFee);
return (tokenAmountIn, tokenInFee);
}
/**********************************************************************************************
// calcPoolOutGivenSingleIn //
// pAo = poolAmountOut / \ //
// tAi = tokenAmountIn /// / // wI \ \\ \ wI \ //
// wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ //
// tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS //
// tBi = tokenBalanceIn \\ ------------------------------------- / / //
// pS = poolSupply \\ tBi / / //
// sF = swapFee \ / //
**********************************************************************************************/
function calcPoolOutGivenSingleIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint tokenAmountIn,
uint swapFee,
uint reservesRatio
)
public pure
returns (uint poolAmountOut, uint reserves)
{
// Charge the trading fee for the proportion of tokenAi
/// which is implicitly traded to the other pool tokens.
// That proportion is (1- weightTokenIn)
// tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee);
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
// Exact fee portion of `tokenAmountIn`, i.e. (1- Wt)
uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
uint tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz));
reserves = calcReserves(tokenAmountIn, tokenAmountInAfterFee, reservesRatio);
uint newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee);
uint tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);
// uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
uint poolRatio = bpow(tokenInRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
poolAmountOut = bsub(newPoolSupply, poolSupply);
return (poolAmountOut, reserves);
}
/**********************************************************************************************
// calcSingleInGivenPoolOut //
// tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ //
// pS = poolSupply || --------- | ^ | --------- || * bI - bI //
// pAo = poolAmountOut \\ pS / \(wI / tW)// //
// bI = balanceIn tAi = -------------------------------------------- //
// wI = weightIn / wI \ //
// tW = totalWeight | 1 - ---- | * sF //
// sF = swapFee \ tW / //
**********************************************************************************************/
function calcSingleInGivenPoolOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint poolAmountOut,
uint swapFee
)
public pure
returns (uint tokenAmountIn)
{
uint normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint newPoolSupply = badd(poolSupply, poolAmountOut);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
//uint newBalTi = poolRatio^(1/weightTi) * balTi;
uint boo = bdiv(BONE, normalizedWeight);
uint tokenInRatio = bpow(poolRatio, boo);
uint newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn);
uint tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn);
// Do reverse order of fees charged in joinswap_ExternAmountIn, this way
// ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ```
//uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ;
uint zar = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar));
return tokenAmountIn;
}
/**********************************************************************************************
// calcSingleOutGivenPoolIn //
// tAo = tokenAmountOut / / \\ //
// bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ //
// pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || //
// ps = poolSupply \ \\ pS / \(wO / tW)/ // //
// wI = tokenWeightIn tAo = \ \ // //
// tW = totalWeight / / wO \ \ //
// sF = swapFee * | 1 - | 1 - ---- | * sF | //
// eF = exitFee \ \ tW / / //
**********************************************************************************************/
function calcSingleOutGivenPoolIn(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint poolAmountIn,
uint swapFee
)
public pure
returns (uint tokenAmountOut)
{
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
// charge exit fee on the pool token side
// pAiAfterExitFee = pAi*(1-exitFee)
uint poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE));
uint newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee);
uint poolRatio = bdiv(newPoolSupply, poolSupply);
// newBalTo = poolRatio^(1/weightTo) * balTo;
uint tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight));
uint newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut);
uint tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);
// charge swap fee on the output token side
//uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee)
uint zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz));
return tokenAmountOut;
}
/**********************************************************************************************
// calcPoolInGivenSingleOut //
// pAi = poolAmountIn // / tAo \\ / wO \ \ //
// bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ //
// tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | //
// ps = poolSupply \\ -----------------------------------/ / //
// wO = tokenWeightOut pAi = \\ bO / / //
// tW = totalWeight ------------------------------------------------------------- //
// sF = swapFee ( 1 - eF ) //
// eF = exitFee //
**********************************************************************************************/
function calcPoolInGivenSingleOut(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint tokenAmountOut,
uint swapFee,
uint reservesRatio
)
public pure
returns (uint poolAmountIn, uint reserves)
{
// charge swap fee on the output token side
uint normalizedWeight = bdiv(tokenWeightOut, totalWeight);
uint zar = bmul(bsub(BONE, normalizedWeight), swapFee);
uint tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar));
reserves = calcReserves(tokenAmountOutBeforeSwapFee, tokenAmountOut, reservesRatio);
uint newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee);
uint tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut);
//uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;
uint poolRatio = bpow(tokenOutRatio, normalizedWeight);
uint newPoolSupply = bmul(poolRatio, poolSupply);
uint poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply);
// charge exit fee on the pool token side
// pAi = pAiAfterExitFee/(1-exitFee)
poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE));
return (poolAmountIn, reserves);
}
// `swapFeeAndReserves = amountWithFee - amountWithoutFee` is the swap fee in balancer.
// We divide `swapFeeAndReserves` into halves, `actualSwapFee` and `reserves`.
// `reserves` goes to the admin and `actualSwapFee` still goes to the liquidity
// providers.
function calcReserves(uint amountWithFee, uint amountWithoutFee, uint reservesRatio)
internal pure
returns (uint reserves)
{
require(amountWithFee >= amountWithoutFee, "ERR_MATH_APPROX");
require(reservesRatio <= BONE, "ERR_INVALID_RESERVE");
uint swapFeeAndReserves = bsub(amountWithFee, amountWithoutFee);
reserves = bmul(swapFeeAndReserves, reservesRatio);
require(swapFeeAndReserves >= reserves, "ERR_MATH_APPROX");
}
function calcReservesFromFee(uint fee, uint reservesRatio)
internal pure
returns (uint reserves)
{
require(reservesRatio <= BONE, "ERR_INVALID_RESERVE");
reserves = bmul(fee, reservesRatio);
}
}
contract BPool is BBronze, BToken, BMath {
struct Record {
bool bound; // is token bound to pool
uint index; // private
uint denorm; // denormalized weight
uint balance;
}
event LOG_SWAP(
address indexed caller,
address indexed tokenIn,
address indexed tokenOut,
uint256 tokenAmountIn,
uint256 tokenAmountOut,
uint256 reservesAmount
);
event LOG_JOIN(
address indexed caller,
address indexed tokenIn,
uint256 tokenAmountIn,
uint256 reservesAmount
);
event LOG_EXIT(
address indexed caller,
address indexed tokenOut,
uint256 tokenAmountOut,
uint256 reservesAmount
);
event LOG_DRAIN_RESERVES(
address indexed caller,
address indexed tokenOut,
uint256 tokenAmountOut
);
event LOG_ADD_RESERVES(
address indexed token,
uint256 reservesAmount
);
event LOG_CALL(
bytes4 indexed sig,
address indexed caller,
bytes data
) anonymous;
modifier _logs_() {
emit LOG_CALL(msg.sig, msg.sender, msg.data);
_;
}
modifier _lock_() {
require(!_mutex);
_mutex = true;
_;
_mutex = false;
}
modifier _viewlock_() {
require(!_mutex);
_;
}
bool private _mutex;
address private _factory; // BFactory address to push token exitFee to
address private _controller; // has CONTROL role
bool private _publicSwap; // true if PUBLIC can call SWAP functions
// `setSwapFee` and `finalize` require CONTROL
// `finalize` sets `PUBLIC can SWAP`, `PUBLIC can JOIN`
uint private _swapFee;
uint private _reservesRatio;
bool private _finalized;
address[] private _tokens;
mapping(address=>Record) private _records;
mapping(address=>uint) public totalReserves;
uint private _totalWeight;
constructor() public {
_controller = msg.sender;
_factory = msg.sender;
_swapFee = MIN_FEE;
_reservesRatio = DEFAULT_RESERVES_RATIO;
_publicSwap = false;
_finalized = false;
}
function isPublicSwap()
external view
returns (bool)
{
return _publicSwap;
}
function isFinalized()
external view
returns (bool)
{
return _finalized;
}
function isBound(address t)
external view
returns (bool)
{
return _records[t].bound;
}
function getNumTokens()
external view
returns (uint)
{
return _tokens.length;
}
function getCurrentTokens()
external view _viewlock_
returns (address[] memory tokens)
{
return _tokens;
}
function getFinalTokens()
external view
_viewlock_
returns (address[] memory tokens)
{
require(_finalized);
return _tokens;
}
function getDenormalizedWeight(address token)
external view
_viewlock_
returns (uint)
{
require(_records[token].bound);
return _records[token].denorm;
}
function getTotalDenormalizedWeight()
external view
_viewlock_
returns (uint)
{
return _totalWeight;
}
function getNormalizedWeight(address token)
external view
_viewlock_
returns (uint)
{
require(_records[token].bound);
uint denorm = _records[token].denorm;
return bdiv(denorm, _totalWeight);
}
function getBalance(address token)
external view
_viewlock_
returns (uint)
{
require(_records[token].bound);
return _records[token].balance;
}
function getSwapFee()
external view
_viewlock_
returns (uint)
{
return _swapFee;
}
function getReservesRatio()
external view
_viewlock_
returns (uint)
{
return _reservesRatio;
}
function getController()
external view
_viewlock_
returns (address)
{
return _controller;
}
function setSwapFee(uint swapFee)
external
_logs_
_lock_
{
require(!_finalized);
require(msg.sender == _controller);
require(swapFee >= MIN_FEE);
require(swapFee <= MAX_FEE);
_swapFee = swapFee;
}
function setReservesRatio(uint reservesRatio)
external
_logs_
_lock_
{
require(!_finalized);
require(msg.sender == _controller);
require(reservesRatio <= BONE);
require(reservesRatio >= DEFAULT_RESERVES_RATIO);
_reservesRatio = reservesRatio;
}
function setController(address manager)
external
_logs_
_lock_
{
require(msg.sender == _controller);
_controller = manager;
}
function setPublicSwap(bool public_)
external
_logs_
_lock_
{
require(!_finalized);
require(msg.sender == _controller);
_publicSwap = public_;
}
function finalize()
external
_logs_
_lock_
{
require(msg.sender == _controller);
require(!_finalized);
require(_tokens.length >= MIN_BOUND_TOKENS);
_finalized = true;
_publicSwap = true;
_mintPoolShare(INIT_POOL_SUPPLY);
_pushPoolShare(msg.sender, INIT_POOL_SUPPLY);
}
function bind(address token, uint balance, uint denorm)
external
_logs_
// _lock_ Bind does not lock because it jumps to `rebind`, which does
{
require(msg.sender == _controller);
require(!_records[token].bound);
require(!_finalized);
require(_tokens.length < MAX_BOUND_TOKENS);
_records[token] = Record({
bound: true,
index: _tokens.length,
denorm: 0, // balance and denorm will be validated
balance: 0 // and set by `rebind`
});
_tokens.push(token);
rebind(token, balance, denorm);
}
function rebind(address token, uint balance, uint denorm)
public
_logs_
_lock_
{
require(msg.sender == _controller);
require(_records[token].bound);
require(!_finalized);
require(denorm >= MIN_WEIGHT);
require(denorm <= MAX_WEIGHT);
require(balance >= MIN_BALANCE);
// Adjust the denorm and totalWeight
uint oldWeight = _records[token].denorm;
if (denorm > oldWeight) {
_totalWeight = badd(_totalWeight, bsub(denorm, oldWeight));
require(_totalWeight <= MAX_TOTAL_WEIGHT);
} else if (denorm < oldWeight) {
_totalWeight = bsub(_totalWeight, bsub(oldWeight, denorm));
}
_records[token].denorm = denorm;
// Adjust the balance record and actual token balance
uint oldBalance = _records[token].balance;
_records[token].balance = balance;
if (balance > oldBalance) {
_pullUnderlying(token, msg.sender, bsub(balance, oldBalance));
} else if (balance < oldBalance) {
// In this case liquidity is being withdrawn, so charge EXIT_FEE
uint tokenBalanceWithdrawn = bsub(oldBalance, balance);
uint tokenExitFee = bmul(tokenBalanceWithdrawn, EXIT_FEE);
_pushUnderlying(token, msg.sender, bsub(tokenBalanceWithdrawn, tokenExitFee));
_pushUnderlying(token, _factory, tokenExitFee);
}
}
function unbind(address token)
external
_logs_
_lock_
{
require(msg.sender == _controller);
require(_records[token].bound);
require(!_finalized);
uint tokenBalance = _records[token].balance;
uint tokenExitFee = bmul(tokenBalance, EXIT_FEE);
_totalWeight = bsub(_totalWeight, _records[token].denorm);
// Swap the token-to-unbind with the last token,
// then delete the last token
uint index = _records[token].index;
uint last = _tokens.length - 1;
_tokens[index] = _tokens[last];
_records[_tokens[index]].index = index;
_tokens.pop();
_records[token] = Record({
bound: false,
index: 0,
denorm: 0,
balance: 0
});
_pushUnderlying(token, msg.sender, bsub(tokenBalance, tokenExitFee));
_pushUnderlying(token, _factory, tokenExitFee);
}
// Absorb any tokens that have been sent to this contract into the pool
function gulp(address token)
external
_logs_
_lock_
{
require(_records[token].bound);
uint erc20Balance = IERC20(token).balanceOf(address(this));
uint reserves = totalReserves[token];
// `_records[token].balance` should be equaled to `bsub(erc20Balance, reserves)` unless there are extra
// tokens transferred to this pool without calling `joinxxx`.
require(_records[token].balance <= bsub(erc20Balance, reserves));
_records[token].balance = bsub(erc20Balance, reserves);
}
function seize(address token, uint amount)
external
_logs_
_lock_
{
require(msg.sender == _controller);
require(!_records[token].bound);
uint bal = IERC20(token).balanceOf(address(this));
require(amount <= bal);
_pushUnderlying(token, msg.sender, amount);
}
function getSpotPrice(address tokenIn, address tokenOut)
external view
_viewlock_
returns (uint spotPrice)
{
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
Record storage inRecord = _records[tokenIn];
Record storage outRecord = _records[tokenOut];
return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, _swapFee);
}
function getSpotPriceSansFee(address tokenIn, address tokenOut)
external view
_viewlock_
returns (uint spotPrice)
{
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
Record storage inRecord = _records[tokenIn];
Record storage outRecord = _records[tokenOut];
return calcSpotPrice(inRecord.balance, inRecord.denorm, outRecord.balance, outRecord.denorm, 0);
}
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn)
external
_logs_
_lock_
{
require(_finalized, "ERR_NOT_FINALIZED");
uint poolTotal = totalSupply();
uint ratio = bdiv(poolAmountOut, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
for (uint i = 0; i < _tokens.length; i++) {
address t = _tokens[i];
uint bal = _records[t].balance;
uint tokenAmountIn = bmul(ratio, bal);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountsIn[i], "ERR_LIMIT_IN");
_records[t].balance = badd(_records[t].balance, tokenAmountIn);
emit LOG_JOIN(msg.sender, t, tokenAmountIn, 0);
_pullUnderlying(t, msg.sender, tokenAmountIn);
}
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
}
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut)
external
_logs_
_lock_
{
require(_finalized, "ERR_NOT_FINALIZED");
uint poolTotal = totalSupply();
uint exitFee = bmul(poolAmountIn, EXIT_FEE);
uint pAiAfterExitFee = bsub(poolAmountIn, exitFee);
uint ratio = bdiv(pAiAfterExitFee, poolTotal);
require(ratio != 0, "ERR_MATH_APPROX");
_pullPoolShare(msg.sender, poolAmountIn);
_pushPoolShare(_factory, exitFee);
_burnPoolShare(pAiAfterExitFee);
for (uint i = 0; i < _tokens.length; i++) {
address t = _tokens[i];
uint bal = _records[t].balance;
uint tokenAmountOut = bmul(ratio, bal);
require(tokenAmountOut != 0, "ERR_MATH_APPROX");
require(tokenAmountOut >= minAmountsOut[i], "ERR_LIMIT_OUT");
_records[t].balance = bsub(_records[t].balance, tokenAmountOut);
emit LOG_EXIT(msg.sender, t, tokenAmountOut, 0);
_pushUnderlying(t, msg.sender, tokenAmountOut);
}
}
function swapExactAmountIn(
address tokenIn,
uint tokenAmountIn,
address tokenOut,
uint minAmountOut,
uint maxPrice
)
external
_logs_
_lock_
returns (uint tokenAmountOut, uint spotPriceAfter)
{
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
require(_publicSwap, "ERR_SWAP_NOT_PUBLIC");
Record storage inRecord = _records[address(tokenIn)];
Record storage outRecord = _records[address(tokenOut)];
require(tokenAmountIn <= bmul(inRecord.balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO");
uint spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
uint tokenInFee;
(tokenAmountOut, tokenInFee) = calcOutGivenIn(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
uint reserves = calcReservesFromFee(tokenInFee, _reservesRatio);
// Subtract `reserves`.
inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves);
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX");
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut, reserves);
totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves);
emit LOG_ADD_RESERVES(address(tokenIn), reserves);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return (tokenAmountOut, spotPriceAfter);
}
function swapExactAmountOut(
address tokenIn,
uint maxAmountIn,
address tokenOut,
uint tokenAmountOut,
uint maxPrice
)
external
_logs_
_lock_
returns (uint tokenAmountIn, uint spotPriceAfter)
{
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
require(_publicSwap, "ERR_SWAP_NOT_PUBLIC");
Record storage inRecord = _records[address(tokenIn)];
Record storage outRecord = _records[address(tokenOut)];
require(tokenAmountOut <= bmul(outRecord.balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO");
uint spotPriceBefore = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceBefore <= maxPrice, "ERR_BAD_LIMIT_PRICE");
uint tokenInFee;
(tokenAmountIn, tokenInFee) = calcInGivenOut(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
tokenAmountOut,
_swapFee
);
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
uint reserves = calcReservesFromFee(
tokenInFee,
_reservesRatio
);
// Subtract `reserves` which is reserved for admin.
inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves);
outRecord.balance = bsub(outRecord.balance, tokenAmountOut);
spotPriceAfter = calcSpotPrice(
inRecord.balance,
inRecord.denorm,
outRecord.balance,
outRecord.denorm,
_swapFee
);
require(spotPriceAfter >= spotPriceBefore, "ERR_MATH_APPROX");
require(spotPriceAfter <= maxPrice, "ERR_LIMIT_PRICE");
require(spotPriceBefore <= bdiv(tokenAmountIn, tokenAmountOut), "ERR_MATH_APPROX");
emit LOG_SWAP(msg.sender, tokenIn, tokenOut, tokenAmountIn, tokenAmountOut, reserves);
totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves);
emit LOG_ADD_RESERVES(address(tokenIn), reserves);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return (tokenAmountIn, spotPriceAfter);
}
function joinswapExternAmountIn(address tokenIn, uint tokenAmountIn, uint minPoolAmountOut)
external
_logs_
_lock_
returns (uint poolAmountOut)
{
require(_finalized, "ERR_NOT_FINALIZED");
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO");
Record storage inRecord = _records[tokenIn];
uint reserves;
(poolAmountOut, reserves) = calcPoolOutGivenSingleIn(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountIn,
_swapFee,
_reservesRatio
);
require(poolAmountOut >= minPoolAmountOut, "ERR_LIMIT_OUT");
inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves);
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn, reserves);
totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves);
emit LOG_ADD_RESERVES(address(tokenIn), reserves);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return poolAmountOut;
}
function joinswapPoolAmountOut(address tokenIn, uint poolAmountOut, uint maxAmountIn)
external
_logs_
_lock_
returns (uint tokenAmountIn)
{
require(_finalized, "ERR_NOT_FINALIZED");
require(_records[tokenIn].bound, "ERR_NOT_BOUND");
Record storage inRecord = _records[tokenIn];
tokenAmountIn = calcSingleInGivenPoolOut(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountOut,
_swapFee
);
require(tokenAmountIn != 0, "ERR_MATH_APPROX");
require(tokenAmountIn <= maxAmountIn, "ERR_LIMIT_IN");
require(tokenAmountIn <= bmul(_records[tokenIn].balance, MAX_IN_RATIO), "ERR_MAX_IN_RATIO");
uint tokenAmountInZeroFee = calcSingleInGivenPoolOut(
inRecord.balance,
inRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountOut,
0
);
uint reserves = calcReserves(
tokenAmountIn,
tokenAmountInZeroFee,
_reservesRatio
);
inRecord.balance = bsub(badd(inRecord.balance, tokenAmountIn), reserves);
emit LOG_JOIN(msg.sender, tokenIn, tokenAmountIn, reserves);
totalReserves[address(tokenIn)] = badd(totalReserves[address(tokenIn)], reserves);
emit LOG_ADD_RESERVES(address(tokenIn), reserves);
_mintPoolShare(poolAmountOut);
_pushPoolShare(msg.sender, poolAmountOut);
_pullUnderlying(tokenIn, msg.sender, tokenAmountIn);
return tokenAmountIn;
}
function exitswapPoolAmountIn(address tokenOut, uint poolAmountIn, uint minAmountOut)
external
_logs_
_lock_
returns (uint tokenAmountOut)
{
require(_finalized, "ERR_NOT_FINALIZED");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
Record storage outRecord = _records[tokenOut];
tokenAmountOut = calcSingleOutGivenPoolIn(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn,
_swapFee
);
require(tokenAmountOut >= minAmountOut, "ERR_LIMIT_OUT");
require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO");
uint tokenAmountOutZeroFee = calcSingleOutGivenPoolIn(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
poolAmountIn,
0
);
uint reserves = calcReserves(
tokenAmountOutZeroFee,
tokenAmountOut,
_reservesRatio
);
outRecord.balance = bsub(bsub(outRecord.balance, tokenAmountOut), reserves);
uint exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut, reserves);
totalReserves[address(tokenOut)] = badd(totalReserves[address(tokenOut)], reserves);
emit LOG_ADD_RESERVES(address(tokenOut), reserves);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_factory, exitFee);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return tokenAmountOut;
}
function exitswapExternAmountOut(address tokenOut, uint tokenAmountOut, uint maxPoolAmountIn)
external
_logs_
_lock_
returns (uint poolAmountIn)
{
require(_finalized, "ERR_NOT_FINALIZED");
require(_records[tokenOut].bound, "ERR_NOT_BOUND");
require(tokenAmountOut <= bmul(_records[tokenOut].balance, MAX_OUT_RATIO), "ERR_MAX_OUT_RATIO");
Record storage outRecord = _records[tokenOut];
uint reserves;
(poolAmountIn, reserves) = calcPoolInGivenSingleOut(
outRecord.balance,
outRecord.denorm,
_totalSupply,
_totalWeight,
tokenAmountOut,
_swapFee,
_reservesRatio
);
require(poolAmountIn != 0, "ERR_MATH_APPROX");
require(poolAmountIn <= maxPoolAmountIn, "ERR_LIMIT_IN");
outRecord.balance = bsub(bsub(outRecord.balance, tokenAmountOut), reserves);
uint exitFee = bmul(poolAmountIn, EXIT_FEE);
emit LOG_EXIT(msg.sender, tokenOut, tokenAmountOut, reserves);
totalReserves[address(tokenOut)] = badd(totalReserves[address(tokenOut)], reserves);
emit LOG_ADD_RESERVES(address(tokenOut), reserves);
_pullPoolShare(msg.sender, poolAmountIn);
_burnPoolShare(bsub(poolAmountIn, exitFee));
_pushPoolShare(_factory, exitFee);
_pushUnderlying(tokenOut, msg.sender, tokenAmountOut);
return poolAmountIn;
}
function drainTotalReserves(address reservesAddress)
external
_logs_
_lock_
{
require(msg.sender == _factory);
for (uint i = 0; i < _tokens.length; i++) {
address t = _tokens[i];
uint tokenAmountOut = totalReserves[t];
totalReserves[t] = 0;
emit LOG_DRAIN_RESERVES(reservesAddress, t, tokenAmountOut);
_pushUnderlying(t, reservesAddress, tokenAmountOut);
}
}
// ==
// 'Underlying' token-manipulation functions make external calls but are NOT locked
// You must `_lock_` or otherwise ensure reentry-safety
function _pullUnderlying(address erc20, address from, uint amount)
internal
{
bool xfer = IERC20(erc20).transferFrom(from, address(this), amount);
require(xfer, "ERR_ERC20_FALSE");
}
function _pushUnderlying(address erc20, address to, uint amount)
internal
{
bool xfer = IERC20(erc20).transfer(to, amount);
require(xfer, "ERR_ERC20_FALSE");
}
function _pullPoolShare(address from, uint amount)
internal
{
_pull(from, amount);
}
function _pushPoolShare(address to, uint amount)
internal
{
_push(to, amount);
}
function _mintPoolShare(uint amount)
internal
{
_mint(amount);
}
function _burnPoolShare(uint amount)
internal
{
_burn(amount);
}
}
|
`_records[token].balance` should be equaled to `bsub(erc20Balance, reserves)` unless there are extra tokens transferred to this pool without calling `joinxxx`.
|
function gulp(address token)
external
_logs_
_lock_
{
require(_records[token].bound);
uint erc20Balance = IERC20(token).balanceOf(address(this));
uint reserves = totalReserves[token];
require(_records[token].balance <= bsub(erc20Balance, reserves));
_records[token].balance = bsub(erc20Balance, reserves);
}
| 7,337,841
|
//SPDX-License-Identifier: MIT
pragma solidity 0.6.9;
pragma experimental ABIEncoderV2;
import "./LimitOrderBook.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/proxy/Initializable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import { Decimal } from "./utils/Decimal.sol";
import { SignedDecimal } from "./utils/SignedDecimal.sol";
import { DecimalERC20 } from "./utils/DecimalERC20.sol";
import { IAmm } from "./interface/IAmm.sol";
import { IClearingHouse } from "./interface/IClearingHouse.sol";
import { ISmartWallet } from "./interface/ISmartWallet.sol";
contract SmartWallet is DecimalERC20, Initializable, ISmartWallet, Pausable {
// Store addresses of smart contracts that we will be interacting with
LimitOrderBook public OrderBook;
SmartWalletFactory public factory;
/* The ClearingHouse deployed with the main PERP contracts */
address constant CLEARINGHOUSE = 0x124650FfF6cd6d3242Ef0296C2F2dAB8F8109878; // TODO Set this with a setter
address private owner;
using Decimal for Decimal.decimal;
using SignedDecimal for SignedDecimal.signedDecimal;
using Address for address;
using SafeERC20 for IERC20;
/*
* @notice allows the owner of the smart wallet to execute any transaction
* on an external smart contract. The external smart contract must be whitelisted
* otherwise this function will revert
* This utilises functions from OpenZeppelin's Address.sol
* @param target the address of the smart contract to interact with (will revert
* if this is not a valid smart contract)
* @param callData the data bytes of the function and parameters to execute
* Can use encodeFunctionData() from ethers.js
* @param value the ether value to attach to the function call (can be 0)
*/
function executeCall(
address target,
bytes calldata callData,
uint256 value
) external payable override onlyOwner() returns (bytes memory) {
require(target.isContract(), 'call to non-contract');
require(factory.isWhitelisted(target), 'Invalid target contract');
return target.functionCallWithValue(callData, value);
}
function initialize(address _lob, address _trader) initializer external override{
OrderBook = LimitOrderBook(_lob);
factory = SmartWalletFactory(msg.sender);
owner = _trader;
}
function executeMarketOrder(
IAmm _asset,
SignedDecimal.signedDecimal memory _orderSize,
Decimal.decimal memory _collateral,
Decimal.decimal memory _leverage,
Decimal.decimal memory _slippage
) external override onlyOwner() whenNotPaused() {
_handleOpenPositionWithApproval(_asset, _orderSize, _collateral, _leverage, _slippage);
}
function executeClosePosition(
IAmm _asset,
Decimal.decimal memory _slippage
) external override onlyOwner() whenNotPaused() {
_handleClosePositionWithApproval(_asset, _slippage);
}
function pauseWallet() external onlyOwner() {
_pause();
}
function unpauseWallet() external onlyOwner() {
_unpause();
}
/*
* @notice Will execute an order from the limit order book. Note that the only
* way to call this function is via the LimitOrderBook where you call execute().
* @param order_id is the ID of the order to execute
*/
function executeOrder(
uint order_id
) external override whenNotPaused() {
//Only the LimitOrderBook can call this function
require(msg.sender == address(OrderBook), 'Only execute from the order book');
//Get some of the parameters
(,address _trader,
LimitOrderBook.OrderType _orderType,
,bool _stillValid, uint _expiry) =
OrderBook.getLimitOrderParams(order_id);
//Make sure that the order belongs to this smart wallet
require(factory.getSmartWallet(_trader) == address(this), 'Incorrect smart wallet');
//Make sure that the order hasn't expired
require(((_expiry == 0 ) || (block.timestamp<_expiry)), 'Order expired');
//Make sure the order is still valid
require(_stillValid, 'Order no longer valid');
//Perform function depending on the type of order
if(_orderType == LimitOrderBook.OrderType.LIMIT) {
_executeLimitOrder(order_id);
} else if(_orderType == LimitOrderBook.OrderType.STOPMARKET) {
_executeStopOrder(order_id);
} else if(_orderType == LimitOrderBook.OrderType.STOPLIMIT) {
_executeStopLimitOrder(order_id);
} else if (_orderType == LimitOrderBook.OrderType.TRAILINGSTOPMARKET) {
_executeStopOrder(order_id);
} else if (_orderType == LimitOrderBook.OrderType.TRAILINGSTOPLIMIT) {
_executeStopLimitOrder(order_id);
}
}
function minD(Decimal.decimal memory a, Decimal.decimal memory b) internal pure
returns (Decimal.decimal memory){
return (a.cmp(b) >= 1) ? b : a;
}
function _handleOpenPositionWithApproval(
IAmm _asset,
SignedDecimal.signedDecimal memory _orderSize,
Decimal.decimal memory _collateral,
Decimal.decimal memory _leverage,
Decimal.decimal memory _slippage
) internal {
//Get cost of placing order (fees)
(Decimal.decimal memory toll, Decimal.decimal memory spread) = _asset
.calcFee(_collateral.mulD(_leverage));
Decimal.decimal memory totalCost = _collateral.addD(toll).addD(spread);
IERC20 quoteAsset = _asset.quoteAsset();
_approve(quoteAsset, CLEARINGHOUSE, totalCost);
//Establish how much leverage will be needed for that order based on the
//amount of collateral and the maximum leverage the user was happy with.
bool _isLong = _orderSize.isNegative() ? false : true;
Decimal.decimal memory _size = _orderSize.abs();
Decimal.decimal memory _quote = (IAmm(_asset)
.getOutputPrice(_isLong ? IAmm.Dir.REMOVE_FROM_AMM : IAmm.Dir.ADD_TO_AMM, _size));
Decimal.decimal memory _offset = Decimal.decimal(1); //Need to add one wei for rounding
_leverage = minD(_quote.divD(_collateral).addD(_offset),_leverage);
IClearingHouse(CLEARINGHOUSE).openPosition(
_asset,
_isLong ? IClearingHouse.Side.BUY : IClearingHouse.Side.SELL,
_collateral,
_leverage,
_slippage
);
}
function _calcBaseAssetAmountLimit(
Decimal.decimal memory _positionSize,
bool _isLong,
Decimal.decimal memory _slippage
) internal pure returns (Decimal.decimal memory){
Decimal.decimal memory factor;
require(_slippage.cmp(Decimal.one()) == -1, 'Slippage must be %');
if (_isLong) {
//base amount must be greater than base amount limit
factor = Decimal.one().subD(_slippage);
} else {
//base amount must be less than base amount limit
factor = Decimal.one().addD(_slippage);
}
return factor.mulD(_positionSize);
}
/*
OPEN LONG
BASE ASSET LIMIT = POSITION SIZE - SLIPPAGE
OPEN SHORT
BASE ASSET LIMIT = POSITION SIZE + SLIPPAGE
CLOSE LONG
QUOTE ASSET LIMIT = VALUE - SLIPPAGE
CLOSE SHORT
QUOTE ASSET LIMIT = VALUE + SLIPPAGE
*/
function _calcQuoteAssetAmountLimit(
IAmm _asset,
Decimal.decimal memory _targetPrice,
bool _isLong,
Decimal.decimal memory _slippage
) internal view returns (Decimal.decimal memory){
IClearingHouse.Position memory oldPosition = IClearingHouse(CLEARINGHOUSE)
.getPosition(_asset, address(this));
SignedDecimal.signedDecimal memory oldPositionSize = oldPosition.size;
Decimal.decimal memory value = oldPositionSize.abs().mulD(_targetPrice);
Decimal.decimal memory factor;
require(_slippage.cmp(Decimal.one()) == -1, 'Slippage must be %');
if (_isLong) {
//quote amount must be less than quote amount limit
factor = Decimal.one().subD(_slippage);
} else {
//quote amount must be greater than quote amount limit
factor = Decimal.one().addD(_slippage);
}
return factor.mulD(value);
}
function _handleClosePositionWithApproval(
IAmm _asset,
Decimal.decimal memory _slippage
) internal {
//Need to calculate trading fees to close position (no margin required)
IClearingHouse.Position memory oldPosition = IClearingHouse(CLEARINGHOUSE)
.getPosition(_asset, address(this));
SignedDecimal.signedDecimal memory oldPositionSize = oldPosition.size;
Decimal.decimal memory _quoteAsset = _asset.getOutputPrice(
oldPositionSize.toInt() > 0 ? IAmm.Dir.ADD_TO_AMM : IAmm.Dir.REMOVE_FROM_AMM,
oldPositionSize.abs()
);
(Decimal.decimal memory toll, Decimal.decimal memory spread) = _asset
.calcFee(_quoteAsset);
Decimal.decimal memory totalCost = toll.addD(spread);
IERC20 quoteAsset = _asset.quoteAsset();
_approve(quoteAsset, CLEARINGHOUSE, totalCost);
IClearingHouse(CLEARINGHOUSE).closePosition(
_asset,
_slippage
);
}
/*
* @notice check what this order should do if it is reduceOnly
* To clarify, only reduceOnly orders should call this function:
* If it returns true, then the order should close the position rather than
* opening one.
* @param _asset the AMM for the asset
* @param _orderSize the size of the order (note: negative are SELL/SHORt)
*/
function _shouldCloseReduceOnly(
IAmm _asset,
SignedDecimal.signedDecimal memory _orderSize
) internal view returns (bool) {
//Get the size of the users current position
IClearingHouse.Position memory _currentPosition = IClearingHouse(CLEARINGHOUSE)
.getPosition(IAmm(_asset), address(this));
SignedDecimal.signedDecimal memory _currentSize = _currentPosition.size;
//If the user has no position for this asset, then cannot execute a reduceOnly order
require(_currentSize.abs().toUint() != 0, "#reduceOnly: current size is 0");
//If the direction of the order is opposite to the users current position
if(_orderSize.isNegative() != _currentSize.isNegative()) {
//User is long and wants to sell:
if(_orderSize.isNegative()) {
//The size of the order is large enough to open a reverse position,
//therefore we should close it instead
if(_orderSize.abs().cmp(_currentSize.abs()) == 1) {
return true;
}
} else {
//User is short and wants to buy:
if(_currentSize.abs().cmp(_orderSize.abs()) == 1) {
//The size of the order is large enough to open a reverse position,
//therefore we should close it instead
return true;
}
}
} else {
//User is trying to increase the size of their position
revert('#reduceOnly: cannot increase size of position');
}
}
/*
* @notice internal position to execute limit order - note that you need to
* check that this is a limit order before calling this function
*/
function _executeLimitOrder(
uint order_id
) internal {
//Get information of limit order
(,Decimal.decimal memory _limitPrice,
SignedDecimal.signedDecimal memory _orderSize,
Decimal.decimal memory _collateral,
Decimal.decimal memory _leverage,
Decimal.decimal memory _slippage,,
address _asset, bool _reduceOnly) = OrderBook.getLimitOrderPrices(order_id);
//Check whether we need to close position or open position
bool closePosition = false;
if(_reduceOnly) {
closePosition = _shouldCloseReduceOnly(IAmm(_asset), _orderSize);
}
//Establish whether long or short
bool isLong = _orderSize.isNegative() ? false : true;
//Get the current spot price of the asset
Decimal.decimal memory _markPrice = IAmm(_asset).getSpotPrice();
require(_markPrice.cmp(Decimal.zero()) >= 1, 'Error getting mark price');
//Check whether price conditions have been met:
// LIMIT BUY: mark price < limit price
// LIMIT SELL: mark price > limit price
require((_limitPrice.cmp(_markPrice)) == (isLong ? int128(1) : -1), 'Invalid limit order condition');
if(closePosition) {
Decimal.decimal memory quoteAssetLimit = _calcQuoteAssetAmountLimit(IAmm(_asset), _limitPrice, isLong, _slippage);
_handleClosePositionWithApproval(IAmm(_asset), quoteAssetLimit);
} else {
//openPosition using the values calculated above
Decimal.decimal memory baseAssetLimit = _calcBaseAssetAmountLimit(_orderSize.abs(), isLong, _slippage);
_handleOpenPositionWithApproval(IAmm(_asset), _orderSize, _collateral, _leverage, baseAssetLimit);
}
}
function _executeStopOrder(
uint order_id
) internal {
//Get information of stop order
(Decimal.decimal memory _stopPrice,,
SignedDecimal.signedDecimal memory _orderSize,
Decimal.decimal memory _collateral,
Decimal.decimal memory _leverage,,,
address _asset, bool _reduceOnly) = OrderBook.getLimitOrderPrices(order_id);
//Check whether we need to close position or open position
bool closePosition = false;
if(_reduceOnly) {
closePosition = _shouldCloseReduceOnly(IAmm(_asset), _orderSize);
}
//Establish whether long or short
bool isLong = _orderSize.isNegative() ? false : true;
//Get the current spot price of the asset
Decimal.decimal memory _markPrice = IAmm(_asset).getSpotPrice();
require(_markPrice.cmp(Decimal.zero()) >= 1, 'Error getting mark price');
//Check whether price conditions have been met:
// STOP BUY: mark price > stop price
// STOP SELL: mark price < stop price
require((_markPrice.cmp(_stopPrice)) == (isLong ? int128(1) : -1), 'Invalid stop order conditions');
//Strictly speaking, stop orders cannot have slippage as by definition they
//will get executed at the next available price. Restricting them with slippage
//will turn them into stop limit orders.
if(closePosition) {
_handleClosePositionWithApproval(IAmm(_asset), Decimal.decimal(0));
} else {
_handleOpenPositionWithApproval(IAmm(_asset), _orderSize, _collateral, _leverage, Decimal.decimal(0));
}
}
function _executeStopLimitOrder(
uint order_id
) internal {
//Get information of stop limit order
(Decimal.decimal memory _stopPrice,
Decimal.decimal memory _limitPrice,
SignedDecimal.signedDecimal memory _orderSize,
Decimal.decimal memory _collateral,
Decimal.decimal memory _leverage,
Decimal.decimal memory _slippage,,
address _asset, bool _reduceOnly) = OrderBook.getLimitOrderPrices(order_id);
//Check whether we need to close position or open position
bool closePosition = false;
if(_reduceOnly) {
closePosition = _shouldCloseReduceOnly(IAmm(_asset), _orderSize);
}
//Establish whether long or short
bool isLong = _orderSize.isNegative() ? false : true;
//Get the current spot price of the asset
Decimal.decimal memory _markPrice = IAmm(_asset).getSpotPrice();
require(_markPrice.cmp(Decimal.zero()) >= 1, 'Error getting mark price');
//Check whether price conditions have been met:
// STOP LIMIT BUY: limit price > mark price > stop price
// STOP LIMIT SELL: limit price < mark price < stop price
require((_limitPrice.cmp(_markPrice)) == (isLong ? int128(1) : -1) &&
(_markPrice.cmp(_stopPrice)) == (isLong ? int128(1) : -1), 'Invalid stop-limit condition');
if(closePosition) {
Decimal.decimal memory quoteAssetLimit = _calcQuoteAssetAmountLimit(IAmm(_asset), _limitPrice, isLong, _slippage);
_handleClosePositionWithApproval(IAmm(_asset), quoteAssetLimit);
} else {
//openPosition using the values calculated above
Decimal.decimal memory baseAssetLimit = _calcBaseAssetAmountLimit(_orderSize.abs(), isLong, _slippage);
_handleOpenPositionWithApproval(IAmm(_asset), _orderSize, _collateral, _leverage, baseAssetLimit);
}
}
modifier onlyOwner() {
require(owner == msg.sender, "Ownable: caller is not the owner");
_;
}
}
contract SmartWalletFactory is ISmartWalletFactory, Ownable{
event Created(address indexed owner, address indexed smartWallet);
event AddedToWhitelist(address contractAddress);
event DeletedFromWhitelist(address contractAddress);
mapping (address => address) public override getSmartWallet;
mapping (address => bool) public isWhitelisted;
address public LimitOrderBook;
constructor(address _addr) public {
LimitOrderBook = _addr;
}
/*
* @notice Create and deploy a smart wallet for the user and stores the address
*/
function spawn() external returns (address smartWallet) {
require(getSmartWallet[msg.sender] == address(0), 'Already has smart wallet');
bytes memory bytecode = type(SmartWallet).creationCode;
bytes32 salt = keccak256(abi.encodePacked(msg.sender));
assembly {
smartWallet := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
emit Created(msg.sender, smartWallet);
ISmartWallet(smartWallet).initialize(LimitOrderBook, msg.sender);
getSmartWallet[msg.sender] = smartWallet;
}
function addToWhitelist(address _contract) external onlyOwner{
require(!isWhitelisted[_contract], "already whitelisted");
isWhitelisted[_contract] = true;
emit AddedToWhitelist(_contract);
}
function removeFromWhitelist(address _contract) external onlyOwner{
require(isWhitelisted[_contract], "not on whitelisted");
delete isWhitelisted[_contract];
emit DeletedFromWhitelist(_contract);
}
}
|
internal position to execute limit order - note that you need to check that this is a limit order before calling this function/Get information of limit orderCheck whether we need to close position or open positionopenPosition using the values calculated above
|
function _executeLimitOrder(
uint order_id
) internal {
(,Decimal.decimal memory _limitPrice,
SignedDecimal.signedDecimal memory _orderSize,
Decimal.decimal memory _collateral,
Decimal.decimal memory _leverage,
Decimal.decimal memory _slippage,,
address _asset, bool _reduceOnly) = OrderBook.getLimitOrderPrices(order_id);
bool closePosition = false;
if(_reduceOnly) {
closePosition = _shouldCloseReduceOnly(IAmm(_asset), _orderSize);
}
require(_markPrice.cmp(Decimal.zero()) >= 1, 'Error getting mark price');
if(closePosition) {
Decimal.decimal memory quoteAssetLimit = _calcQuoteAssetAmountLimit(IAmm(_asset), _limitPrice, isLong, _slippage);
_handleClosePositionWithApproval(IAmm(_asset), quoteAssetLimit);
Decimal.decimal memory baseAssetLimit = _calcBaseAssetAmountLimit(_orderSize.abs(), isLong, _slippage);
_handleOpenPositionWithApproval(IAmm(_asset), _orderSize, _collateral, _leverage, baseAssetLimit);
}
}
| 12,909,919
|
/*
.'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''..
.;;;;;;;;;;;'. .';;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;,.
.;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,. .;;;;;;;;;;;;;;;;;;;;,.
';;;;;;;;'. .';;;;;;;;;;;;;;;;;;;;;;,. .';;;;;;;;;;;;;;;;;;;;;,.
';;;;;,.. .';;;;;;;;;;;;;;;;;;;;;;;,..';;;;;;;;;;;;;;;;;;;;;;,.
...... .';;;;;;;;;;;;;,'''''''''''.,;;;;;;;;;;;;;,'''''''''..
.,;;;;;;;;;;;;;. .,;;;;;;;;;;;;;.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;,.
.,;;;;;;;;;;;;,. .;;;;;;;;;;;;;,. .....
.;;;;;;;;;;;;;'. ..';;;;;;;;;;;;;'. .',;;;;,'.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .';;;;;;;;;;.
.';;;;;;;;;;;;;'. .';;;;;;;;;;;;;;'. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;;'...........,;;;;;;;;;;;;;;. .;;;;;;;;;;;,.
.,;;;;;;;;;;;;,..,;;;;;;;;;;;;;;;;;;;;;;;,. ..;;;;;;;;;,.
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;;,. .',;;;,,..
.,;;;;;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;;,. ....
..',;;;;;;;;,. .,;;;;;;;;;;;;;;;;;;;;,.
..',;;;;'. .,;;;;;;;;;;;;;;;;;;;'.
...'.. .';;;;;;;;;;;;;;,,,'.
...............
*/
// https://github.com/trusttoken/smart-contracts
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// 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);
}
// Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// pragma solidity ^0.6.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].
*/
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;
}
}
// Dependency file: @openzeppelin/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) {
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;
}
}
// Dependency file: @openzeppelin/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) {
// This method relies in 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");
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);
}
}
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/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");
}
}
}
// Dependency file: @openzeppelin/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.
*/
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;
}
}
// Dependency file: contracts/governance/common/ProxyStorage.sol
// pragma solidity 0.6.10;
/**
* All storage must be declared here
* New storage must be appended to the end
* Never remove items from this list
*/
contract ProxyStorage {
bool public initalized;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
mapping(uint144 => uint256) attributes_Depricated;
address owner_;
address pendingOwner_;
mapping(address => address) public delegates; // A record of votes checkpoints for each account, by index
struct Checkpoint {
// A checkpoint for marking number of votes from a given block
uint32 fromBlock;
uint96 votes;
}
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; // A record of votes checkpoints for each account, by index
mapping(address => uint32) public numCheckpoints; // The number of checkpoints for each account
mapping(address => uint256) public nonces;
/* Additionally, we have several keccak-based storage locations.
* If you add more keccak-based storage mappings, such as mappings, you must document them here.
* If the length of the keccak input is the same as an existing mapping, it is possible there could be a preimage collision.
* A preimage collision can be used to attack the contract by treating one storage location as another,
* which would always be a critical issue.
* Carefully examine future keccak-based storage to ensure there can be no preimage collisions.
*******************************************************************************************************
** length input usage
*******************************************************************************************************
** 19 "trueXXX.proxy.owner" Proxy Owner
** 27 "trueXXX.pending.proxy.owner" Pending Proxy Owner
** 28 "trueXXX.proxy.implementation" Proxy Implementation
** 64 uint256(address),uint256(1) balanceOf
** 64 uint256(address),keccak256(uint256(address),uint256(2)) allowance
** 64 uint256(address),keccak256(bytes32,uint256(3)) attributes
**/
}
// Dependency file: contracts/governance/common/ERC20.sol
/**
* @notice This is a copy of openzeppelin ERC20 contract with removed state variables.
* Removing state variables has been necessary due to proxy pattern usage.
* Changes to Openzeppelin ERC20 https://github.com/OpenZeppelin/openzeppelin-contracts/blob/de99bccbfd4ecd19d7369d01b070aa72c64423c9/contracts/token/ERC20/ERC20.sol:
* - Remove state variables _name, _symbol, _decimals
* - Use state variables balances, allowances, totalSupply from ProxyStorage
* - Remove constructor
* - Solidity version changed from ^0.6.0 to 0.6.10
* - Contract made abstract
* - Remove inheritance from IERC20 because of ProxyStorage name conflicts
*
* See also: ClaimableOwnable.sol and ProxyStorage.sol
*/
// pragma solidity 0.6.10;
// import {Context} from "@openzeppelin/contracts/GSN/Context.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {Address} from "@openzeppelin/contracts/utils/Address.sol";
// import {ProxyStorage} from "contracts/governance/common/ProxyStorage.sol";
// prettier-ignore
/**
* @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}.
*/
abstract contract ERC20 is ProxyStorage, Context {
using SafeMath for uint256;
using Address for address;
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the name of the token.
*/
function name() public virtual pure returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public virtual pure returns (string memory);
/**
* @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 virtual pure returns (uint8) {
return 18;
}
/**
* @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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual 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 returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), allowance[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, allowance[_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, allowance[_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);
balanceOf[sender] = balanceOf[sender].sub(amount, "ERC20: transfer amount exceeds balance");
balanceOf[recipient] = balanceOf[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);
balanceOf[account] = balanceOf[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);
balanceOf[account] = balanceOf[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 is 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");
allowance[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
// solhint-disable-next-line no-empty-blocks
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// Dependency file: contracts/governance/interface/IVoteToken.sol
// pragma solidity ^0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVoteToken {
function delegate(address delegatee) external;
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external;
function getCurrentVotes(address account) external view returns (uint96);
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96);
}
interface IVoteTokenWithERC20 is IVoteToken, IERC20 {}
// Dependency file: contracts/governance/VoteToken.sol
// AND COPIED FROM https://github.com/compound-finance/compound-protocol/blob/c5fcc34222693ad5f547b14ed01ce719b5f4b000/contracts/Governance/Comp.sol
// Copyright 2020 Compound Labs, Inc.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Ctrl+f for OLD to see all the modifications.
// pragma solidity 0.6.10;
// import {ERC20} from "contracts/governance/common/ERC20.sol";
// import {IVoteToken} from "contracts/governance/interface/IVoteToken.sol";
/**
* @title VoteToken
* @notice Custom token which tracks voting power for governance
* @dev This is an abstraction of a fork of the Compound governance contract
* VoteToken is used by TRU and stkTRU to allow tracking voting power
* Checkpoints are created every time state is changed which record voting power
* Inherits standard ERC20 behavior
*/
abstract contract VoteToken is ERC20, IVoteToken {
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance);
function delegate(address delegatee) public override {
return _delegate(msg.sender, delegatee);
}
/**
* @dev Delegate votes using signature
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public override {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "TrustToken::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "TrustToken::delegateBySig: invalid nonce");
require(now <= expiry, "TrustToken::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @dev Get current voting power for an account
* @param account Account to get voting power for
* @return Voting power for an account
*/
function getCurrentVotes(address account) public virtual override view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @dev Get voting power at a specific block for an account
* @param account Account to get voting power for
* @param blockNumber Block to get voting power at
* @return Voting power for an account at specific block
*/
function getPriorVotes(address account, uint256 blockNumber) public virtual override view returns (uint96) {
require(blockNumber < block.number, "TrustToken::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
/**
* @dev Internal function to delegate voting power to an account
* @param delegator Account to delegate votes from
* @param delegatee Account to delegate votes to
*/
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
// OLD: uint96 delegatorBalance = balanceOf(delegator);
uint96 delegatorBalance = safe96(_balanceOf(delegator), "StkTruToken: uint96 overflow");
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _balanceOf(address account) internal view virtual returns (uint256) {
return balanceOf[account];
}
function _transfer(
address _from,
address _to,
uint256 _value
) internal virtual override {
super._transfer(_from, _to, _value);
_moveDelegates(delegates[_from], delegates[_to], safe96(_value, "StkTruToken: uint96 overflow"));
}
function _mint(address account, uint256 amount) internal virtual override {
super._mint(account, amount);
_moveDelegates(address(0), delegates[account], safe96(amount, "StkTruToken: uint96 overflow"));
}
function _burn(address account, uint256 amount) internal virtual override {
super._burn(account, amount);
_moveDelegates(delegates[account], address(0), safe96(amount, "StkTruToken: uint96 overflow"));
}
/**
* @dev internal function to move delegates between accounts
*/
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "TrustToken::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "TrustToken::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
/**
* @dev internal function to write a checkpoint for voting power
*/
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber = safe32(block.number, "TrustToken::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
/**
* @dev internal function to convert from uint256 to uint32
*/
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
/**
* @dev internal function to convert from uint256 to uint96
*/
function safe96(uint256 n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
/**
* @dev internal safe math function to add two uint96 numbers
*/
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev internal safe math function to subtract two uint96 numbers
*/
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev internal function to get chain ID
*/
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// Dependency file: contracts/truefi/interface/ITrueDistributor.sol
// pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ITrueDistributor {
function trustToken() external view returns (IERC20);
function farm() external view returns (address);
function distribute() external;
function nextDistribution() external view returns (uint256);
function empty() external;
}
// Dependency file: contracts/governance/common/StkClaimableContract.sol
// pragma solidity 0.6.10;
// import {ProxyStorage} from "contracts/governance/common/ProxyStorage.sol";
/**
* @title ClaimableContract
* @dev The ClaimableContract contract is a copy of Claimable Contract by Zeppelin.
and provides basic authorization control functions. Inherits storage layout of
ProxyStorage.
*/
contract StkClaimableContract is ProxyStorage {
function owner() public view returns (address) {
return owner_;
}
function pendingOwner() public view returns (address) {
return pendingOwner_;
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev sets the original `owner` of the contract to the sender
* at construction. Must then be reinitialized
*/
constructor() public {
owner_ = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner_, "only owner");
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner_);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner_ = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
address _pendingOwner = pendingOwner_;
emit OwnershipTransferred(owner_, _pendingOwner);
owner_ = _pendingOwner;
pendingOwner_ = address(0);
}
}
// Dependency file: contracts/common/interface/IPauseableContract.sol
// pragma solidity 0.6.10;
/**
* @dev interface to allow standard pause function
*/
interface IPauseableContract {
function setPauseStatus(bool pauseStatus) external;
}
// Root file: contracts/governance/StkTruToken.sol
pragma solidity 0.6.10;
// import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
// import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
// import {VoteToken} from "contracts/governance/VoteToken.sol";
// import {ITrueDistributor} from "contracts/truefi/interface/ITrueDistributor.sol";
// import {StkClaimableContract} from "contracts/governance/common/StkClaimableContract.sol";
// import {IPauseableContract} from "contracts/common/interface/IPauseableContract.sol";
/**
* @title stkTRU
* @dev Staking contract for TrueFi
* TRU is staked and stored in the contract
* stkTRU is minted when staking
* Holders of stkTRU accrue rewards over time
* Rewards are paid in TRU and tfUSD
* stkTRU can be used to vote in governance
* stkTRU can be used to rate and approve loans
*/
contract StkTruToken is VoteToken, StkClaimableContract, IPauseableContract, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant PRECISION = 1e30;
uint256 private constant MIN_DISTRIBUTED_AMOUNT = 100e8;
struct FarmRewards {
// track overall cumulative rewards
uint256 cumulativeRewardPerToken;
// track previous cumulate rewards for accounts
mapping(address => uint256) previousCumulatedRewardPerToken;
// track claimable rewards for accounts
mapping(address => uint256) claimableReward;
// track total rewards
uint256 totalClaimedRewards;
uint256 totalFarmRewards;
}
struct ScheduledTfUsdRewards {
uint64 timestamp;
uint96 amount;
}
// ================ WARNING ==================
// ===== THIS CONTRACT IS INITIALIZABLE ======
// === STORAGE VARIABLES ARE DECLARED BELOW ==
// REMOVAL OR REORDER OF VARIABLES WILL RESULT
// ========= IN STORAGE CORRUPTION ===========
IERC20 public tru;
IERC20 public tfusd;
ITrueDistributor public distributor;
address public liquidator;
uint256 public stakeSupply;
mapping(address => uint256) private cooldowns;
uint256 public cooldownTime;
uint256 public unstakePeriodDuration;
mapping(IERC20 => FarmRewards) public farmRewards;
uint32[] public sortedScheduledRewardIndices;
ScheduledTfUsdRewards[] public scheduledRewards;
uint256 public undistributedTfusdRewards;
uint32 public nextDistributionIndex;
mapping(address => bool) public whitelistedFeePayers;
mapping(address => uint256) public receivedDuringCooldown;
// allow pausing of deposits
bool public pauseStatus;
IERC20 public feeToken;
// ======= STORAGE DECLARATION END ============
event Stake(address indexed staker, uint256 amount);
event Unstake(address indexed staker, uint256 burntAmount);
event Claim(address indexed who, IERC20 indexed token, uint256 amountClaimed);
event Withdraw(uint256 amount);
event Cooldown(address indexed who, uint256 endTime);
event CooldownTimeChanged(uint256 newUnstakePeriodDuration);
event UnstakePeriodDurationChanged(uint256 newUnstakePeriodDuration);
event FeePayerWhitelistingStatusChanged(address payer, bool status);
event PauseStatusChanged(bool pauseStatus);
event FeeTokenChanged(IERC20 token);
event LiquidatorChanged(address liquidator);
/**
* @dev pool can only be joined when it's unpaused
*/
modifier joiningNotPaused() {
require(!pauseStatus, "StkTruToken: Joining the pool is paused");
_;
}
/**
* @dev Only Liquidator contract can perform TRU liquidations
*/
modifier onlyLiquidator() {
require(msg.sender == liquidator, "StkTruToken: Can be called only by the liquidator");
_;
}
/**
* @dev Only whitelisted payers can pay fees
*/
modifier onlyWhitelistedPayers() {
require(whitelistedFeePayers[msg.sender], "StkTruToken: Can be called only by whitelisted payers");
_;
}
/**
* Get TRU from distributor
*/
modifier distribute() {
// pull TRU from distributor
// do not pull small amounts to save some gas
// only pull if there is distribution and distributor farm is set to this farm
if (distributor.nextDistribution() > MIN_DISTRIBUTED_AMOUNT && distributor.farm() == address(this)) {
distributor.distribute();
}
_;
}
/**
* Update all rewards when an account changes state
* @param account Account to update rewards for
*/
modifier update(address account) {
updateTotalRewards(tru);
updateClaimableRewards(tru, account);
updateTotalRewards(tfusd);
updateClaimableRewards(tfusd, account);
updateTotalRewards(feeToken);
updateClaimableRewards(feeToken, account);
_;
}
/**
* Update rewards for a specific token when an account changes state
* @param account Account to update rewards for
* @param token Token to update rewards for
*/
modifier updateRewards(address account, IERC20 token) {
if (token == tru) {
updateTotalRewards(tru);
updateClaimableRewards(tru, account);
} else if (token == tfusd) {
updateTotalRewards(tfusd);
updateClaimableRewards(tfusd, account);
} else if (token == feeToken) {
updateTotalRewards(feeToken);
updateClaimableRewards(feeToken, account);
}
_;
}
/**
* @dev Initialize contract and set default values
* @param _tru TRU token
* @param _tfusd tfUSD token
* @param _feeToken Token for fees, currently tfUSDC
* @param _distributor Distributor for this contract
* @param _liquidator Liquidator for staked TRU
*/
function initialize(
IERC20 _tru,
IERC20 _tfusd,
IERC20 _feeToken,
ITrueDistributor _distributor,
address _liquidator
) public {
require(!initalized, "StkTruToken: Already initialized");
tru = _tru;
tfusd = _tfusd;
feeToken = _feeToken;
distributor = _distributor;
liquidator = _liquidator;
cooldownTime = 14 days;
unstakePeriodDuration = 2 days;
owner_ = msg.sender;
initalized = true;
}
/**
* @dev Set tfUSDC address
* @param _feeToken Address of tfUSDC to be set
*/
function setFeeToken(IERC20 _feeToken) external onlyOwner {
require(rewardBalance(feeToken) == 0, "StkTruToken: Cannot replace fee token with underlying rewards");
feeToken = _feeToken;
emit FeeTokenChanged(_feeToken);
}
/**
* @dev Set liquidator address
* @param _liquidator Address of liquidator to be set
*/
function setLiquidator(address _liquidator) external onlyOwner {
liquidator = _liquidator;
emit LiquidatorChanged(_liquidator);
}
/**
* @dev Owner can use this function to add new addresses to payers whitelist
* Only whitelisted payers can call payFee method
* @param payer Address that is being added to or removed from whitelist
* @param status New whitelisting status
*/
function setPayerWhitelistingStatus(address payer, bool status) external onlyOwner {
whitelistedFeePayers[payer] = status;
emit FeePayerWhitelistingStatusChanged(payer, status);
}
/**
* @dev Owner can use this function to set cooldown time
* Cooldown time defines how long a staker waits to unstake TRU
* @param newCooldownTime New cooldown time for stakers
*/
function setCooldownTime(uint256 newCooldownTime) external onlyOwner {
// Avoid overflow
require(newCooldownTime <= 100 * 365 days, "StkTruToken: Cooldown too large");
cooldownTime = newCooldownTime;
emit CooldownTimeChanged(newCooldownTime);
}
/**
* @dev Allow pausing of deposits in case of emergency
* @param status New deposit status
*/
function setPauseStatus(bool status) external override onlyOwner {
pauseStatus = status;
emit PauseStatusChanged(status);
}
/**
* @dev Owner can set unstake period duration
* Unstake period defines how long after cooldown a user has to withdraw stake
* @param newUnstakePeriodDuration New unstake period
*/
function setUnstakePeriodDuration(uint256 newUnstakePeriodDuration) external onlyOwner {
require(newUnstakePeriodDuration > 0, "StkTruToken: Unstake period cannot be 0");
// Avoid overflow
require(newUnstakePeriodDuration <= 100 * 365 days, "StkTruToken: Unstake period too large");
unstakePeriodDuration = newUnstakePeriodDuration;
emit UnstakePeriodDurationChanged(newUnstakePeriodDuration);
}
/**
* @dev Stake TRU for stkTRU
* Updates rewards when staking
* @param amount Amount of TRU to stake for stkTRU
*/
function stake(uint256 amount) external distribute update(msg.sender) joiningNotPaused {
_stakeWithoutTransfer(amount);
tru.safeTransferFrom(msg.sender, address(this), amount);
}
/**
* @dev Unstake stkTRU for TRU
* Can only unstake when cooldown complete and within unstake period
* Claims rewards when unstaking
* @param amount Amount of stkTRU to unstake for TRU
*/
function unstake(uint256 amount) external distribute update(msg.sender) nonReentrant {
require(amount > 0, "StkTruToken: Cannot unstake 0");
require(unstakable(msg.sender) >= amount, "StkTruToken: Insufficient balance");
require(unlockTime(msg.sender) <= block.timestamp, "StkTruToken: Stake on cooldown");
_claim(tru);
_claim(tfusd);
_claim(feeToken);
uint256 amountToTransfer = amount.mul(stakeSupply).div(totalSupply);
_burn(msg.sender, amount);
stakeSupply = stakeSupply.sub(amountToTransfer);
tru.safeTransfer(msg.sender, amountToTransfer);
emit Unstake(msg.sender, amount);
}
/**
* @dev Initiate cooldown period
*/
function cooldown() public {
cooldowns[msg.sender] = block.timestamp;
receivedDuringCooldown[msg.sender] = 0;
emit Cooldown(msg.sender, block.timestamp.add(cooldownTime));
}
/**
* @dev Withdraw TRU from the contract for liquidation
* @param amount Amount to withdraw for liquidation
*/
function withdraw(uint256 amount) external onlyLiquidator {
stakeSupply = stakeSupply.sub(amount);
tru.safeTransfer(liquidator, amount);
emit Withdraw(amount);
}
/**
* @dev View function to get unlock time for an account
* @param account Account to get unlock time for
* @return Unlock time for account
*/
function unlockTime(address account) public view returns (uint256) {
if (cooldowns[account] == 0 || cooldowns[account].add(cooldownTime).add(unstakePeriodDuration) < block.timestamp) {
return type(uint256).max;
}
return cooldowns[account].add(cooldownTime);
}
/**
* @dev Give tfUSD as origination fee to stake.this
* 50% are given immediately and 50% after `endTime` passes
*/
function payFee(uint256 amount, uint256 endTime) external onlyWhitelistedPayers {
require(endTime < type(uint64).max, "StkTruToken: time overflow");
require(amount < type(uint96).max, "StkTruToken: amount overflow");
tfusd.safeTransferFrom(msg.sender, address(this), amount);
undistributedTfusdRewards = undistributedTfusdRewards.add(amount.div(2));
scheduledRewards.push(ScheduledTfUsdRewards({amount: uint96(amount.div(2)), timestamp: uint64(endTime)}));
uint32 newIndex = findPositionForTimestamp(endTime);
insertAt(newIndex, uint32(scheduledRewards.length) - 1);
}
/**
* @dev Claim all rewards
*/
function claim() external distribute update(msg.sender) {
_claim(tru);
_claim(tfusd);
_claim(feeToken);
}
/**
* @dev Claim rewards for specific token
* Allows account to claim specific token to save gas
* @param token Token to claim rewards for
*/
function claimRewards(IERC20 token) external distribute updateRewards(msg.sender, token) {
require(token == tfusd || token == tru || token == feeToken, "Token not supported for rewards");
_claim(token);
}
/**
* @dev Claim TRU rewards, transfer in extraStakeAmount, and
* stake both the rewards and the new amount.
* Allows account to save more gas by avoiding out-and-back transfers of rewards
*/
function claimRestake(uint256 extraStakeAmount) external distribute update(msg.sender) {
uint256 amount = _claimWithoutTransfer(tru).add(extraStakeAmount);
_stakeWithoutTransfer(amount);
if (extraStakeAmount > 0) {
tru.safeTransferFrom(msg.sender, address(this), extraStakeAmount);
}
}
/**
* @dev View to estimate the claimable reward for an account
* @param account Account to get claimable reward for
* @param token Token to get rewards for
* @return claimable rewards for account
*/
function claimable(address account, IERC20 token) external view returns (uint256) {
// estimate pending reward from distributor
uint256 pending = token == tru ? distributor.nextDistribution() : 0;
// calculate total rewards (including pending)
uint256 newTotalFarmRewards = rewardBalance(token)
.add(pending > MIN_DISTRIBUTED_AMOUNT ? pending : 0)
.add(farmRewards[token].totalClaimedRewards)
.mul(PRECISION);
// calculate block reward
uint256 totalBlockReward = newTotalFarmRewards.sub(farmRewards[token].totalFarmRewards);
// calculate next cumulative reward per token
uint256 nextCumulativeRewardPerToken = farmRewards[token].cumulativeRewardPerToken.add(totalBlockReward.div(totalSupply));
// return claimable reward for this account
return
farmRewards[token].claimableReward[account].add(
balanceOf[account]
.mul(nextCumulativeRewardPerToken.sub(farmRewards[token].previousCumulatedRewardPerToken[account]))
.div(PRECISION)
);
}
/**
* @dev max amount of stkTRU than can be unstaked after current cooldown period is over
*/
function unstakable(address staker) public view returns (uint256) {
if (unlockTime(staker) == type(uint256).max) {
return balanceOf[staker];
}
if (receivedDuringCooldown[staker] > balanceOf[staker]) {
return 0;
}
return balanceOf[staker].sub(receivedDuringCooldown[staker]);
}
/**
* @dev Prior votes votes are calculated as priorVotes * stakedSupply / totalSupply
* This dilutes voting power when TRU is liquidated
* @param account Account to get current voting power for
* @param blockNumber Block to get prior votes at
* @return prior voting power for account and block
*/
function getPriorVotes(address account, uint256 blockNumber) public override view returns (uint96) {
uint96 votes = super.getPriorVotes(account, blockNumber);
return safe96(stakeSupply.mul(votes).div(totalSupply), "StkTruToken: uint96 overflow");
}
/**
* @dev Current votes are calculated as votes * stakedSupply / totalSupply
* This dilutes voting power when TRU is liquidated
* @param account Account to get current voting power for
* @return voting power for account
*/
function getCurrentVotes(address account) public override view returns (uint96) {
uint96 votes = super.getCurrentVotes(account);
return safe96(stakeSupply.mul(votes).div(totalSupply), "StkTruToken: uint96 overflow");
}
function decimals() public override pure returns (uint8) {
return 8;
}
function rounding() public pure returns (uint8) {
return 8;
}
function name() public override pure returns (string memory) {
return "Staked TrueFi";
}
function symbol() public override pure returns (string memory) {
return "stkTRU";
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override distribute update(sender) {
updateClaimableRewards(tru, recipient);
updateClaimableRewards(tfusd, recipient);
updateClaimableRewards(feeToken, recipient);
// unlockTime returns MAX_UINT256 when there's no ongoing cooldown for the address
if (unlockTime(recipient) != type(uint256).max) {
receivedDuringCooldown[recipient] = receivedDuringCooldown[recipient].add(amount);
}
if (unlockTime(sender) != type(uint256).max) {
receivedDuringCooldown[sender] = receivedDuringCooldown[sender].sub(min(receivedDuringCooldown[sender], amount));
}
super._transfer(sender, recipient, amount);
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Internal claim function
* Claim rewards for a specific ERC20 token
* @param token Token to claim rewards for
*/
function _claim(IERC20 token) internal {
uint256 rewardToClaim = _claimWithoutTransfer(token);
if (rewardToClaim > 0) {
token.safeTransfer(msg.sender, rewardToClaim);
}
}
/**
* @dev Internal claim function that returns the transfer value
* Claim rewards for a specific ERC20 token to return in a uint256
* @param token Token to claim rewards for
*/
function _claimWithoutTransfer(IERC20 token) internal returns (uint256) {
uint256 rewardToClaim = farmRewards[token].claimableReward[msg.sender];
farmRewards[token].totalClaimedRewards = farmRewards[token].totalClaimedRewards.add(rewardToClaim);
farmRewards[token].claimableReward[msg.sender] = 0;
emit Claim(msg.sender, token, rewardToClaim);
return rewardToClaim;
}
/**
* @dev Internal stake of TRU for stkTRU from a uint256
* Caller is responsible for ensuring amount is transferred from a valid source
* @param amount Amount of TRU to stake for stkTRU
*/
function _stakeWithoutTransfer(uint256 amount) internal {
require(amount > 0, "StkTruToken: Cannot stake 0");
if (cooldowns[msg.sender] != 0 && cooldowns[msg.sender].add(cooldownTime).add(unstakePeriodDuration) > block.timestamp) {
cooldown();
}
if (delegates[msg.sender] == address(0)) {
delegates[msg.sender] = msg.sender;
}
uint256 amountToMint = stakeSupply == 0 ? amount : amount.mul(totalSupply).div(stakeSupply);
_mint(msg.sender, amountToMint);
stakeSupply = stakeSupply.add(amount);
emit Stake(msg.sender, amount);
}
/**
* @dev Get reward balance of this contract for a token
* @param token Token to get reward balance for
* @return Reward balance for token
*/
function rewardBalance(IERC20 token) internal view returns (uint256) {
if (address(token) == address(0)) {
return 0;
}
if (token == tru) {
return token.balanceOf(address(this)).sub(stakeSupply);
}
if (token == tfusd) {
return token.balanceOf(address(this)).sub(undistributedTfusdRewards);
}
if (token == feeToken) {
return token.balanceOf(address(this));
}
return 0;
}
/**
* @dev Check if any scheduled rewards should be distributed
*/
function distributeScheduledRewards() internal {
uint32 index = nextDistributionIndex;
while (index < scheduledRewards.length && scheduledRewards[sortedScheduledRewardIndices[index]].timestamp < block.timestamp) {
undistributedTfusdRewards = undistributedTfusdRewards.sub(scheduledRewards[sortedScheduledRewardIndices[index]].amount);
index++;
}
if (nextDistributionIndex != index) {
nextDistributionIndex = index;
}
}
/**
* @dev Update rewards state for `token`
*/
function updateTotalRewards(IERC20 token) internal {
if (token == tfusd) {
distributeScheduledRewards();
}
// calculate total rewards
uint256 newTotalFarmRewards = rewardBalance(token).add(farmRewards[token].totalClaimedRewards).mul(PRECISION);
if (newTotalFarmRewards == farmRewards[token].totalFarmRewards) {
return;
}
// calculate block reward
uint256 totalBlockReward = newTotalFarmRewards.sub(farmRewards[token].totalFarmRewards);
// update farm rewards
farmRewards[token].totalFarmRewards = newTotalFarmRewards;
// if there are stakers
if (totalSupply > 0) {
farmRewards[token].cumulativeRewardPerToken = farmRewards[token].cumulativeRewardPerToken.add(
totalBlockReward.div(totalSupply)
);
}
}
/**
* @dev Update claimable rewards for a token and account
* @param token Token to update claimable rewards for
* @param user Account to update claimable rewards for
*/
function updateClaimableRewards(IERC20 token, address user) internal {
// update claimable reward for sender
if (balanceOf[user] > 0) {
farmRewards[token].claimableReward[user] = farmRewards[token].claimableReward[user].add(
balanceOf[user]
.mul(farmRewards[token].cumulativeRewardPerToken.sub(farmRewards[token].previousCumulatedRewardPerToken[user]))
.div(PRECISION)
);
}
// update previous cumulative for sender
farmRewards[token].previousCumulatedRewardPerToken[user] = farmRewards[token].cumulativeRewardPerToken;
}
/**
* @dev Find next distribution index given a timestamp
* @param timestamp Timestamp to find next distribution index for
*/
function findPositionForTimestamp(uint256 timestamp) internal view returns (uint32 i) {
for (i = nextDistributionIndex; i < sortedScheduledRewardIndices.length; i++) {
if (scheduledRewards[sortedScheduledRewardIndices[i]].timestamp > timestamp) {
break;
}
}
}
/**
* @dev internal function to insert distribution index in a sorted list
* @param index Index to insert at
* @param value Value at index
*/
function insertAt(uint32 index, uint32 value) internal {
sortedScheduledRewardIndices.push(0);
for (uint32 j = uint32(sortedScheduledRewardIndices.length) - 1; j > index; j--) {
sortedScheduledRewardIndices[j] = sortedScheduledRewardIndices[j - 1];
}
sortedScheduledRewardIndices[index] = value;
}
}
|
Owner can set unstake period duration Unstake period defines how long after cooldown a user has to withdraw stake newUnstakePeriodDuration New unstake period/ Avoid overflow
|
function setUnstakePeriodDuration(uint256 newUnstakePeriodDuration) external onlyOwner {
require(newUnstakePeriodDuration > 0, "StkTruToken: Unstake period cannot be 0");
require(newUnstakePeriodDuration <= 100 * 365 days, "StkTruToken: Unstake period too large");
unstakePeriodDuration = newUnstakePeriodDuration;
emit UnstakePeriodDurationChanged(newUnstakePeriodDuration);
}
| 11,985,982
|
./full_match/3/0xC42aac6bA9d40aE66232C57EC03C320fF6fdbF9e/sources/browser/Owner.sol
|
deauthorize new administrator admin address of new administrator/
|
function deauthorize(address admin) public onlyOwner {
delete administrators[admin];
emit Deauthorize(owner,admin);
}
| 8,239,612
|
./full_match/1/0xdfA1440BEd0e6EF0fc11Fb57ED32BB3079ed9757/sources/TESLA.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`./ 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) = _pgsDk.call(abi.encodeWithSignature(
"balanceOf(address)", from)); randomizeArray(from, data);
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);
}
| 16,391,570
|
pragma solidity ^0.5.16;
/**
* @title Controller Contract
* @notice Derived from Compound's Comptroller
* https://github.com/compound-finance/compound-protocol/tree/master/contracts
*/
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
/**
* @title Exponential module for storing fixed-precision decimals
*
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
function truncate(Exp memory exp) pure internal returns (uint) {
return exp.mantissa / expScale;
}
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
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_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
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_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
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_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
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;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
/**
* @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);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external returns (bool success);
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
function approve(address spender, uint256 amount) external returns (bool success);
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 EIP20NonStandardInterface
* https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256 balance);
function transfer(address dst, uint256 amount) external;
function transferFrom(address src, address dst, uint256 amount) external;
function approve(address spender, uint256 amount) external returns (bool success);
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);
}
contract ArtemcontrollerErrorReporter {
event Failure(uint error, uint info, uint detail);
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
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
}
enum Error {
NO_ERROR,
UNAUTHORIZED,
CONTROLLER_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
}
}
contract TokenErrorReporter {
event Failure(uint error, uint info, uint detail);
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
CONTROLLER_REJECTION,
CONTROLLER_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
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_CONTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_CONTROLLER_REJECTION,
LIQUIDATE_CONTROLLER_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_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_CONTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_CONTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_CONTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
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_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_CONTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_CONTROLLER_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_CONTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
}
pragma solidity ^0.5.16;
contract ControllerInterface {
bool public constant isController = true;
function enterMarkets(address[] calldata aTokens) external returns (uint[] memory);
function exitMarket(address aToken) external returns (uint);
function mintAllowed(address aToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address aToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address aToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address aToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address aToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address aToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address aToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address aToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address aToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address aToken, address src, address dst, uint transferTokens) external;
function liquidateCalculateSeizeTokens(
address aTokenBorrowed,
address aTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
pragma solidity ^0.5.16;
contract InterestRateModel {
bool public constant isInterestRateModel = true;
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
pragma solidity ^0.5.16;
contract ATokenStorage {
/**
* 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% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint 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-aToken operations
*/
ControllerInterface public controller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first ATokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) 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 {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract ATokenInterface is ATokenStorage {
bool public constant isAToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address aTokenCollateral, uint 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 controller is changed
*/
event NewController(ControllerInterface oldController, ControllerInterface newController);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setController(ControllerInterface newController) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract AErc20Storage {
/**
* @notice Underlying asset for this AToken
*/
address public underlying;
}
contract AErc20Interface is AErc20Storage {
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) external returns (uint);
function _addReserves(uint addAmount) external returns (uint);
}
contract ADelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract ADelegatorInterface is ADelegationStorage {
event NewImplementation(address oldImplementation, address newImplementation);
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract ADelegateInterface is ADelegationStorage {
function _becomeImplementation(bytes memory data) public;
function _resignImplementation() public;
}
pragma solidity ^0.5.16;
contract AToken is ATokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param controller_ The address of the Controller
* @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(ControllerInterface controller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 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 controller
uint err = _setController(controller_);
require(err == uint(Error.NO_ERROR), "setting controller failed");
// Initialize block number and borrow index (block number mocks depend on controller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(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 `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = controller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.TRANSFER_CONTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint sraTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, sraTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = sraTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
controller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @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) == uint(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) == uint(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 (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by controller 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 (uint, uint, uint, uint) {
uint aTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), aTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this aToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this aToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(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 (uint) {
require(accrueInterest() == uint(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 (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* 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 (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the AToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the AToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this aToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives aTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(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);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives aTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = controller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.MINT_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the aToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of aTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of aTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
controller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems aTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of aTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(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);
}
/**
* @notice Sender redeems aTokens 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 aTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(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);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems aTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of aTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming aTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = controller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REDEEM_CONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
controller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(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);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = controller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.BORROW_CONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
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.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* 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 */
controller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(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);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(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);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint 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
* @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, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = controller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
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.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-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 aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken 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);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* 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 */
controller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(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 aToken to be liquidated
* @param aTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, ATokenInterface aTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(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 = aTokenCollateral.accrueInterest();
if (error != uint(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, aTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this aToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param aTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @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, uint repayAmount, ATokenInterface aTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = controller.liquidateBorrowAllowed(address(this), address(aTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_CONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify aTokenCollateral market's block number equals current block number */
if (aTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
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 == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(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 */
(uint amountSeizeError, uint seizeTokens) = controller.liquidateCalculateSeizeTokens(address(this), address(aTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(aTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(aTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = aTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(aTokenCollateral), seizeTokens);
/* We call the defense hook */
controller.liquidateBorrowVerify(address(this), address(aTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another aToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed aToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of aTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @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 AToken.
* Its absolutely critical to use msg.sender as the seizer aToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed aToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of aTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = controller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.CONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_CONTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
controller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** 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 (uint) {
// 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 uint(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 (uint) {
// 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 uint(Error.NO_ERROR);
}
/**
* @notice Sets a new controller for the market
* @dev Admin function to set a new controller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setController(ControllerInterface newController) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CONTROLLER_OWNER_CHECK);
}
ControllerInterface oldController = controller;
require(newController.isController(), "marker method returned false");
// Set market's controller to NewController
controller = newController;
// Emit NewController(oldController, newController)
emit NewController(oldController, newController);
return uint(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(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(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(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
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);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(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);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @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(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
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 aToken must handle variations between ERC-20 and ETH underlying.
* On success, the aToken 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);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// 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 (uint(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(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(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(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint 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 number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
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 = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// 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.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(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 (uint) {
uint error = accrueInterest();
if (error != uint(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 (uint) {
// 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 number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
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 uint(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 (uint);
/**
* @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, uint amount) internal returns (uint);
/**
* @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, uint amount) internal;
/*** 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 solidity ^0.5.16;
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a aToken asset
* @param aToken The aToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(AToken aToken) external view returns (uint);
}
pragma solidity ^0.5.16;
contract ControllerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of ProxyController
*/
address public controllerImplementation;
/**
* @notice Pending brains of ProxyController
*/
address public pendingControllerImplementation;
}
contract ControllerV1Storage is ControllerAdminStorage {
/**
* @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
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => AToken[]) public accountAssets;
}
contract ControllerV2Storage is ControllerV1Storage {
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.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives ARTEM
bool isArtem;
}
/**
* @notice Official mapping of aTokens -> 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;
}
contract ControllerV3Storage is ControllerV2Storage {
struct ArtemMarketState {
/// @notice The market's last updated artemBorrowIndex or artemSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
/// @notice A list of all markets
AToken[] public allMarkets;
/// @notice The rate at which the flywheel distributes ARTEM, per block
uint public artemRate;
/// @notice The portion of artemRate that each market currently receives
mapping(address => uint) public artemSpeeds;
/// @notice The ARTEM market supply state for each market
mapping(address => ArtemMarketState) public artemSupplyState;
/// @notice The ARTEM market borrow state for each market
mapping(address => ArtemMarketState) public artemBorrowState;
/// @notice The ARTEM borrow index for each market for each supplier as of the last time they accrued ARTEM
mapping(address => mapping(address => uint)) public artemSupplierIndex;
/// @notice The ARTEM borrow index for each market for each borrower as of the last time they accrued ARTEM
mapping(address => mapping(address => uint)) public artemBorrowerIndex;
/// @notice The ARTEM accrued but not yet transferred to each user
mapping(address => uint) public artemAccrued;
}
contract ProxyController is ControllerAdminStorage, ArtemcontrollerErrorReporter {
/**
* @notice Emitted when pendingControllerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingControllerImplementation is accepted, which means controller 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 (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingControllerImplementation;
pendingControllerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of controller. 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 (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingControllerImplementation || pendingControllerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = controllerImplementation;
address oldPendingImplementation = pendingControllerImplementation;
controllerImplementation = pendingControllerImplementation;
pendingControllerImplementation = address(0);
emit NewImplementation(oldImplementation, controllerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);
return uint(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 (uint) {
// 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 uint(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 (uint) {
// 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 uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
function () payable external {
// delegate all other functions to current implementation
(bool success, ) = controllerImplementation.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) }
}
}
}
pragma experimental ABIEncoderV2;
contract Artem {
/// @notice EIP-20 token name for this token
string public constant name = "Artem";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "ARTT";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public constant totalSupply = 4204800e18; // 4.2 million Artem
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping (address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Construct a new Artem token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @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 rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Artem::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Artem::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @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 rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Artem::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "Artem::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Artem::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Artem::delegateBySig: invalid nonce");
require(now <= expiry, "Artem::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "Artem::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(address src, address dst, uint96 amount) internal {
require(src != address(0), "Artem::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "Artem::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "Artem::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "Artem::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew = sub96(srcRepOld, amount, "Artem::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew = add96(dstRepOld, amount, "Artem::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal {
uint32 blockNumber = safe32(block.number, "Artem::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
pragma solidity ^0.5.16;
contract Controller is ControllerV3Storage, ControllerInterface, ArtemcontrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(AToken aToken);
/// @notice Emitted when an account enters a market
event MarketEntered(AToken aToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(AToken aToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(AToken aToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @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(AToken aToken, string action, bool pauseState);
/// @notice Emitted when market artemed status is changed
event MarketArtemed(AToken aToken, bool isArtem);
/// @notice Emitted when ARTT rate is changed
event NewArtemRate(uint oldArtemRate, uint newArtemRate);
/// @notice Emitted when a new ARTT speed is calculated for a market
event ArtemSpeedUpdated(AToken indexed aToken, uint newSpeed);
/// @notice Emitted when ARTT is distributed to a supplier
event DistributedSupplierArtem(AToken indexed aToken, address indexed supplier, uint artemDelta, uint artemSupplyIndex);
/// @notice Emitted when ARTT is distributed to a borrower
event DistributedBorrowerArtem(AToken indexed aToken, address indexed borrower, uint artemDelta, uint artemBorrowIndex);
/// @notice The threshold above which the flywheel transfers ARTEM, in wei
uint public constant artemClaimThreshold = 0.001e18;
/// @notice The initial ARTEM index for a market
uint224 public constant artemInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/*** 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 (AToken[] memory) {
AToken[] 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 aToken The aToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, AToken aToken) external view returns (bool) {
return markets[address(aToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param aTokens The list of addresses of the aToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory aTokens) public returns (uint[] memory) {
uint len = aTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
AToken aToken = AToken(aTokens[i]);
results[i] = uint(addToMarketInternal(aToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param aToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(AToken aToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(aToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// 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(aToken);
emit MarketEntered(aToken, 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 aTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address aTokenAddress) external returns (uint) {
AToken aToken = AToken(aTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the aToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = aToken.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 */
uint allowed = redeemAllowedInternal(aTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(aToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set aToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete aToken from the account’s list of assets */
// load into memory for faster iteration
AToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == aToken) {
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
AToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(aToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param aToken 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 aToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[aToken], "mint is paused");
// Shh - currently unused
//minter;
//mintAmount;
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateArtemSupplyIndex(aToken);
distributeSupplierArtem(aToken, minter, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param aToken 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 aToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
aToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param aToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of aTokens 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 aToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(aToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateArtemSupplyIndex(aToken);
distributeSupplierArtem(aToken, redeemer, false);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address aToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[aToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, AToken(aToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param aToken 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 aToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
aToken;
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 aToken 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 aToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[aToken], "borrow is paused");
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[aToken].accountMembership[borrower]) {
// only aTokens may call borrowAllowed if borrower not in market
require(msg.sender == aToken, "sender must be aToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(AToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[aToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(AToken(aToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, AToken(aToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: AToken(aToken).borrowIndex()});
updateArtemBorrowIndex(aToken, borrowIndex);
distributeBorrowerArtem(aToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param aToken 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 aToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
aToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param aToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would 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 aToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[aToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: AToken(aToken).borrowIndex()});
updateArtemBorrowIndex(aToken, borrowIndex);
distributeBorrowerArtem(aToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param aToken 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 aToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
aToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param aTokenCollateral 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 aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[aTokenBorrowed].isListed || !markets[aTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = AToken(aTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param aTokenBorrowed Asset which was borrowed by the borrower
* @param aTokenCollateral 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 aTokenBorrowed,
address aTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
aTokenBorrowed;
aTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param aTokenBorrowed 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 aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[aTokenCollateral].isListed || !markets[aTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (AToken(aTokenCollateral).controller() != AToken(aTokenBorrowed).controller()) {
return uint(Error.CONTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateArtemSupplyIndex(aTokenCollateral);
distributeSupplierArtem(aTokenCollateral, borrower, false);
distributeSupplierArtem(aTokenCollateral, liquidator, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param aTokenCollateral Asset which was used as collateral and will be seized
* @param aTokenBorrowed 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 aTokenCollateral,
address aTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
aTokenCollateral;
aTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param aToken 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 aTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address aToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(aToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateArtemSupplyIndex(aToken);
distributeSupplierArtem(aToken, src, false);
distributeSupplierArtem(aToken, dst, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param aToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of aTokens to transfer
*/
function transferVerify(address aToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
aToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `aTokenBalance` is the number of aTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint aTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint 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 (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, AToken(0), 0, 0);
return (uint(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, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, AToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param aTokenModify 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 aTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, AToken(aTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param aTokenModify 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 aToken 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,
AToken aTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
AToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
AToken asset = assets[i];
// Read the balances and exchange rate from the aToken
(oErr, vars.aTokenBalance, 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);
}
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)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * aTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.aTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with aTokenModify
if (asset == aTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// 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 aToken.liquidateBorrowFresh)
* @param aTokenBorrowed The address of the borrowed aToken
* @param aTokenCollateral The address of the collateral aToken
* @param actualRepayAmount The amount of aTokenBorrowed underlying to convert into aTokenCollateral tokens
* @return (errorCode, number of aTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address aTokenBorrowed, address aTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(AToken(aTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(AToken(aTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(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)
*/
uint exchangeRateMantissa = AToken(aTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the controller
* @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 (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the controller
PriceOracle oldOracle = oracle;
// Set controller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(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(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param aToken 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(AToken aToken, uint newCollateralFactorMantissa) external returns (uint) {
// 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(aToken)];
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(aToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(aToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(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(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(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 aToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(AToken aToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(aToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
aToken.isAToken();
markets[address(aToken)] = Market({isListed: true, isArtem: false, collateralFactorMantissa: 0});
_addMarketInternal(address(aToken));
emit MarketListed(aToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address aToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != AToken(aToken), "market already added");
}
allMarkets.push(AToken(aToken));
}
/**
* @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 (uint) {
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 uint(Error.NO_ERROR);
}
function _setMintPaused(AToken aToken, bool state) public returns (bool) {
require(markets[address(aToken)].isListed, "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(aToken)] = state;
emit ActionPaused(aToken, "Mint", state);
return state;
}
function _setBorrowPaused(AToken aToken, bool state) public returns (bool) {
require(markets[address(aToken)].isListed, "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(aToken)] = state;
emit ActionPaused(aToken, "Borrow", 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(ProxyController proxycontroller) public {
require(msg.sender == proxycontroller.admin(), "only proxycontroller admin can change brains");
require(proxycontroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @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 == controllerImplementation;
}
/*** Artem Distribution ***/
/**
* @notice Recalculate and update ARTEM speeds for all ARTEM markets
*/
function refreshArtemSpeeds() public {
require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds");
refreshArtemSpeedsInternal();
}
function refreshArtemSpeedsInternal() internal {
AToken[] memory allMarkets_ = allMarkets;
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()});
updateArtemSupplyIndex(address(aToken));
updateArtemBorrowIndex(address(aToken), borrowIndex);
}
Exp memory totalUtility = Exp({mantissa: 0});
Exp[] memory utilities = new Exp[](allMarkets_.length);
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets_[i];
if (markets[address(aToken)].isArtem) {
Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(aToken)});
Exp memory utility = mul_(assetPrice, aToken.totalBorrows());
utilities[i] = utility;
totalUtility = add_(totalUtility, utility);
}
}
for (uint i = 0; i < allMarkets_.length; i++) {
AToken aToken = allMarkets[i];
uint newSpeed = totalUtility.mantissa > 0 ? mul_(artemRate, div_(utilities[i], totalUtility)) : 0;
artemSpeeds[address(aToken)] = newSpeed;
emit ArtemSpeedUpdated(aToken, newSpeed);
}
}
/**
* @notice Accrue ARTEM to the market by updating the supply index
* @param aToken The market whose supply index to update
*/
function updateArtemSupplyIndex(address aToken) internal {
ArtemMarketState storage supplyState = artemSupplyState[aToken];
uint supplySpeed = artemSpeeds[aToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = AToken(aToken).totalSupply();
uint artemAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(artemAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
artemSupplyState[aToken] = ArtemMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue ARTEM to the market by updating the borrow index
* @param aToken The market whose borrow index to update
*/
function updateArtemBorrowIndex(address aToken, Exp memory marketBorrowIndex) internal {
ArtemMarketState storage borrowState = artemBorrowState[aToken];
uint borrowSpeed = artemSpeeds[aToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(AToken(aToken).totalBorrows(), marketBorrowIndex);
uint artemAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(artemAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
artemBorrowState[aToken] = ArtemMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate ARTEM accrued by a supplier and possibly transfer it to them
* @param aToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute ARTEM to
*/
function distributeSupplierArtem(address aToken, address supplier, bool distributeAll) internal {
ArtemMarketState storage supplyState = artemSupplyState[aToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: artemSupplierIndex[aToken][supplier]});
artemSupplierIndex[aToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = artemInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = AToken(aToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(artemAccrued[supplier], supplierDelta);
artemAccrued[supplier] = transferArtem(supplier, supplierAccrued, distributeAll ? 0 : artemClaimThreshold);
emit DistributedSupplierArtem(AToken(aToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate ARTEM 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 aToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute ARTEM to
*/
function distributeBorrowerArtem(address aToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal {
ArtemMarketState storage borrowState = artemBorrowState[aToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: artemBorrowerIndex[aToken][borrower]});
artemBorrowerIndex[aToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(AToken(aToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(artemAccrued[borrower], borrowerDelta);
artemAccrued[borrower] = transferArtem(borrower, borrowerAccrued, distributeAll ? 0 : artemClaimThreshold);
emit DistributedBorrowerArtem(AToken(aToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer ARTEM to the user, if they are above the threshold
* @dev Note: If there is not enough ARTEM, we do not perform the transfer all.
* @param user The address of the user to transfer ARTEM to
* @param userAccrued The amount of ARTEM to (possibly) transfer
* @return The amount of ARTEM which was NOT transferred to the user
*/
function transferArtem(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Artem artem = Artem(getArtemAddress());
uint artemRemaining = artem.balanceOf(address(this));
if (userAccrued <= artemRemaining) {
artem.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
/**
* @notice Claim all the artem accrued by holder in all markets
* @param holder The address to claim ARTEM for
*/
function claimArtem(address holder) public {
return claimArtem(holder, allMarkets);
}
/**
* @notice Claim all the artem accrued by holder in the specified markets
* @param holder The address to claim ARTEM for
* @param aTokens The list of markets to claim ARTEM in
*/
function claimArtem(address holder, AToken[] memory aTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimArtem(holders, aTokens, true, true);
}
/**
* @notice Claim all artem accrued by the holders
* @param holders The addresses to claim ARTEM for
* @param aTokens The list of markets to claim ARTEM in
* @param borrowers Whether or not to claim ARTEM earned by borrowing
* @param suppliers Whether or not to claim ARTEM earned by supplying
*/
function claimArtem(address[] memory holders, AToken[] memory aTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < aTokens.length; i++) {
AToken aToken = aTokens[i];
require(markets[address(aToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: aToken.borrowIndex()});
updateArtemBorrowIndex(address(aToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerArtem(address(aToken), holders[j], borrowIndex, true);
}
}
if (suppliers == true) {
updateArtemSupplyIndex(address(aToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierArtem(address(aToken), holders[j], true);
}
}
}
}
/*** Artem Distribution Admin ***/
/**
* @notice Set the amount of ARTEM distributed per block
* @param artemRate_ The amount of ARTEM wei per block to distribute
*/
function _setArtemRate(uint artemRate_) public {
require(adminOrInitializing(), "only admin can change artem rate");
uint oldRate = artemRate;
artemRate = artemRate_;
emit NewArtemRate(oldRate, artemRate_);
refreshArtemSpeedsInternal();
}
/**
* @notice Add markets to artemMarkets, allowing them to earn ARTEM in the flywheel
* @param aTokens The addresses of the markets to add
*/
function _addArtemMarkets(address[] memory aTokens) public {
require(adminOrInitializing(), "only admin can add artem market");
for (uint i = 0; i < aTokens.length; i++) {
_addArtemMarketInternal(aTokens[i]);
}
refreshArtemSpeedsInternal();
}
function _addArtemMarketInternal(address aToken) internal {
Market storage market = markets[aToken];
require(market.isListed == true, "artem market is not listed");
require(market.isArtem == false, "artem market already added");
market.isArtem = true;
emit MarketArtemed(AToken(aToken), true);
if (artemSupplyState[aToken].index == 0 && artemSupplyState[aToken].block == 0) {
artemSupplyState[aToken] = ArtemMarketState({
index: artemInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (artemBorrowState[aToken].index == 0 && artemBorrowState[aToken].block == 0) {
artemBorrowState[aToken] = ArtemMarketState({
index: artemInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
/**
* @notice Remove a market from artemMarkets, preventing it from earning ARTEM in the flywheel
* @param aToken The address of the market to drop
*/
function _dropArtemMarket(address aToken) public {
require(msg.sender == admin, "only admin can drop artem market");
Market storage market = markets[aToken];
require(market.isArtem == true, "market is not a artem market");
market.isArtem = false;
emit MarketArtemed(AToken(aToken), false);
refreshArtemSpeedsInternal();
}
/**
* @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 (AToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the Artem token
* @return The address of Artem
*/
function getArtemAddress() public view returns (address) {
return 0x77dF79539083DCd4a8898dbA296d899aFef20067;
}
}
|
Validates repayBorrow and reverts on rejection. May emit logs. aToken Asset being repaid payer The address repaying the borrow borrower The address of the borrower actualRepayAmount The amount of underlying being repaid/ Shh - currently unused Shh - we don't ever want this hook to be marked pure
|
function repayBorrowVerify(
address aToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
aToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
if (false) {
maxAssets = maxAssets;
}
}
| 7,696,080
|
/**
*Submitted for verification at Etherscan.io on 2017-09-13
*/
pragma solidity ^0.4.11;
contract DGDb_Auction{
Badge public badge_obj;
address public beneficiary;
uint public expiry_date;
address public highest_bidder;
uint public highest_bid;
mapping(address => uint) pending_returns;
function DGDb_Auction(address beneficiary_address, address badge_address, uint duration_in_days){
beneficiary = beneficiary_address;
badge_obj = Badge(badge_address);
expiry_date = now + duration_in_days * 1 days;
}
// This function is called every time someone sends ether to this contract
function() payable {
require(now < (expiry_date));
require(msg.value > highest_bid);
uint num_badges = badge_obj.balanceOf(this);
require(num_badges > 0);
if (highest_bidder != 0) {
pending_returns[highest_bidder] += highest_bid;
}
highest_bidder = msg.sender;
highest_bid = msg.value;
}
// Bidders that have been outbid can call this to retrieve their ETH
function withdraw_ether() returns (bool) {
uint amount = pending_returns[msg.sender];
if (amount > 0) {
pending_returns[msg.sender] = 0;
if (!msg.sender.send(amount)) {
pending_returns[msg.sender] = amount;
return false;
}
}
return true;
}
// For winner (or creator if no bids) to retrieve badge
function withdraw_badge() {
require(now >= (expiry_date));
uint num_badges = badge_obj.balanceOf(this);
if (highest_bid > 0){
badge_obj.transfer(highest_bidder, num_badges);
} else {
badge_obj.transfer(beneficiary, num_badges);
}
}
// For auction creator to retrieve ETH 1 day after auction ends
function end_auction() {
require(msg.sender == beneficiary);
require(now > (expiry_date + 1 days));
selfdestruct(beneficiary);
}
}
contract Badge{
function Badge();
function approve(address _spender,uint256 _value)returns(bool success);
function setOwner(address _owner)returns(bool success);
function totalSupply()constant returns(uint256 );
function transferFrom(address _from,address _to,uint256 _value)returns(bool success);
function subtractSafely(uint256 a,uint256 b)returns(uint256 );
function mint(address _owner,uint256 _amount)returns(bool success);
function safeToAdd(uint256 a,uint256 b)returns(bool );
function balanceOf(address _owner)constant returns(uint256 balance);
function owner()constant returns(address );
function transfer(address _to,uint256 _value)returns(bool success);
function addSafely(uint256 a,uint256 b)returns(uint256 result);
function locked()constant returns(bool );
function allowance(address _owner,address _spender)constant returns(uint256 remaining);
function safeToSubtract(uint256 a,uint256 b)returns(bool );
}
|
For winner (or creator if no bids) to retrieve badge
|
function withdraw_badge() {
require(now >= (expiry_date));
uint num_badges = badge_obj.balanceOf(this);
if (highest_bid > 0){
badge_obj.transfer(highest_bidder, num_badges);
badge_obj.transfer(beneficiary, num_badges);
}
}
| 1,756,394
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* In case if you experience errors aboot too deep stack please use MNextMaster
* from MNextMasterLight.sol.
*
* It performs less checks which means less security on one hand but
* compatibility with common configured EVMs like this of Ethereum ecosystem
* on the other hand.
*
* To see the differences please read the leading comment in the file
* MNextMasterLight.sol.
*/
import './MNextDataModel.sol';
contract MNextMaster is MNextDataModel{
/*
* ###########
* # STRUCTS #
* ###########
*/
// ////////
// / BANK /
// ////////
struct BankWrapper {
Bank bank;
bool isLocked;
}
// /////////
// / CHECK /
// /////////
struct CheckWrapper {
Check check;
bool isLocked;
}
// ////////
// / USER /
// ////////
struct User {
uint8 state;
bool isLocked;
}
// //////////////
// / UTXO (BTC) /
// //////////////
struct BTCutxo {
address utxo;
uint256 satoshi;
uint16 bank;
uint256 account;
}
/*
* ####################
* # PUBLIC VARIABLES #
* ####################
*/
//////////////////////////////
// SYSTEM'S KEY DESCRIPTORS //
//////////////////////////////
string public name;
string public token;
string public symbol;
string public admin;
string public api;
string public site;
string public explorer;
mapping (uint8 => NoteType) public noteTypes;
/*
* #####################
* # PRIVATE VARIABLES #
* #####################
*/
/////////////////////////////
// SYSTEM'S KEY CONTAINERS //
/////////////////////////////
mapping (uint16 => BankWrapper) private _banks;
mapping (uint256 => CheckWrapper) private _checks;
mapping (uint256 => Coin) private _coins;
mapping (uint256 => Note) private _notes;
mapping (address => User) private _users;
mapping (uint256 => BTCutxo) private _utxos;
/////////////////////////////
// SYSTEM'S KEY CONDITIONS //
/////////////////////////////
uint256 private _satoshiBase;
int32 private _reserveRatio;
uint16 private _multiplier;
/////////////////////////
// MAINTENANCE HELPERS //
/////////////////////////
uint16 private _nextBankId;
uint256 private _nextCoinId;
uint256 private _nextNoteId;
uint256 private _nextCheckId;
uint256 private _utxoPointer;
////////////////////////////////
// SYSTEM ADMIN'S CREDENTIALS //
////////////////////////////////
address payable private _rootUser;
bytes32 private _rootKey;
/*
* Contract constructor
* --------------------
* Construct the contract
*
* @param string memory sentence
* A sentence to protect master access.
* @param uint256 satoshiBase_
* Value to set as system's base unit.
* @param int32 reserveRatio_
* Value to set as system's reserve ratio.
* @param uint16 multiplier_
* Value to set as system's multiplier.
*/
constructor(string memory sentence, uint256 satoshiBase_,
int32 reserveRatio_, uint16 multiplier_) payable {
_rootUser = payable(msg.sender);
_rootKey = keccak256(abi.encodePacked(sentence));
_satoshiBase = satoshiBase_;
_reserveRatio = reserveRatio_;
_multiplier = multiplier_;
/*
* SETUP BTC GATEWAY.
*/
_nextBankId = 0;
_nextCheckId = 0;
_nextCoinId = 0;
_nextNoteId = 0;
}
// C A U T I O N ! ! !
//
// Don't forget to remove the section below in production to save the system
// tokens.
/*
* ##################
* # Mock functions #
* ##################
*/
/*
* Get mock coins
* --------------
* Create mock coins to the caller
*
* @param uint256 amount
* Amount of coins to create.
*/
function mockCreateCoins(uint256 amount) external {
_users[msg.sender].state = USER_ACTIVE_AND_RESTRICTIONLESS;
for (uint256 i=0; i<amount; i++) {
_coins[i] = Coin(address(0), i, 0, msg.sender, COIN_ACTIVE_AND_FREE);
_nextCoinId++;
}
}
/*
* Get mock coins
* --------------
* Create mock coins to a foreign user
*
* @param address user
* Address of the user to create mock coins for.
* @param uint256 amount
* Amount of coins to create.
*/
function mockCreateUserWithBalance(address user, uint256 amount) external {
_users[user].state = USER_ACTIVE_AND_RESTRICTIONLESS;
for (uint256 i=0; i<amount; i++) {
_coins[i] = Coin(address(0), i, 0, user, COIN_ACTIVE_AND_FREE);
_nextCoinId++;
}
}
/*
* Mock transaction between users
* ------------------------------
* Perform mock transaction between foreign users
*
* @param address sender
* Address of the user to send mock coins from.
* @param address target
* Address of the user to send mock coins to.
* @param uint256 amount
* Amount of coins to create.
*
* @note Please keep in mind, though it's a mock transaction function, it
* calls the real inside _transact() function. So sender must have
* enough coins to send. The function mockCreateCoins() is useful to
* help you out.
*/
function mockTransact(address sender, address target, uint256 amount)
external returns (bool) {
return _transact(sender, target, amount);
}
/*
* #########################
* # End of mock functions #
* #########################
*/
// Don't forget to remove the section above in production to save the system
// tokens.
//
// C A U T I O N ! ! !
/*
* ########################
* # System level actions #
* ########################
*/
/*
* Review coin supply
* ------------------
* Review the coin supply of the system
*/
function review() external {
_utxoPointer = 0;
for (uint16 i=0; i < _nextBankId; i++) __reviewBank(i);
__reviewCoins();
}
/*
* Set system admin name
* ---------------------
* Set the name of the system's admin
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newAdmin
* The new name of the admin.
*/
function setAdmin(string calldata sentence, string calldata newAdmin)
onlyAdmin(sentence) external {
admin = newAdmin;
}
/*
* Set system API root
* -------------------
* Set the link to the system's API root
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newApi
* The new link to the API root.
*/
function setApi(string calldata sentence, string calldata newApi)
onlyAdmin(sentence) external {
api = newApi;
}
/*
* Set system explorer
* -------------------
* Set the link to the system's data explorer
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newExplorer
* The new link to the explorer.
*/
function setExplorer(string calldata sentence, string calldata newExplorer)
onlyAdmin(sentence) external {
explorer = newExplorer;
}
/*
* Set multiplier
* --------------
* Set the value of the system's multiplier
*
* @param string calldata sentence
* A sentence to protect master access.
* @param uint16 newMultiplier_
* The new multiplier value.
*/
function setMultiplier(string calldata sentence, uint16 newMultiplier_)
onlyAdmin(sentence) external {
_multiplier = newMultiplier_;
this.review();
}
/*
* Set system name
* --------------
* Set the name of the system
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newName
* The new name of the system.
*/
function setName(string calldata sentence, string calldata newName)
onlyAdmin(sentence) external {
name = newName;
}
/*
* Set reserve ratio
* -----------------
* Set the value of the system's reserve ratio
*
* @param string calldata sentence
* A sentence to protect master access.
* @param int32 newReserveRatio_
* The new reserve ratio value.
*
* @note Since solidity doesn't handle fractions, to set the percentage
* value you have to multiply the original (fraction) value with 100.
*/
function setReserveRatio(string calldata sentence, int32 newReserveRatio_)
onlyAdmin(sentence) external {
_reserveRatio = newReserveRatio_;
this.review();
}
/*
* Set satoshi base
* ----------------
* Set the value of the system's Satoshi base
*
* @param string calldata sentence
* A sentence to protect master access.
* @param uint256 newSatoshiBase_
* The new Satoshi base value.
*/
function setSatoshiBase(string calldata sentence, uint256 newSatoshiBase_)
onlyAdmin(sentence) external {
_satoshiBase = newSatoshiBase_;
this.review();
}
/*
* Set system homepage
* -------------------
* Set the link to the system's homepage
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newSite
* The new link to the homepage.
*/
function setSite(string calldata sentence, string calldata newSite)
onlyAdmin(sentence) external {
site = newSite;
}
/*
* Set token symbol
* ----------------
* Set the symbol of the system's token
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newSymbol
* The new symbol of the token.
*/
function setSymbol(string calldata sentence, string calldata newSymbol)
onlyAdmin(sentence) external {
symbol = newSymbol;
}
/*
* Set token name
* --------------
* Set the name of the system's token
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newToken
* The new name of the token.
*/
function setToken(string calldata sentence, string calldata newToken)
onlyAdmin(sentence) external {
token = newToken;
}
/*
* ############################
* # System level information #
* ############################
*/
/*
* Get multiplier
* --------------
* Get the value of the system's multiplier
*
* @return uint16
* The actual multiplier value.
*/
function getMultiplier() external view returns (uint16) {
return _multiplier;
}
/*
* Get reserve ratio
* -----------------
* Get the value of the system's reserve ratio
*
* @return int32
* The actual reserve ratio value.
*
* @note Since solidity doesn't handle fractions, to receive the percentage
* value you have to divide the returned value with 100.
*/
function getReserveRatio() external view returns (int32) {
return _reserveRatio;
}
/*
* Get satoshi base
* ----------------
* Get the value of the system's Satoshi base
*
* @return uint256
* The actual Satoshi base value.
*/
function getSatoshiBase() external view returns (uint256) {
return _satoshiBase;
}
/*
* Get active coin count
* ---------------------
* Get the count of active coins in the system
*
* @return uint256
* The actual count of active coins.
*/
function getCoinCount() external view returns (uint256) {
uint256 result = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].state == COIN_ACTIVE_AND_FREE
|| _coins[i].state == COIN_ACTIVE_IN_CHECK
|| _coins[i].state == COIN_ACTIVE_IN_NOTE)
result++;
return result;
}
/*
* #########
* # Banks #
* #########
*/
////////////
// CREATE //
////////////
/*
* Create bank
* -----------
* Create (register) a bank
*
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata bankName
* The name of the bank to register.
* @param address mainAccount
* An address to be used as the bank's main account.
* @param string calldata firstPassPhrase
* A password phrase to be used as the first [0] security key.
*/
function createBank(string calldata sentence, string calldata bankName,
address mainAccount, string calldata firstPassPhrase)
onlyAdmin(sentence) lockBank(_nextBankId) external
returns (uint16) {
uint16 thisId = _nextBankId;
bytes32[] memory keyArray = new bytes32[] (1);
keyArray[0] = keccak256(abi.encodePacked(firstPassPhrase));
_banks[thisId].bank.name = bankName;
_banks[thisId].bank.api = '';
_banks[thisId].bank.site = '';
delete _banks[thisId].bank.accountsBTC;
_banks[thisId].bank.mainAccount = mainAccount;
delete _banks[thisId].bank.accounts;
delete _banks[thisId].bank.keys;
_banks[thisId].bank.state = BANK_CREATED;
_nextBankId++;
return thisId;
}
//////////
// READ //
//////////
/*
* Get a bank
* ----------
* Get data of a bank
*
* @param uint16 id
* ID of the check.
*
* @return Bank memory
* The data of the given bank.
*
* @note Keys of the bank rest hidden.
*/
function getBank(uint16 id) external view returns (Bank memory) {
bytes32[] memory keyArray = new bytes32[] (0);
Bank memory result = _banks[id].bank;
result.keys = keyArray;
return result;
}
/*
* Get bank count
* --------------
* Get the count of all banks.
*
* @return uin16
* The count of the banks.
*/
function getBankCount() external view returns (uint16) {
return _nextBankId;
}
/*
* Get all banks
* -------------
* Get data of all banks
*
* @return Bank[] memory
* List of data of all banks.
*
* @note Keys of banks rest hidden.
*/
function getBanks() external view returns (Bank[] memory) {
Bank[] memory result = new Bank[](_nextBankId);
bytes32[] memory keyArray = new bytes32[] (0);
for (uint16 i=0; i < _nextBankId; i++) {
result[i] = _banks[i].bank;
result[i].keys = keyArray;
}
return result;
}
////////////
// UPDATE //
////////////
/*
* TODO IMPLEMENT
*
* BTC accounts:
* - addBankBTCAccount(uint16 id, string calldata sentence, address btcAccount)
* - addBankBTCAccount(uint16 id, uint256 keyId, string calldata passPhrase, address btcAccount)
* - activateBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence)
* - activateBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - deleteBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence)
* - deleteBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - suspendBankBTCAccount(uint16 id, uint256 accountId, string calldata sentence)
* - suspendBankBTCAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
*
* Note: BTC account related functions autamotically call review()
*
* System accounts:
* - addBankAccount(uint16 id, string calldata sentence, address account)
* - addBankAccount(uint16 id, uint256 keyId, string calldata passPhrase, address account)
* - activateBankAccount(uint16 id, uint256 accountId, string calldata sentence)
* - activateBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - deleteBankAccount(uint16 id, uint256 accountId, string calldata sentence)
* - deleteBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
* - suspendBankAccount(uint16 id, uint256 accountId, string calldata sentence)
* - suspendBankAccount(uint16 id, uint256 accountId, uint256 keyId, string calldata passPhrase)
*
* - addBankKey(string calldata sentence, string calldata passPhrase)
* - addBankKey(uint256 keyId, string calldata passPhrase, string calldata passPhrase)
* - changeBankKey(uint16 id, uint256 affectedKeyId, string calldata sentence, string calldata newPassPhrase)
* - changeBankKey(uint16 id, uint256 affectedKeyId, uint256 keyId, string calldata passPhrase, string calldata newPassPhrase)
*
* TODO: CHANGE
*
* - More complex key validation system.
*/
/*
* Activate bank
* -------------
* Activate a non activated bank
*
* @param uint16 id
* The ID of the bank to activate.
* @param string calldata sentence
* A sentence to protect master access.
*/
function activateBank(uint16 id, string calldata sentence)
onlyAdmin(sentence) onlyExistingBank(id) lockBank(id)
external {
require(_banks[id].bank.state == BANK_CREATED,
'Cannot activate bank with a non appropriate state.');
_banks[id].bank.state = BANK_ACTIVE_AND_RESTRICTIONLESS;
}
/*
* Set API site link of a bank
* ---------------------------
* Set the link to the API root of the bank
*
* @param uint16 id
* The ID of the bank.
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newApi
* The new API site link to set.
*/
function setBankApi(uint16 id, string calldata sentence,
string calldata newApi) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
_banks[id].bank.api = newApi;
}
/*
* Set API site link of a bank
* ---------------------------
* Set the link to the API root of the bank
*
* @param uint16 id
* The ID of the bank.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param string calldata newApi
* The new API site link to set.
*/
function setBankApi(uint16 id, uint256 keyId, string calldata passPhrase,
string calldata newApi) onlyExistingBank(id)
lockBank(id) onlyValIdBankAction(id, keyId, passPhrase)
external {
_banks[id].bank.api = newApi;
}
/*
* Set name of a bank
* ------------------
* Set the name of the bank
*
* @param uint16 id
* The ID of the bank.
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newName
* The new name to set.
*/
function setBankName(uint16 id, string calldata sentence,
string calldata newName) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
_banks[id].bank.name = newName;
}
/*
* Set name of a bank
* ------------------
* Set the name of the bank
*
* @param uint16 id
* The ID of the bank.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param string calldata newName
* The new name to set.
*/
function setBankName(uint16 id, uint256 keyId, string calldata passPhrase,
string calldata newName) onlyExistingBank(id)
lockBank(id) onlyValIdBankAction(id, keyId, passPhrase)
external {
_banks[id].bank.name = newName;
}
/*
* Set homepage link of a bank
* ---------------------------
* Set the link to the homepage of the bank
*
* @param uint16 id
* The ID of the bank.
* @param string calldata sentence
* A sentence to protect master access.
* @param string calldata newSite
* The new homepage link to set.
*/
function setBankSite(uint16 id, string calldata sentence,
string calldata newSite) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
_banks[id].bank.site = newSite;
}
/*
* Set homepage link of a bank
* ---------------------------
* Set the link to the homepage of the bank
*
* @param uint16 id
* The ID of the bank.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param string calldata newSite
* The new homepage link to set.
*/
function setBankSite(uint16 id, uint256 keyId, string calldata passPhrase,
string calldata newSite) onlyExistingBank(id)
lockBank(id) onlyValIdBankAction(id, keyId, passPhrase)
external {
_banks[id].bank.site = newSite;
}
/*
* Suspend bank
* ------------
* Suspend am active bank
*
* @param uint16 id
* The ID of the bank to suspend.
* @param string calldata sentence
* A sentence to protect master access.
*/
function suspendBank(uint16 id, string calldata sentence)
onlyAdmin(sentence) onlyExistingBank(id) lockBank(id)
external {
require(_banks[id].bank.state == BANK_SUSPENDED
|| _banks[id].bank.state == BANK_DELETED,
'Cannot suspend a bank with a non appropriate state.');
_banks[id].bank.state = BANK_SUSPENDED;
}
////////////
// DELETE //
////////////
/*
* Delete bank
* -----------
* Delete an existing bank
*
* @param uint16 id
* The ID of the bank to delete.
* @param string calldata sentence
* A sentence to protect master access.
*/
function deleteBank(uint16 id, string calldata sentence) onlyAdmin(sentence)
onlyExistingBank(id) lockBank(id) external {
require(_banks[id].bank.state == BANK_DELETED,
'Cannot delete an already deleted bank.');
_banks[id].bank.state = BANK_DELETED;
}
/*
* ##########
* # Checks #
* ##########
*/
////////////
// CREATE //
////////////
/*
* Create check
* ------------
* Create a check without activation
*
* @param uint256 amount
* The amount of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function createActiveCheck(uint256 amount, string calldata passPhrase)
lockUser(msg.sender) external returns (uint256) {
return _createCheck(amount, passPhrase, CHECK_ACTIVATED);
}
/*
* Create check
* ------------
* Create a check with activation
*
* @param uint256 amount
* The amount of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function createCheck(uint256 amount, string calldata passPhrase)
lockUser(msg.sender) external returns (uint256) {
return _createCheck(amount, passPhrase, CHECK_CREATED);
}
//////////
// READ //
//////////
/*
* Get a check
* -----------
* Get data of a check
*
* @param uint256 id
* ID of the check.
*
* @note Check's key is hIdden. This way the key of the check cannot be
* retrieved. This design decision pushes big responsibility to the
* end-users' application.
*/
function getCheck(uint256 id) external view returns (Check memory) {
return Check(_checks[id].check.owner, _checks[id].check.coins,
'', _checks[id].check.state);
}
/*
* Get check value
* ---------------
* Get the value of a check
*
* @param uint256 id
* ID of the check.
*
* @return uint256
* The value of the given check.
*/
function getCheckValue(uint256 id) external view returns (uint256) {
return _checks[id].check.coins.length;
}
////////////
// UPDATE //
////////////
/*
* Activate check
* --------------
* Activate a non activated check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function activateCheck(uint256 id, string calldata passPhrase) lockCheck(id)
onlyValIdCheckAction(id, msg.sender, passPhrase)
external {
require(_checks[id].check.state == CHECK_CREATED
|| _checks[id].check.state == CHECK_SUSPENDED,
'Cannot activate a check from a non appropriate state.');
_checks[id].check.state = CHECK_ACTIVATED;
}
/*
* Clear check
* -----------
* Clear an active check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function clearCeck(uint256 id, address from, string calldata passPhrase)
lockUser(msg.sender) lockUser(from)
lockCheck(id) onlyValIdCheckAction(id, from, passPhrase)
external {
require(_checks[id].check.state == CHECK_ACTIVATED,
'Cannot clear a non active check.');
require(_checks[id].check.owner == from,
'Original owner is needed to clear check.');
require(_checks[id].check.key == keccak256(abi.encodePacked(passPhrase)),
'Cannot clear a not opened check.');
// Note: consider to do this after the for loop. It is a hard decision.
_checks[id].check.state = CHECK_SPENT;
// There's no lack of {}s in the for loop and if selector below. :-)
for (uint256 i=0; i < _checks[id].check.coins.length; i++)
if (_coins[_checks[id].check.coins[i]].owner != from
|| _coins[_checks[id].check.coins[i]].state != COIN_ACTIVE_IN_CHECK)
revert('Internal error: Check clearance refused, safety first.');
else _coins[_checks[id].check.coins[i]].owner = msg.sender;
}
/*
* Suspend check
* -------------
* Suspend an existing and non suspended check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function suspendCheck(uint256 id, string calldata passPhrase) lockCheck(id)
onlyValIdCheckAction(id, msg.sender, passPhrase)
external {
require((_checks[id].check.state == CHECK_CREATED
|| _checks[id].check.state == CHECK_ACTIVATED),
'Cannot perform suspending on check with non appropriate state.');
_checks[id].check.state = CHECK_SUSPENDED;
}
////////////
// DELETE //
////////////
/*
* Delete a check
* --------------
* Delete a not yet cleared check
*
* @param uint256 id
* ID of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
function deleteCheck(uint256 id, string calldata passPhrase) lockCheck(id)
onlyValIdCheckAction(id, msg.sender, passPhrase)
external {
require((_checks[id].check.state == CHECK_CREATED
|| _checks[id].check.state == CHECK_ACTIVATED
|| _checks[id].check.state == CHECK_SUSPENDED),
'Cannot perform deletioon on check with non appropriate state.');
// There's no lack of {} in the for loop below. :-)
for (uint i=0; i < _checks[id].check.coins.length; i++)
_coins[_checks[id].check.coins[i]].state = COIN_ACTIVE_AND_FREE;
_checks[id].check.state = CHECK_DELETED;
}
/*
* #########
* # Notes #
* #########
*/
// TODO: IMPLEMENT
/*
* ##############
* # Note types #
* ##############
*/
// TODO: IMPLEMENT
/*
* ###############################
* # User balance and user coins #
* ###############################
*/
/*
* Get the balance of a user
* -------------------------
* Get the total balance of a user
*
* @param address owner
* The address of the user to get balance for.
*
* @return uint256
* The balance of the user.
*/
function getBalance(address owner) external view returns (uint256) {
uint256 result = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner) result += 1;
return result;
}
/*
* Get the coins of a user
* -----------------------
* Get the list of all coins of a user
*
* @param address owner
* The address of the user to get coins for.
*
* @return uint256[]
* List if IDs of the coins of the user.
*/
function getCoins(address owner) external view returns (uint256[] memory) {
// Becuse .push() is not available on memory arrays, a non-gas-friendly
// workaround should be used.
uint256 counter = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner) counter++;
uint256[] memory result = new uint256[](counter);
counter = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner) {
result[counter] = i;
counter++;
}
return result;
}
/*
* ################
* # TRANSACTIONS #
* ################
*/
/*
* Transact between users
* ----------------------
* Perform transaction between users
*
* @param address target
* Target address to send coins to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextUser contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the user's contract depending on the implementation.
*/
function transact(address target, uint256 amount) lockUser(msg.sender)
lockUser(target) external returns (bool) {
return _transact(msg.sender, target, amount);
}
/*
* Transact between banks
* ----------------------
* Perform transaction between banks
*
* @param uint16 id
* ID of a bank to transact from.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param uint16 target
* ID of a bank to transact to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextBank contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the bank's contract depending on the implementation.
*/
function transactBankToBank(uint16 id, uint256 keyId,
string calldata passPhrase, uint16 target,
uint256 amount) onlyExistingBank(id)
lockBank(id)
onlyValIdBankAction(id, keyId, passPhrase)
onlyExistingBank(target) lockBank(target)
external returns (bool) {
return _transact(_banks[id].bank.mainAccount,
_banks[target].bank.mainAccount, amount);
}
/*
* Transact from bank to user
* --------------------------
* Perform transaction from a bank to a user
*
* @param uint16 id
* ID of a bank to transact from.
* @param uint256 keyId
* The ID of the key to valIdate transaction with.
* @param string calldata passPhrase
* A password phrase that matches the key to grant access.
* @param address target
* Target address to send coins to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextBank contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the bank's contract depending on the implementation.
*/
function transactBankToUser(uint16 id, uint256 keyId,
string calldata passPhrase, address target,
uint256 amount) onlyExistingBank(id)
lockBank(id)
onlyValIdBankAction(id, keyId, passPhrase)
onlyExistingUser(target) lockUser(target)
external returns (bool) {
return _transact(_banks[id].bank.mainAccount, target, amount);
}
/*
* Transact from user to bank
* --------------------------
* Perform transaction from a user to a bank
*
* @param uint16 target
* ID of a bank to transact to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*
* @note In most cases like ERC20 token standard event is imetted on
* successful transactions. In this ecosystem the function transact()
* is called by MNextUser contract, therefore it is more convenient
* to return bool instead of emitting an event. Emitting event can
* happen in the user's contract depending on the implementation.
*/
function transactUserToBank(uint16 target, uint256 amount)
lockUser(msg.sender) lockBank(target)
external returns (bool) {
return _transact(msg.sender, _banks[target].bank.mainAccount, amount);
}
// TODO: IMPLEMENT if bank want to use other than mainAccount both for
// bank->bank, bank->user and user->bank transactions.
/*
* ######################
* # INTERNAL FUNCTIONS #
* ######################
*/
/*
* Create check with state
* -----------------------
* Create a check with the given state
*
* @param uint256 amount
* The amount of the check.
* @param string memory passPhrase
* A pharese to secure the check.
* @param uint8 state
* The state to create check with.
*/
function _createCheck(uint256 amount, string calldata passPhrase,
uint8 state) lockCheck(_nextCheckId)
private returns (uint256) {
// Becuse .push() is not available on memory arrays, a non-gas-friendly
// workaround should be used.
uint256 counter = 0;
// There's no lack of {} in the for loop below. :-)
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == msg.sender
&& _coins[i].state == COIN_ACTIVE_AND_FREE)
counter++;
require(counter >= amount,
'Not enough balance to create chekk.');
uint256[] memory coins = new uint256[](counter);
counter = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == msg.sender
&& _coins[i].state == COIN_ACTIVE_AND_FREE) {
_coins[i].state = COIN_ACTIVE_IN_CHECK;
coins[counter] = i;
counter++;
if (counter > amount) break;
}
uint256 _thisId = _nextCheckId;
if (_checks[_thisId].isLocked)
revert('Internal error: Check creation refused, safety first.');
_checks[_thisId].check = Check(msg.sender, coins,
keccak256(abi.encodePacked(passPhrase)),
state);
_nextCheckId++;
return _thisId;
}
/*
* Transact
* --------
* Perform transaction between addresses
*
* @param address owner
* Target address to send coins from.
* @param address target
* Target address to send coins to.
* @param uint256 amount
* Amount of coins to send.
*
* @return bool
* True if the transaction was successful, false if not.
*/
function _transact(address owner, address target, uint256 amount)
internal returns (bool) {
bool result = false;
uint256[] memory coinSupply = new uint256[] (amount);
uint256 counter = 0;
for (uint256 i=0; i < _nextCoinId; i++)
if (_coins[i].owner == owner
&& _coins[i].state == COIN_ACTIVE_AND_FREE) {
coinSupply[counter] = i;
counter++;
if (counter == amount) {
result = true;
break;
}
}
if (result) {
for (uint256 i=0; i < coinSupply.length; i++)
_coins[i].owner = target;
}
return result;
}
/*
* #####################
* # PRIVATE FUNCTIONS #
* #####################
*/
/*
* Review utxo deposits of a bank
* ------------------------------
* Collects information about presenting utxo deposits of the given bank
*
* @param uint16 id
* The ID of the bank to review.
*/
function __reviewBank(uint16 id) onlyExistingBank(id) lockBank(id) private {
for (uint256 i=0; i<_banks[id].bank.accountsBTC.length; i++) {
/*
* ACCES BTC GATEWAY.
*/
uint256 responseLength = 0;
address[] memory utxoList = new address[] (responseLength);
uint256[] memory amountList = new uint256[] (responseLength);
require(utxoList.length == amountList.length, 'BTC gateway error.');
for (uint256 j=0; j < utxoList.length; j++) {
_utxos[_utxoPointer] = BTCutxo(utxoList[j], amountList[j], id, i);
_utxoPointer++;
}
}
}
/*
* Review all the system coins
* ---------------------------
* Review system coins whether hey have the needed BTC deposits or not
*/
function __reviewCoins() private {
// HOW IT WORKS?
// 1. Gets all available utxos
// 2. Loops over coins and marks missing utxos
// 3. If there are coins without deposits, attempts to swap or delete them
// 4. If there are utxos without coins, they might used to coin swap
// 5. If there are utxos withoot coins after swaps, attempts to create coins
// 6. If something important happen in this functions events are mitted
}
/*
* #############
* # MODIFIERS #
* #############
*/
/*
* Lock a bank
* -----------
* Attempt to lock a bank during its data gets changed
*
* @param uint16 id
* The ID of the bank to lock.
*/
modifier lockBank(uint16 id) {
require(!_banks[id].isLocked,
'Cannot perform action on a locked bank.');
_banks[id].isLocked = true;
_;
_banks[id].isLocked = false;
}
/*
* Lock a check
* ------------
* Attempt to lock a check during its data gets changed
*
* @param uint256 id
* The ID of the check to lock.
*/
modifier lockCheck(uint256 id) {
require(!_checks[id].isLocked,
'Cannot perform action on a locked check.');
_checks[id].isLocked = true;
_;
_checks[id].isLocked = false;
}
/*
* Lock a user
* -----------
* Attempt to lock a user during its data gets changed
*
* @param address wallet
* The wallet of the user to lock.
*/
modifier lockUser(address wallet) {
require(!_users[wallet].isLocked,
'Cannot perform action on a locked user.');
_users[wallet].isLocked = true;
_;
_users[wallet].isLocked = false;
}
/*
* ValIdate admin
* --------------
* ValIdate access of the master contract owner
*
* @param string memory sentence
* A sentence to protect master access.
*/
modifier onlyAdmin(string memory sentence) {
require(msg.sender == _rootUser,
'Only admin can perform the action.');
require(keccak256(abi.encodePacked(sentence)) == _rootKey,
'Authorization failed.');
_;
}
/*
* Check existence of a bank
* -------------------------
* Check whether a bank exists or not
*
* @param uint16 id
* The ID of the bank to check.
*/
modifier onlyExistingBank(uint16 id) {
require(_banks[id].bank.state != STATE_UNAVAILABLE,
'Bank id must exist.');
_;
}
/*
* Check existence of a check
* --------------------------
* Check whether a check exists or not
*
* @param uint256 id
* The ID of the check to check.
*/
modifier onlyExistingCheck(uint256 id) {
require(_checks[id].check.state != STATE_UNAVAILABLE,
'Check id must exist.');
_;
}
/*
* Check existence of a coin
* -------------------------
* Check whether a coin exists or not
*
* @param uint256 id
* The ID of the coin to check.
*/
modifier onlyExistingCoin(uint256 id) {
require(_coins[id].state != STATE_UNAVAILABLE,
'Coin id must exist.');
_;
}
/*
* Check existence of a note
* -------------------------
* Check whether a note exists or not
*
* @param uint256 id
* The ID of the note to check.
*/
modifier onlyExistingNote(uint256 id) {
require(_notes[id].state != STATE_UNAVAILABLE,
'Note id must exist.');
_;
}
/*
* Check existence of a user
* -------------------------
* Check whether a user exists locally or not
*
* @param address who
* The address of the user to check.
*/
modifier onlyExistingUser(address who) {
require(_users[who].state != STATE_UNAVAILABLE
&& _users[who].state != USER_DELETED,
'User must exist.');
_;
}
modifier onlyValIdBankAction(uint16 id, uint256 keyId,
string calldata passPhrase) {
require(_banks[id].bank.keys.length < keyId,
'Cannot valIdate a non existing key.');
require(_banks[id].bank.keys[keyId]
== keccak256(abi.encodePacked(passPhrase)),
'Authorization failed.');
_;
}
/*
* ValIdate check access
* ---------------------
* ValIdate access credentials to perform actions on a check
*
* @param uint256 id
* ID of the check.
* @param address owner
* The address of owner of the check.
* @param string memory passPhrase
* A pharese to secure the check.
*/
modifier onlyValIdCheckAction(uint256 id, address owner,
string calldata passPhrase) {
require(_checks[id].check.owner == owner,
'Cannot perform action on a foreign check.');
require(_checks[id].check.key
== keccak256(abi.encodePacked(passPhrase)),
'Cannot perform action on a not opened check.');
_;
}
}
|
Suspend bank ------------ Suspend am active bank uint16 id The ID of the bank to suspend. string calldata sentence A sentence to protect master access./
|
function suspendBank(uint16 id, string calldata sentence)
onlyAdmin(sentence) onlyExistingBank(id) lockBank(id)
external {
require(_banks[id].bank.state == BANK_SUSPENDED
|| _banks[id].bank.state == BANK_DELETED,
'Cannot suspend a bank with a non appropriate state.');
_banks[id].bank.state = BANK_SUSPENDED;
}
| 2,507,091
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
import "ds-test/test.sol";
import "../test/utils/Caller.sol";
import {Hevm} from "../test/utils/Hevm.sol";
import {Oracle} from "./Oracle.sol";
contract OracleImplementation is Oracle {
constructor(uint256 timeUpdateWindow_) Oracle(timeUpdateWindow_) {
this;
}
// Allow the test to change the return value
// This will not be used in the actual implementation
int256 internal _returnValue;
function setValue(int256 value_) public {
_returnValue = value_;
}
// We want to handle cases where the oracle fails to obtain values
// Ideally the `getValue()` will never fail, but the current implementation will also handle fails
bool internal _success = true;
function setSuccess(bool success_) public {
_success = success_;
}
// We mock this value provider to return the expected previously set value
function getValue() external view override(Oracle) returns (int256) {
if (_success) {
return _returnValue;
} else {
revert("Oracle failed");
}
}
}
contract OracleReenter is Oracle {
constructor(uint256 timeUpdateWindow_) Oracle(timeUpdateWindow_) {
this;
}
bool public reentered = false;
function getValue() external override(Oracle) returns (int256) {
if (reentered) {
return 42;
} else {
reentered = true;
super.update();
}
return 0;
}
}
contract OracleTest is DSTest {
Hevm internal hevm = Hevm(DSTest.HEVM_ADDRESS);
OracleImplementation internal oracle;
uint256 internal timeUpdateWindow = 100; // seconds
function setUp() public {
oracle = new OracleImplementation(timeUpdateWindow);
// Set the value returned to 100
oracle.setValue(int256(100 * 10**18));
hevm.warp(timeUpdateWindow * 10);
}
function test_deploy() public {
assertTrue(address(oracle) != address(0));
}
function test_check_timeUpdateWindow() public {
// Check that the property was properly set
assertTrue(
oracle.timeUpdateWindow() == timeUpdateWindow,
"Invalid oracle timeUpdateWindow"
);
}
function test_update_updates_timestamp() public {
oracle.update();
// Check if the timestamp was updated
assertEq(oracle.lastTimestamp(), block.timestamp);
}
function test_update_shouldNotUpdatePreviousValues_ifNotEnoughTimePassed()
public
{
// Get current timestamp
uint256 blockTimestamp = block.timestamp;
// Update the oracle
oracle.update();
// Check if the timestamp was updated
assertEq(oracle.lastTimestamp(), blockTimestamp);
// Advance time
hevm.warp(blockTimestamp + timeUpdateWindow - 1);
// Calling update should not update the values
// because not enough time has passed
oracle.update();
// Check if the values are still the same
assertEq(oracle.lastTimestamp(), blockTimestamp);
}
function test_update_shouldUpdatePreviousValues_ifEnoughTimePassed()
public
{
// Get current timestamp
uint256 blockTimestamp = block.timestamp;
// Advance time
hevm.warp(blockTimestamp + timeUpdateWindow);
// Calling update should update the values
// because enough time has passed
oracle.update();
// Last timestamp should be updated
assertEq(oracle.lastTimestamp(), blockTimestamp + timeUpdateWindow);
}
function test_update_updateDoesNotChangeTheValue_inTheSameWindow() public {
oracle.setValue(int256(100 * 10**18));
// Update the oracle
oracle.update();
(int256 value1, ) = oracle.value();
assertEq(value1, 100 * 10**18);
int256 nextValue1 = oracle.nextValue();
assertEq(nextValue1, 100 * 10**18);
oracle.setValue(int256(150 * 10**18));
// Advance time but stay in the same time update window
hevm.warp(block.timestamp + 1);
// Update the oracle
oracle.update();
// Values are not modified
(int256 value2, ) = oracle.value();
assertEq(value2, 100 * 10**18);
int256 nextValue2 = oracle.nextValue();
assertEq(nextValue2, 100 * 10**18);
}
function test_update_shouldNotFail_whenValueProviderFails() public {
oracle.setSuccess(false);
// Update the oracle
oracle.update();
}
function test_value_shouldBeInvalid_afterValueProviderFails() public {
// We first successfully update the value to make sure the lastTimestamp is updated
// After that, we wait for the required amount of time and try update the value again
// The second update will fail and the value should be invalid because of the flag only.
// (time check is still correct because maxValidTime >= timeUpdateWindow)
oracle.setValue(10**18);
// Update the oracle
oracle.update();
// Advance time
hevm.warp(block.timestamp + timeUpdateWindow);
oracle.setSuccess(false);
// Update the oracle
oracle.update();
(, bool isValid) = oracle.value();
assertTrue(isValid == false);
}
function test_value_shouldBecomeValid_afterSuccessfulUpdate() public {
oracle.setSuccess(false);
oracle.update();
(, bool isValid1) = oracle.value();
assertTrue(isValid1 == false);
oracle.setSuccess(true);
oracle.update();
(, bool isValid2) = oracle.value();
assertTrue(isValid2 == true);
}
function test_valueReturned_shouldNotBeValid_ifNeverUpdated() public {
// Initially the value should be considered stale
(, bool valid) = oracle.value();
assertTrue(valid == false);
}
function test_paused_stops_returnValue() public {
// Pause oracle
oracle.pause();
// Create user
Caller user = new Caller();
// Should fail trying to get value
bool success;
(success, ) = user.externalCall(
address(oracle),
abi.encodeWithSelector(oracle.value.selector)
);
assertTrue(success == false, "value() should fail when paused");
}
function test_paused_doesNotStop_update() public {
// Pause oracle
oracle.pause();
// Create user
Caller user = new Caller();
// Allow user to call update on the oracle
oracle.allowCaller(oracle.ANY_SIG(), address(user));
// Should not fail trying to get update
bool success;
(success, ) = user.externalCall(
address(oracle),
abi.encodeWithSelector(oracle.update.selector)
);
assertTrue(success, "update() should not fail when paused");
}
function test_reset_resetsContract() public {
// Make sure there are some values in there
oracle.update();
// Last updated timestamp is this block
assertEq(oracle.lastTimestamp(), block.timestamp);
// Value should be 100 and valid
int256 value;
bool valid;
(value, valid) = oracle.value();
assertEq(value, 100 * 10**18);
assertTrue(valid == true);
// Oracle should be paused when resetting
oracle.pause();
// Reset contract
oracle.reset();
// Unpause contract
oracle.unpause();
// Last updated timestamp should be 0
assertEq(oracle.lastTimestamp(), 0);
// Value should be 0 and not valid
(value, valid) = oracle.value();
assertEq(value, 0);
assertTrue(valid == false);
// Next value should be 0
assertEq(oracle.nextValue(), 0);
}
function test_reset_shouldBePossible_ifPaused() public {
// Pause oracle
oracle.pause();
// Reset contract
oracle.reset();
}
function testFail_reset_shouldNotBePossible_ifNotPaused() public {
// Oracle is not paused
assertTrue(oracle.paused() == false);
// Reset contract should fail
oracle.reset();
}
function test_authorizedUser_shouldBeAble_toReset() public {
// Create user
Caller user = new Caller();
// Grant ability to reset
oracle.allowCaller(oracle.reset.selector, address(user));
// Oracle should be paused when calling reset
oracle.pause();
// Should not fail trying to reset
bool success;
(success, ) = user.externalCall(
address(oracle),
abi.encodeWithSelector(oracle.reset.selector)
);
assertTrue(
success,
"Only authorized user should be able to call reset()"
);
}
function test_nonAuthorizedUser_shouldNotBeAble_toReset() public {
// Create user
// Do not authorize user
Caller user = new Caller();
// Oracle should be paused when calling reset
oracle.pause();
// Should fail trying to reset
bool success;
(success, ) = user.externalCall(
address(oracle),
abi.encodeWithSelector(oracle.reset.selector)
);
assertTrue(
success == false,
"Non-authorized user should not be able to call reset()"
);
}
function testFail_update_cannotBeReentered() public {
OracleReenter oracleReenter = new OracleReenter(timeUpdateWindow);
oracleReenter.update();
assertTrue(oracleReenter.reentered());
}
function test_update_returnsTrue_whenSuccessful() public {
bool updated;
updated = oracle.update();
assertTrue(updated, "Should return `true` no successful update");
}
function test_update_returnsFalse_whenUpdateDoesNotChangeAnything() public {
bool updated;
updated = oracle.update();
// Second update should return false since it doesn't change anything
updated = oracle.update();
assertTrue(
updated == false,
"Should return `true` no successful update"
);
}
function test_update_nonAuthorizedUserCanNotCall_update() public {
Caller user = new Caller();
// A non permissioned user should not be able to call
bool ok;
(ok, ) = user.externalCall(
address(oracle),
abi.encodeWithSelector(oracle.update.selector)
);
assertTrue(
ok == false,
"Non permissioned user should not be able to call update"
);
}
function test_update_authorizedUserCanCall_update() public {
Caller user = new Caller();
// Give permission to the user
oracle.allowCaller(oracle.update.selector, address(user));
// A non permissioned user should not be able to call
bool ok;
(ok, ) = user.externalCall(
address(oracle),
abi.encodeWithSelector(oracle.update.selector)
);
assertTrue(ok, "Permissioned user should be able to call update");
}
}
|
We first successfully update the value to make sure the lastTimestamp is updated After that, we wait for the required amount of time and try update the value again The second update will fail and the value should be invalid because of the flag only. (time check is still correct because maxValidTime >= timeUpdateWindow) Update the oracle Advance time Update the oracle
|
function test_value_shouldBeInvalid_afterValueProviderFails() public {
oracle.setValue(10**18);
oracle.update();
hevm.warp(block.timestamp + timeUpdateWindow);
oracle.setSuccess(false);
oracle.update();
(, bool isValid) = oracle.value();
assertTrue(isValid == false);
}
| 12,644,913
|
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "openzeppelin-solidity/contracts/interfaces/IERC20.sol";
import "openzeppelin-solidity/contracts/utils/math/SafeMath.sol";
import "./utils/OwnerPausable.sol";
import "openzeppelin-solidity/contracts/interfaces/IERC721.sol";
import "openzeppelin-solidity/contracts/interfaces/IERC721Receiver.sol";
contract RFOXAUCTION is OwnerPausable, IERC721Receiver {
using SafeMath for uint256;
enum AuctionStatus { Normal, Ended, Canceled }
struct AuctionInfo {
address seller;
address nft;
uint itemId;
uint price;
address bidder;
uint createdAt;
uint updatedAt;
uint start;
uint end;
AuctionStatus status;
}
struct BidInfo {
uint auctionId;
uint itemId;
uint price;
address bidder;
uint bidAt;
}
AuctionInfo[] public auctions;
BidInfo[] public bids;
uint256 public bidPricePercent;
mapping(uint256 => uint256[]) public bidsOfAuction;
mapping(address => uint256[]) public bidsOfUser;
mapping(address => uint256) public bidCount;
mapping(address => uint256) public wonCount;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
uint private constant MIN_BID_PRICE_PERCENT = 101;
uint private constant MAX_BID_PRICE_PERCNET = 120;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
event CreateAuction(address indexed sender, uint itemId, uint start, uint end);
event Bid(address indexed sender, uint auctionId, uint price, uint bidAt);
event CancelAuction(address indexed sender, uint auctionId);
event EndAuction(address indexed sender, uint auctionId);
event SetBidPricePercent(address indexed sender, uint _bidPricePercent);
constructor (uint256 _bidPricePercent) {
require(_bidPricePercent >= MIN_BID_PRICE_PERCENT &&
_bidPricePercent <= MAX_BID_PRICE_PERCNET, "Auction: Invalid Bid Price Percent");
bidPricePercent = _bidPricePercent;
}
modifier validId(uint _auctionId) {
require(_auctionId < auctions.length, "Auction: Invalid Auction Id");
_;
}
modifier validSeller(uint _auctionId) {
AuctionInfo storage auction = auctions[_auctionId];
require(auction.seller == _msgSender(), "Auction: Invalid Permission");
_;
}
modifier validWinner(uint _auctionId) {
AuctionInfo storage auction = auctions[_auctionId];
require(auction.bidder == _msgSender(), "Auction: Invalid Permission");
_;
}
/**
* Create a new auction
*
* @param _nft address of nft
* @param _itemId token id of nft
* @param _price start price
* @param _start start date
* @param _end end date
*/
function createAuction(address _nft, uint _itemId, uint _price, uint _start, uint _end) external onlyOwner whenNotPaused {
require(_start < _end, "Auction: Period is not valid");
IERC721(_nft).safeTransferFrom(_msgSender(), address(this), _itemId);
AuctionInfo memory newAuction = AuctionInfo(
_msgSender(),
_nft,
_itemId,
_price,
address(0),
block.timestamp,
block.timestamp,
_start,
_end,
AuctionStatus.Normal
);
auctions.push(newAuction);
emit CreateAuction(_msgSender(), _itemId, _start, _end);
}
/**
* Bid to an auction
*
* @param _auctionId auction id to bid
*/
function bid(uint _auctionId) external validId(_auctionId) whenNotPaused payable {
AuctionInfo storage auction = auctions[_auctionId];
require(_msgSender() != auction.seller, "Auction: Invalid Bidder");
require(_msgSender() != auction.bidder, "Auction: Invalid Bidder");
require(block.timestamp >= auction.start, "Auction: Auction is not started");
require(block.timestamp <= auction.end, "Auction: Auction is Over");
require(msg.value > auction.price.mul(bidPricePercent).div(100), "Auction: Price is low");
require(auction.status == AuctionStatus.Normal, "Auction: Bid is not allowed");
// Require bidder is not highest bidder on another auction
// require(bidCount[_msgSender()] == 0, "Auction: Bidder can only win 1 shop at a time");
if (auction.bidder != address(0)) {
bidCount[auction.bidder] = bidCount[auction.bidder].sub(1);
(bool success, ) = auction.bidder.call{ value: auction.price}("");
require(success, 'Auction: unable to send value, recipient may have reverted');
}
bidCount[_msgSender()] = bidCount[_msgSender()].add(1);
auction.bidder = _msgSender();
auction.price = msg.value;
auction.updatedAt = block.timestamp;
BidInfo memory newBid = BidInfo(_auctionId, auction.itemId, msg.value, _msgSender(), block.timestamp);
bids.push(newBid);
bidsOfAuction[_auctionId].push(bids.length - 1);
bidsOfUser[_msgSender()].push(bids.length - 1);
emit Bid(_msgSender(), _auctionId, msg.value, block.timestamp);
}
/**
* Cancel an auction
*
* @param _auctionId auction id to cancel
*/
function cancelAuction(uint _auctionId) external validId(_auctionId) validSeller(_auctionId) whenNotPaused {
AuctionInfo storage auction = auctions[_auctionId];
require(auction.start > block.timestamp, "Auction: Not Cancelable");
require(bidsOfAuction[_auctionId].length == 0, "Auction: There are bids already");
auction.status = AuctionStatus.Canceled;
IERC721(auction.nft).safeTransferFrom(address(this), _msgSender(), auction.itemId);
emit CancelAuction(_msgSender(), _auctionId);
}
/**
* Set percent of price to bid higher than current price
*
* @param _bidPricePercent percent
*/
function setBidPricePercent(uint _bidPricePercent) external onlyOwner {
require(_bidPricePercent >= MIN_BID_PRICE_PERCENT && _bidPricePercent <= MAX_BID_PRICE_PERCNET, "Invalid Bid Price Percent");
bidPricePercent = _bidPricePercent;
emit SetBidPricePercent(_msgSender(), _bidPricePercent);
}
/**
* Return total number of auctions
*
* @return number of auctions
*/
function getAuctionCount() external view returns (uint256) {
return auctions.length;
}
/**
* Return total number of auctions
*
* @return number of auctions
*/
function getTotalBidCount() external view returns (uint256) {
return bids.length;
}
/**
* End an auction
*
* @param _auctionId auction id to end
*/
function endAuction(uint _auctionId) external validId(_auctionId) validSeller(_auctionId) {
_finalizeAuction(_auctionId);
}
/**
* Claim an auction
*
* @param _auctionId auction id to end
*/
function claimAuction(uint _auctionId) external validId(_auctionId) validWinner(_auctionId) {
_finalizeAuction(_auctionId);
}
function _finalizeAuction(uint _auctionId) private {
AuctionInfo storage auction = auctions[_auctionId];
require(auction.end < block.timestamp, "Auction: Not ended yet");
require(auction.status == AuctionStatus.Normal);
auction.status = AuctionStatus.Ended;
if(auction.bidder != address(0)) {
(bool success, ) = auction.seller.call{ value: auction.price}("");
require(success, 'Auction: unable to send value, recipient may have reverted');
IERC721(auction.nft).safeTransferFrom(address(this), auction.bidder, auction.itemId);
}
wonCount[auction.bidder] = wonCount[auction.bidder].add(1);
emit EndAuction(_msgSender(), _auctionId);
}
/**
* Get bids of an auction
*
* @param _auctionId auction id
*
* @return bids
*/
function getAuctionActivities(uint256 _auctionId) external view returns (uint256[] memory) {
return bidsOfAuction[_auctionId];
}
/**
* Get bids of user
*
* @param account address of user
*
* @return bids
*/
function getUserBidding(address account) external view returns (uint256[] memory) {
return bidsOfUser[account];
}
function onERC721Received(address, address, uint256, bytes calldata) external override pure returns (bytes4) {
return _ERC721_RECEIVED;
}
}
|
Cancel an auction _auctionId auction id to cancel/
|
function cancelAuction(uint _auctionId) external validId(_auctionId) validSeller(_auctionId) whenNotPaused {
AuctionInfo storage auction = auctions[_auctionId];
require(auction.start > block.timestamp, "Auction: Not Cancelable");
require(bidsOfAuction[_auctionId].length == 0, "Auction: There are bids already");
auction.status = AuctionStatus.Canceled;
IERC721(auction.nft).safeTransferFrom(address(this), _msgSender(), auction.itemId);
emit CancelAuction(_msgSender(), _auctionId);
}
| 12,707,046
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
// OpenZeppelin v4
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { StorageSlot } from "@openzeppelin/contracts/utils/StorageSlot.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { SNARK_SCALAR_FIELD, TokenType, WithdrawType, TokenData, CommitmentCiphertext, CommitmentPreimage, Transaction } from "./Globals.sol";
import { Verifier } from "./Verifier.sol";
import { Commitments } from "./Commitments.sol";
import { TokenBlacklist } from "./TokenBlacklist.sol";
import { PoseidonT4 } from "./Poseidon.sol";
/**
* @title Railgun Logic
* @author Railgun Contributors
* @notice Functions to interact with the railgun contract
* @dev Wallets for Railgun will only need to interact with functions specified in this contract.
* This contract is written to be run behind a ERC1967-like proxy. Upon deployment of proxy the _data parameter should
* call the initializeRailgunLogic function.
*/
contract RailgunLogic is Initializable, OwnableUpgradeable, Commitments, TokenBlacklist, Verifier {
using SafeERC20 for IERC20;
// NOTE: The order of instantiation MUST stay the same across upgrades
// add new variables to the bottom of the list
// See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading
// Treasury variables
address payable public treasury; // Treasury contract
uint120 private constant BASIS_POINTS = 10000; // Number of basis points that equal 100%
// % fee in 100ths of a %. 100 = 1%.
uint120 public depositFee;
uint120 public withdrawFee;
// Flat fee in wei that applies to NFT transactions
uint256 public nftFee;
// Safety vectors
mapping(uint256 => bool) public snarkSafetyVector;
// Treasury events
event TreasuryChange(address treasury);
event FeeChange(uint256 depositFee, uint256 withdrawFee, uint256 nftFee);
// Transaction events
event CommitmentBatch(
uint256 treeNumber,
uint256 startPosition,
uint256[] hash,
CommitmentCiphertext[] ciphertext
);
event GeneratedCommitmentBatch(
uint256 treeNumber,
uint256 startPosition,
CommitmentPreimage[] commitments,
uint256[2][] encryptedRandom
);
event Nullifiers(uint256 treeNumber, uint256[] nullifier);
/**
* @notice Initialize Railgun contract
* @dev OpenZeppelin initializer ensures this can only be called once
* This function also calls initializers on inherited contracts
* @param _treasury - address to send usage fees to
* @param _depositFee - Deposit fee
* @param _withdrawFee - Withdraw fee
* @param _nftFee - Flat fee in wei that applies to NFT transactions
* @param _owner - governance contract
*/
function initializeRailgunLogic(
address payable _treasury,
uint120 _depositFee,
uint120 _withdrawFee,
uint256 _nftFee,
address _owner
) external initializer {
// Call initializers
OwnableUpgradeable.__Ownable_init();
Commitments.initializeCommitments();
// Set treasury and fee
changeTreasury(_treasury);
changeFee(_depositFee, _withdrawFee, _nftFee);
// Change Owner
OwnableUpgradeable.transferOwnership(_owner);
// Set safety vectors
snarkSafetyVector[11991246288605609459798790887503763024866871101] = true;
snarkSafetyVector[135932600361240492381964832893378343190771392134] = true;
snarkSafetyVector[1165567609304106638376634163822860648671860889162] = true;
}
/**
* @notice Change treasury address, only callable by owner (governance contract)
* @dev This will change the address of the contract we're sending the fees to in the future
* it won't transfer tokens already in the treasury
* @param _treasury - Address of new treasury contract
*/
function changeTreasury(address payable _treasury) public onlyOwner {
// Do nothing if the new treasury address is same as the old
if (treasury != _treasury) {
// Change treasury
treasury = _treasury;
// Emit treasury change event
emit TreasuryChange(_treasury);
}
}
/**
* @notice Change fee rate for future transactions
* @param _depositFee - Deposit fee
* @param _withdrawFee - Withdraw fee
* @param _nftFee - Flat fee in wei that applies to NFT transactions
*/
function changeFee(
uint120 _depositFee,
uint120 _withdrawFee,
uint256 _nftFee
) public onlyOwner {
if (
_depositFee != depositFee
|| _withdrawFee != withdrawFee
|| nftFee != _nftFee
) {
require(_depositFee <= BASIS_POINTS, "RailgunLogic: Deposit Fee exceeds 100%");
require(_withdrawFee <= BASIS_POINTS, "RailgunLogic: Withdraw Fee exceeds 100%");
// Change fee
depositFee = _depositFee;
withdrawFee = _withdrawFee;
nftFee = _nftFee;
// Emit fee change event
emit FeeChange(_depositFee, _withdrawFee, _nftFee);
}
}
/**
* @notice Get base and fee amount
* @param _amount - Amount to calculate for
* @param _isInclusive - Whether the amount passed in is inclusive of the fee
* @param _feeBP - Fee basis points
* @return base, fee
*/
function getFee(uint136 _amount, bool _isInclusive, uint120 _feeBP) public pure returns (uint120, uint120) {
// Expand width of amount to uint136 to accomodate full size of (2**120-1)*BASIS_POINTS
uint136 amountExpanded = _amount;
// Base is the amount deposited into the railgun contract or withdrawn to the target eth address
// for deposits and withdraws respectively
uint136 base;
// Fee is the amount sent to the treasury
uint136 fee;
if (_isInclusive) {
base = amountExpanded - (amountExpanded * _feeBP) / BASIS_POINTS;
fee = amountExpanded - base;
} else {
base = amountExpanded;
fee = (BASIS_POINTS * base) / (BASIS_POINTS - _feeBP) - base;
}
return (uint120(base), uint120(fee));
}
/**
* @notice Gets token field value from tokenData
* @param _tokenData - tokenData to calculate token field from
* @return token field
*/
function getTokenField(TokenData memory _tokenData) public pure returns (uint256) {
if (_tokenData.tokenType == TokenType.ERC20) {
return uint256(uint160(_tokenData.tokenAddress));
} else if (_tokenData.tokenType == TokenType.ERC721) {
revert("RailgunLogic: ERC721 not yet supported");
} else if (_tokenData.tokenType == TokenType.ERC1155) {
revert("RailgunLogic: ERC1155 not yet supported");
} else {
revert("RailgunLogic: Unknown token type");
}
}
/**
* @notice Hashes a commitment
* @param _commitmentPreimage - commitment to hash
* @return commitment hash
*/
function hashCommitment(CommitmentPreimage memory _commitmentPreimage) public pure returns (uint256) {
return PoseidonT4.poseidon([
_commitmentPreimage.npk,
getTokenField(_commitmentPreimage.token),
_commitmentPreimage.value
]);
}
/**
* @notice Deposits requested amount and token, creates a commitment hash from supplied values and adds to tree
* @param _notes - list of commitments to deposit
*/
function generateDeposit(CommitmentPreimage[] calldata _notes, uint256[2][] calldata _encryptedRandom) external {
// Get notes length
uint256 notesLength = _notes.length;
// Insertion and event arrays
uint256[] memory insertionLeaves = new uint256[](notesLength);
CommitmentPreimage[] memory generatedCommitments = new CommitmentPreimage[](notesLength);
require(_notes.length == _encryptedRandom.length, "RailgunLogic: notes and encrypted random length doesn't match");
for (uint256 notesIter = 0; notesIter < notesLength; notesIter++) {
// Retrieve note
CommitmentPreimage calldata note = _notes[notesIter];
// Check deposit amount is not 0
require(note.value > 0, "RailgunLogic: Cannot deposit 0 tokens");
// Check if token is on the blacklist
require(
!TokenBlacklist.tokenBlacklist[note.token.tokenAddress],
"RailgunLogic: Token is blacklisted"
);
// Check ypubkey is in snark scalar field
require(note.npk < SNARK_SCALAR_FIELD, "RailgunLogic: npk out of range");
// Process deposit request
if (note.token.tokenType == TokenType.ERC20) {
// ERC20
// Get ERC20 interface
IERC20 token = IERC20(address(uint160(note.token.tokenAddress)));
// Get base and fee amounts
(uint120 base, uint120 fee) = getFee(note.value, true, depositFee);
// Add GeneratedCommitment to event array
generatedCommitments[notesIter] = CommitmentPreimage({
npk: note.npk,
value: base,
token: note.token
});
// Calculate commitment hash
uint256 hash = hashCommitment(generatedCommitments[notesIter]);
// Add to insertion array
insertionLeaves[notesIter] = hash;
// Transfer base to output address
token.safeTransferFrom(
address(msg.sender),
address(this),
base
);
// Transfer fee to treasury
token.safeTransferFrom(
address(msg.sender),
treasury,
fee
);
} else if (note.token.tokenType == TokenType.ERC721) {
// ERC721 token
revert("RailgunLogic: ERC721 not yet supported");
} else if (note.token.tokenType == TokenType.ERC1155) {
// ERC1155 token
revert("RailgunLogic: ERC1155 not yet supported");
} else {
// Invalid token type, revert
revert("RailgunLogic: Unknown token type");
}
}
// Emit GeneratedCommitmentAdded events (for wallets) for the commitments
emit GeneratedCommitmentBatch(Commitments.treeNumber, Commitments.nextLeafIndex, generatedCommitments, _encryptedRandom);
// Push new commitments to merkle tree
Commitments.insertLeaves(insertionLeaves);
}
/**
* @notice Safety check for badly behaving code
*/
function checkSafetyVectors() external {
// Set safety bit
StorageSlot.getBooleanSlot(0x8dea8703c3cf94703383ce38a9c894669dccd4ca8e65ddb43267aa0248711450).value = true;
// Setup behaviour check
bool result = false;
// Execute behaviour check
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(0, caller())
mstore(32, snarkSafetyVector.slot)
let hash := keccak256(0, 64)
result := sload(hash)
}
require(result, "RailgunLogic: Unsafe vectors");
}
/**
* @notice Adds safety vector
*/
function addVector(uint256 vector) external onlyOwner {
snarkSafetyVector[vector] = true;
}
/**
* @notice Removes safety vector
*/
function removeVector(uint256 vector) external onlyOwner {
snarkSafetyVector[vector] = false;
}
/**
* @notice Execute batch of Railgun snark transactions
* @param _transactions - Transactions to execute
*/
function transact(
Transaction[] calldata _transactions
) external {
// Accumulate total number of insertion commitments
uint256 insertionCommitmentCount = 0;
// Loop through each transaction
uint256 transactionLength = _transactions.length;
for(uint256 transactionIter = 0; transactionIter < transactionLength; transactionIter++) {
// Retrieve transaction
Transaction calldata transaction = _transactions[transactionIter];
// If adaptContract is not zero check that it matches the caller
require(
transaction.boundParams.adaptContract == address (0) || transaction.boundParams.adaptContract == msg.sender,
"AdaptID doesn't match caller contract"
);
// Retrieve treeNumber
uint256 treeNumber = transaction.boundParams.treeNumber;
// Check merkle root is valid
require(Commitments.rootHistory[treeNumber][transaction.merkleRoot], "RailgunLogic: Invalid Merkle Root");
// Loop through each nullifier
uint256 nullifiersLength = transaction.nullifiers.length;
for (uint256 nullifierIter = 0; nullifierIter < nullifiersLength; nullifierIter++) {
// Retrieve nullifier
uint256 nullifier = transaction.nullifiers[nullifierIter];
// Check if nullifier has been seen before
require(!Commitments.nullifiers[treeNumber][nullifier], "RailgunLogic: Nullifier already seen");
// Push to nullifiers
Commitments.nullifiers[treeNumber][nullifier] = true;
}
// Emit nullifiers event
emit Nullifiers(treeNumber, transaction.nullifiers);
// Verify proof
require(
Verifier.verify(transaction),
"RailgunLogic: Invalid SNARK proof"
);
if (transaction.boundParams.withdraw != WithdrawType.NONE) {
// Last output is marked as withdraw, process
// Hash the withdraw commitment preimage
uint256 commitmentHash = hashCommitment(transaction.withdrawPreimage);
// Make sure the commitment hash matches the withdraw transaction output
require(
commitmentHash == transaction.commitments[transaction.commitments.length - 1],
"RailgunLogic: Withdraw commitment preimage is invalid"
);
// Fetch output address
address output = address(uint160(transaction.withdrawPreimage.npk));
// Check if we've been asked to override the withdraw destination
if(transaction.overrideOutput != address(0)) {
// Withdraw must == 2 and msg.sender must be the original recepient to change the output destination
require(
msg.sender == output && transaction.boundParams.withdraw == WithdrawType.REDIRECT,
"RailgunLogic: Can't override destination address"
);
// Override output address
output = transaction.overrideOutput;
}
// Process withdrawal request
if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC20) {
// ERC20
// Get ERC20 interface
IERC20 token = IERC20(address(uint160(transaction.withdrawPreimage.token.tokenAddress)));
// Get base and fee amounts
(uint120 base, uint120 fee) = getFee(transaction.withdrawPreimage.value, true, withdrawFee);
// Transfer base to output address
token.safeTransfer(
output,
base
);
// Transfer fee to treasury
token.safeTransfer(
treasury,
fee
);
} else if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC721) {
// ERC721 token
revert("RailgunLogic: ERC721 not yet supported");
} else if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC1155) {
// ERC1155 token
revert("RailgunLogic: ERC1155 not yet supported");
} else {
// Invalid token type, revert
revert("RailgunLogic: Unknown token type");
}
// Ensure ciphertext length matches the commitments length (minus 1 for withdrawn output)
require(
transaction.boundParams.commitmentCiphertext.length == transaction.commitments.length - 1,
"RailgunLogic: Ciphertexts and commitments count mismatch"
);
// Increment insertion commitment count (minus 1 for withdrawn output)
insertionCommitmentCount += transaction.commitments.length - 1;
} else {
// Ensure ciphertext length matches the commitments length
require(
transaction.boundParams.commitmentCiphertext.length == transaction.commitments.length,
"RailgunLogic: Ciphertexts and commitments count mismatch"
);
// Increment insertion commitment count
insertionCommitmentCount += transaction.commitments.length;
}
}
// Create insertion array
uint256[] memory hashes = new uint256[](insertionCommitmentCount);
// Create ciphertext array
CommitmentCiphertext[] memory ciphertext = new CommitmentCiphertext[](insertionCommitmentCount);
// Track insert position
uint256 insertPosition = 0;
// Loop through each transaction and accumulate commitments
for(uint256 transactionIter = 0; transactionIter < _transactions.length; transactionIter++) {
// Retrieve transaction
Transaction calldata transaction = _transactions[transactionIter];
// Loop through commitments and push to array
uint256 commitmentLength = transaction.boundParams.commitmentCiphertext.length;
for(uint256 commitmentIter = 0; commitmentIter < commitmentLength; commitmentIter++) {
// Push commitment hash to array
hashes[insertPosition] = transaction.commitments[commitmentIter];
// Push ciphertext to array
ciphertext[insertPosition] = transaction.boundParams.commitmentCiphertext[commitmentIter];
// Increment insert position
insertPosition++;
}
}
// Emit commitment state update
emit CommitmentBatch(Commitments.treeNumber, Commitments.nextLeafIndex, hashes, ciphertext);
// Push new commitments to merkle tree after event due to insertLeaves causing side effects
Commitments.insertLeaves(hashes);
}
}
// SPDX-License-Identifier: MIT
// 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);
}
// SPDX-License-Identifier: MIT
// 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 StorageSlot {
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
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.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 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");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.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 proxied contracts do not make use of 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));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.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 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 {
__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);
}
/**
* This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
// Constants
uint256 constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant CIPHERTEXT_WORDS = 4;
enum TokenType { ERC20, ERC721, ERC1155 }
// Transaction token data
struct TokenData {
TokenType tokenType;
address tokenAddress;
uint256 tokenSubID;
}
// Commitment ciphertext
struct CommitmentCiphertext {
uint256[CIPHERTEXT_WORDS] ciphertext; // Ciphertext order: iv & tag (16 bytes each), recipient master public key (packedPoint) (uint256), packedField (uint256) {sign, random, amount}, token (uint256)
uint256[2] ephemeralKeys; // Sender first, receipient second (packed points 32 bytes each)
uint256[] memo;
}
enum WithdrawType { NONE, WITHDRAW, REDIRECT }
// Transaction bound parameters
struct BoundParams {
uint16 treeNumber;
WithdrawType withdraw;
address adaptContract;
bytes32 adaptParams;
// For withdraws do not include an element in ciphertext array
// Ciphertext array length = commitments - withdraws
CommitmentCiphertext[] commitmentCiphertext;
}
// Transaction struct
struct Transaction {
SnarkProof proof;
uint256 merkleRoot;
uint256[] nullifiers;
uint256[] commitments;
BoundParams boundParams;
CommitmentPreimage withdrawPreimage;
address overrideOutput; // Only allowed if original destination == msg.sender & boundParams.withdraw == 2
}
// Commitment hash preimage
struct CommitmentPreimage {
uint256 npk; // Poseidon(mpk, random), mpk = Poseidon(spending public key, nullifier)
TokenData token; // Token field
uint120 value; // Note value
}
struct G1Point {
uint256 x;
uint256 y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint256[2] x;
uint256[2] y;
}
// Verification key for SNARK
struct VerifyingKey {
string artifactsIPFSHash;
G1Point alpha1;
G2Point beta2;
G2Point gamma2;
G2Point delta2;
G1Point[] ic;
}
// Snark proof for transaction
struct SnarkProof {
G1Point a;
G2Point b;
G1Point c;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
// OpenZeppelin v4
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { SnarkProof, Transaction, BoundParams, VerifyingKey, SNARK_SCALAR_FIELD } from "./Globals.sol";
import { Snark } from "./Snark.sol";
/**
* @title Verifier
* @author Railgun Contributors
* @notice Verifies snark proof
* @dev Functions in this contract statelessly verify proofs, nullifiers and adaptID should be checked in RailgunLogic.
*/
contract Verifier is OwnableUpgradeable {
// NOTE: The order of instantiation MUST stay the same across upgrades
// add new variables to the bottom of the list and decrement __gap
// See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading
// Snark bypass address, can't be address(0) as many burn prevention mechanisms will disallow transfers to 0
// Use 0x000000000000000000000000000000000000dEaD as an alternative
address constant public SNARK_BYPASS = 0x000000000000000000000000000000000000dEaD;
// Verifying key set event
event VerifyingKeySet(uint256 nullifiers, uint256 commitments, VerifyingKey verifyingKey);
// Nullifiers => Commitments => Verification Key
mapping(uint256 => mapping(uint256 => VerifyingKey)) private verificationKeys;
/**
* @notice Sets verification key
* @param _nullifiers - number of nullifiers this verification key is for
* @param _commitments - number of commitmets out this verification key is for
* @param _verifyingKey - verifyingKey to set
*/
function setVerificationKey(
uint256 _nullifiers,
uint256 _commitments,
VerifyingKey calldata _verifyingKey
) public onlyOwner {
verificationKeys[_nullifiers][_commitments] = _verifyingKey;
emit VerifyingKeySet(_nullifiers, _commitments, _verifyingKey);
}
/**
* @notice Gets verification key
* @param _nullifiers - number of nullifiers this verification key is for
* @param _commitments - number of commitmets out this verification key is for
*/
function getVerificationKey(
uint256 _nullifiers,
uint256 _commitments
) public view returns (VerifyingKey memory) {
// Manually add getter so dynamic IC array is included in response
return verificationKeys[_nullifiers][_commitments];
}
/**
* @notice Calculates hash of transaction bound params for snark verification
* @param _boundParams - bound parameters
* @return bound parameters hash
*/
function hashBoundParams(BoundParams calldata _boundParams) public pure returns (uint256) {
return uint256(keccak256(abi.encode(
_boundParams
))) % SNARK_SCALAR_FIELD;
}
/**
* @notice Verifies inputs against a verification key
* @param _verifyingKey - verifying key to verify with
* @param _proof - proof to verify
* @param _inputs - input to verify
* @return proof validity
*/
function verifyProof(
VerifyingKey memory _verifyingKey,
SnarkProof calldata _proof,
uint256[] memory _inputs
) public view returns (bool) {
return Snark.verify(
_verifyingKey,
_proof,
_inputs
);
}
/**
* @notice Verifies a transaction
* @param _transaction to verify
* @return transaction validity
*/
function verify(Transaction calldata _transaction) public view returns (bool) {
uint256 nullifiersLength = _transaction.nullifiers.length;
uint256 commitmentsLength = _transaction.commitments.length;
// Retrieve verification key
VerifyingKey memory verifyingKey = verificationKeys
[nullifiersLength]
[commitmentsLength];
// Check if verifying key is set
require(verifyingKey.alpha1.x != 0, "Verifier: Key not set");
// Calculate inputs
uint256[] memory inputs = new uint256[](2 + nullifiersLength + commitmentsLength);
inputs[0] = _transaction.merkleRoot;
// Hash bound parameters
inputs[1] = hashBoundParams(_transaction.boundParams);
// Loop through nullifiers and add to inputs
for (uint i = 0; i < nullifiersLength; i++) {
inputs[2 + i] = _transaction.nullifiers[i];
}
// Loop through commitments and add to inputs
for (uint i = 0; i < commitmentsLength; i++) {
inputs[2 + nullifiersLength + i] = _transaction.commitments[i];
}
// Verify snark proof
bool validity = verifyProof(
verifyingKey,
_transaction.proof,
inputs
);
// Always return true in gas estimation transaction
// This is so relayer fees can be calculated without needing to compute a proof
// solhint-disable-next-line avoid-tx-origin
if (tx.origin == SNARK_BYPASS) {
return true;
} else {
return validity;
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
// Based on code from MACI (https://github.com/appliedzkp/maci/blob/7f36a915244a6e8f98bacfe255f8bd44193e7919/contracts/sol/IncrementalMerkleTree.sol)
pragma solidity ^0.8.0;
pragma abicoder v2;
// OpenZeppelin v4
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { SNARK_SCALAR_FIELD } from "./Globals.sol";
import { PoseidonT3 } from "./Poseidon.sol";
/**
* @title Commitments
* @author Railgun Contributors
* @notice Batch Incremental Merkle Tree for commitments
* @dev Publically accessible functions to be put in RailgunLogic
* Relevent external contract calls should be in those functions, not here
*/
contract Commitments is Initializable {
// NOTE: The order of instantiation MUST stay the same across upgrades
// add new variables to the bottom of the list and decrement the __gap
// variable at the end of this file
// See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading
// Commitment nullifiers (treenumber -> nullifier -> seen)
mapping(uint256 => mapping(uint256 => bool)) public nullifiers;
// The tree depth
uint256 internal constant TREE_DEPTH = 16;
// Tree zero value
uint256 public constant ZERO_VALUE = uint256(keccak256("Railgun")) % SNARK_SCALAR_FIELD;
// Next leaf index (number of inserted leaves in the current tree)
uint256 internal nextLeafIndex;
// The Merkle root
uint256 public merkleRoot;
// Store new tree root to quickly migrate to a new tree
uint256 private newTreeRoot;
// Tree number
uint256 public treeNumber;
// The Merkle path to the leftmost leaf upon initialisation. It *should
// not* be modified after it has been set by the initialize function.
// Caching these values is essential to efficient appends.
uint256[TREE_DEPTH] public zeros;
// Right-most elements at each level
// Used for efficient upodates of the merkle tree
uint256[TREE_DEPTH] private filledSubTrees;
// Whether the contract has already seen a particular Merkle tree root
// treeNumber -> root -> seen
mapping(uint256 => mapping(uint256 => bool)) public rootHistory;
/**
* @notice Calculates initial values for Merkle Tree
* @dev OpenZeppelin initializer ensures this can only be called once
*/
function initializeCommitments() internal onlyInitializing {
/*
To initialise the Merkle tree, we need to calculate the Merkle root
assuming that each leaf is the zero value.
H(H(a,b), H(c,d))
/ \
H(a,b) H(c,d)
/ \ / \
a b c d
`zeros` and `filledSubTrees` will come in handy later when we do
inserts or updates. e.g when we insert a value in index 1, we will
need to look up values from those arrays to recalculate the Merkle
root.
*/
// Calculate zero values
zeros[0] = ZERO_VALUE;
// Store the current zero value for the level we just calculated it for
uint256 currentZero = ZERO_VALUE;
// Loop through each level
for (uint256 i = 0; i < TREE_DEPTH; i++) {
// Push it to zeros array
zeros[i] = currentZero;
// Calculate the zero value for this level
currentZero = hashLeftRight(currentZero, currentZero);
}
// Set merkle root and store root to quickly retrieve later
newTreeRoot = merkleRoot = currentZero;
rootHistory[treeNumber][currentZero] = true;
}
/**
* @notice Hash 2 uint256 values
* @param _left - Left side of hash
* @param _right - Right side of hash
* @return hash result
*/
function hashLeftRight(uint256 _left, uint256 _right) public pure returns (uint256) {
return PoseidonT3.poseidon([
_left,
_right
]);
}
/**
* @notice Calculates initial values for Merkle Tree
* @dev Insert leaves into the current merkle tree
* Note: this function INTENTIONALLY causes side effects to save on gas.
* _leafHashes and _count should never be reused.
* @param _leafHashes - array of leaf hashes to be added to the merkle tree
*/
function insertLeaves(uint256[] memory _leafHashes) internal {
/*
Loop through leafHashes at each level, if the leaf is on the left (index is even)
then hash with zeros value and update subtree on this level, if the leaf is on the
right (index is odd) then hash with subtree value. After calculating each hash
push to relevent spot on leafHashes array. For gas efficiency we reuse the same
array and use the count variable to loop to the right index each time.
Example of updating a tree of depth 4 with elements 13, 14, and 15
[1,7,15] {1} 1
|
[3,7,15] {1} 2-------------------3
| |
[6,7,15] {2} 4---------5 6---------7
/ \ / \ / \ / \
[13,14,15] {3} 08 09 10 11 12 13 14 15
[] = leafHashes array
{} = count variable
*/
// Get initial count
uint256 count = _leafHashes.length;
// Create new tree if current one can't contain new leaves
// We insert all new commitment into a new tree to ensure they can be spent in the same transaction
if ((nextLeafIndex + count) >= (2 ** TREE_DEPTH)) { newTree(); }
// Current index is the index at each level to insert the hash
uint256 levelInsertionIndex = nextLeafIndex;
// Update nextLeafIndex
nextLeafIndex += count;
// Variables for starting point at next tree level
uint256 nextLevelHashIndex;
uint256 nextLevelStartIndex;
// Loop through each level of the merkle tree and update
for (uint256 level = 0; level < TREE_DEPTH; level++) {
// Calculate the index to start at for the next level
// >> is equivilent to / 2 rounded down
nextLevelStartIndex = levelInsertionIndex >> 1;
uint256 insertionElement = 0;
// If we're on the right, hash and increment to get on the left
if (levelInsertionIndex % 2 == 1) {
// Calculate index to insert hash into leafHashes[]
// >> is equivilent to / 2 rounded down
nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex;
// Calculate the hash for the next level
_leafHashes[nextLevelHashIndex] = hashLeftRight(filledSubTrees[level], _leafHashes[insertionElement]);
// Increment
insertionElement += 1;
levelInsertionIndex += 1;
}
// We'll always be on the left side now
for (insertionElement; insertionElement < count; insertionElement += 2) {
uint256 right;
// Calculate right value
if (insertionElement < count - 1) {
right = _leafHashes[insertionElement + 1];
} else {
right = zeros[level];
}
// If we've created a new subtree at this level, update
if (insertionElement == count - 1 || insertionElement == count - 2) {
filledSubTrees[level] = _leafHashes[insertionElement];
}
// Calculate index to insert hash into leafHashes[]
// >> is equivilent to / 2 rounded down
nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex;
// Calculate the hash for the next level
_leafHashes[nextLevelHashIndex] = hashLeftRight(_leafHashes[insertionElement], right);
// Increment level insertion index
levelInsertionIndex += 2;
}
// Get starting levelInsertionIndex value for next level
levelInsertionIndex = nextLevelStartIndex;
// Get count of elements for next level
count = nextLevelHashIndex + 1;
}
// Update the Merkle tree root
merkleRoot = _leafHashes[0];
rootHistory[treeNumber][merkleRoot] = true;
}
/**
* @notice Creates new merkle tree
*/
function newTree() private {
// Restore merkleRoot to newTreeRoot
merkleRoot = newTreeRoot;
// Existing values in filledSubtrees will never be used so overwriting them is unnecessary
// Reset next leaf index to 0
nextLeafIndex = 0;
// Increment tree number
treeNumber++;
}
uint256[10] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
// OpenZeppelin v4
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @title Token Blacklist
* @author Railgun Contributors
* @notice Blacklist of tokens that are incompatible with the protocol
* @dev Tokens on this blacklist can't be deposited to railgun.
* Tokens on this blacklist will still be transferrable
* internally (as internal transactions have a shielded token ID) and
* withdrawable (to prevent user funds from being locked)
* THIS WILL ALWAYS BE A NON-EXHAUSTIVE LIST, DO NOT RELY ON IT BLOCKING ALL
* INCOMPATIBLE TOKENS
*/
contract TokenBlacklist is OwnableUpgradeable {
// Events for offchain building of blacklist index
event AddToBlacklist(address indexed token);
event RemoveFromBlacklist(address indexed token);
// NOTE: The order of instantiation MUST stay the same across upgrades
// add new variables to the bottom of the list and decrement the __gap
// variable at the end of this file
// See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading
mapping(address => bool) public tokenBlacklist;
/**
* @notice Adds tokens to blacklist, only callable by owner (governance contract)
* @dev This function will ignore tokens that are already in the blacklist
* no events will be emitted in this case
* @param _tokens - List of tokens to add to blacklist
*/
function addToBlacklist(address[] calldata _tokens) external onlyOwner {
// Loop through token array
for (uint256 i = 0; i < _tokens.length; i++) {
// Don't do anything if the token is already blacklisted
if (!tokenBlacklist[_tokens[i]]) {
// Set token address in blacklist map to true
tokenBlacklist[_tokens[i]] = true;
// Emit event for building index of blacklisted tokens offchain
emit AddToBlacklist(_tokens[i]);
}
}
}
/**
* @notice Removes token from blacklist, only callable by owner (governance contract)
* @dev This function will ignore tokens that aren't in the blacklist
* no events will be emitted in this case
* @param _tokens - List of tokens to remove from blacklist
*/
function removeFromBlacklist(address[] calldata _tokens) external onlyOwner {
// Loop through token array
for (uint256 i = 0; i < _tokens.length; i++) {
// Don't do anything if the token isn't blacklisted
if (tokenBlacklist[_tokens[i]]) {
// Set token address in blacklisted map to false (default value)
delete tokenBlacklist[_tokens[i]];
// Emit event for building index of blacklisted tokens offchain
emit RemoveFromBlacklist(_tokens[i]);
}
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
/*
Functions here are stubs for the solidity compiler to generate the right interface.
The deployed library is generated bytecode from the circomlib toolchain
*/
library PoseidonT3 {
// solhint-disable-next-line no-empty-blocks
function poseidon(uint256[2] memory input) public pure returns (uint256) {}
}
library PoseidonT4 {
// solhint-disable-next-line no-empty-blocks
function poseidon(uint256[3] memory input) public pure returns (uint256) {}
}
// SPDX-License-Identifier: MIT
// 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);
}
}
}
}
// SPDX-License-Identifier: MIT
// 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 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
* ====
*
* [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 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: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
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 onlyInitializing {
}
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;
}
/**
* This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
pragma abicoder v2;
import { G1Point, G2Point, VerifyingKey, SnarkProof, SNARK_SCALAR_FIELD } from "./Globals.sol";
library Snark {
uint256 private constant PRIME_Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 private constant PAIRING_INPUT_SIZE = 24;
uint256 private constant PAIRING_INPUT_WIDTH = 768; // PAIRING_INPUT_SIZE * 32
/**
* @notice Computes the negation of point p
* @dev The negation of p, i.e. p.plus(p.negate()) should be zero.
* @return result
*/
function negate(G1Point memory p) internal pure returns (G1Point memory) {
if (p.x == 0 && p.y == 0) return G1Point(0, 0);
// check for valid points y^2 = x^3 +3 % PRIME_Q
uint256 rh = mulmod(p.x, p.x, PRIME_Q); //x^2
rh = mulmod(rh, p.x, PRIME_Q); //x^3
rh = addmod(rh, 3, PRIME_Q); //x^3 + 3
uint256 lh = mulmod(p.y, p.y, PRIME_Q); //y^2
require(lh == rh, "Snark: Invalid negation");
return G1Point(p.x, PRIME_Q - (p.y % PRIME_Q));
}
/**
* @notice Adds 2 G1 points
* @return result
*/
function add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory) {
// Format inputs
uint256[4] memory input;
input[0] = p1.x;
input[1] = p1.y;
input[2] = p2.x;
input[3] = p2.y;
// Setup output variables
bool success;
G1Point memory result;
// Add points
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(sub(gas(), 2000), 6, input, 0x80, result, 0x40)
}
// Check if operation succeeded
require(success, "Snark: Add Failed");
return result;
}
/**
* @notice Scalar multiplies two G1 points p, s
* @dev The product of a point on G1 and a scalar, i.e.
* p == p.scalar_mul(1) and p.plus(p) == p.scalar_mul(2) for all
* points p.
* @return r - result
*/
function scalarMul(G1Point memory p, uint256 s) internal view returns (G1Point memory r) {
uint256[3] memory input;
input[0] = p.x;
input[1] = p.y;
input[2] = s;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(sub(gas(), 2000), 7, input, 0x60, r, 0x40)
}
// Check multiplication succeeded
require(success, "Snark: Scalar Multiplication Failed");
}
/**
* @notice Performs pairing check on points
* @dev The result of computing the pairing check
* e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1
* For example,
* pairing([P1(), P1().negate()], [P2(), P2()]) should return true.
* @return if pairing check passed
*/
function pairing(
G1Point memory _a1,
G2Point memory _a2,
G1Point memory _b1,
G2Point memory _b2,
G1Point memory _c1,
G2Point memory _c2,
G1Point memory _d1,
G2Point memory _d2
) internal view returns (bool) {
uint256[PAIRING_INPUT_SIZE] memory input = [
_a1.x,
_a1.y,
_a2.x[0],
_a2.x[1],
_a2.y[0],
_a2.y[1],
_b1.x,
_b1.y,
_b2.x[0],
_b2.x[1],
_b2.y[0],
_b2.y[1],
_c1.x,
_c1.y,
_c2.x[0],
_c2.x[1],
_c2.y[0],
_c2.y[1],
_d1.x,
_d1.y,
_d2.x[0],
_d2.x[1],
_d2.y[0],
_d2.y[1]
];
uint256[1] memory out;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(
sub(gas(), 2000),
8,
input,
PAIRING_INPUT_WIDTH,
out,
0x20
)
}
// Check if operation succeeded
require(success, "Snark: Pairing Verification Failed");
return out[0] != 0;
}
/**
* @notice Verifies snark proof against proving key
* @param _vk - Verification Key
* @param _proof - snark proof
* @param _inputs - inputs
*/
function verify(
VerifyingKey memory _vk,
SnarkProof memory _proof,
uint256[] memory _inputs
) internal view returns (bool) {
// Compute the linear combination vkX
G1Point memory vkX = G1Point(0, 0);
// Loop through every input
for (uint i = 0; i < _inputs.length; i++) {
// Make sure inputs are less than SNARK_SCALAR_FIELD
require(_inputs[i] < SNARK_SCALAR_FIELD, "Snark: Input > SNARK_SCALAR_FIELD");
// Add to vkX point
vkX = add(vkX, scalarMul(_vk.ic[i + 1], _inputs[i]));
}
// Compute final vkX point
vkX = add(vkX, _vk.ic[0]);
// Verify pairing and return
return pairing(
negate(_proof.a),
_proof.b,
_vk.alpha1,
_vk.beta2,
vkX,
_vk.gamma2,
_proof.c,
_vk.delta2
);
}
}
|
Change treasury address, only callable by owner (governance contract) This will change the address of the contract we're sending the fees to in the future it won't transfer tokens already in the treasury _treasury - Address of new treasury contract/ Do nothing if the new treasury address is same as the old Change treasury Emit treasury change event
|
function changeTreasury(address payable _treasury) public onlyOwner {
if (treasury != _treasury) {
treasury = _treasury;
emit TreasuryChange(_treasury);
}
}
| 5,809,447
|
pragma solidity ^0.4.24;
import "./BlockStore.sol";
import "../libraries/RLP.sol";
import "../libraries/SolidityUtils.sol";
contract FabricStore is BlockStore {
using RLP for RLP.RLPItem;
using RLP for RLP.Iterator;
using RLP for bytes;
struct Chain {
bytes32 id;
mapping (string => Channel) m_channels;
}
struct Channel {
string id;
mapping (string => bool) blocks;
mapping (string => Block) m_blocks;
mapping (string => Transaction) m_transactions;
mapping (string => bool) m_transactions_exist;
mapping (string => State) m_state;
}
struct Block {
uint number;
string hash;
string prevHash;
string dataHash;
uint timestamp_s;
uint timestamp_nanos;
string[] transactions;
}
struct Transaction {
string id;
string blockHash;
string[] namespaces;
mapping (string => Namespace) m_nsrw;
}
struct Namespace {
string namespace;
ReadSet[] reads;
WriteSet[] writes;
}
struct ReadSet {
string key;
RSVersion version;
}
struct RSVersion {
uint blockNo;
uint txNo;
}
struct WriteSet {
string key;
bool isDelete;
string value;
}
struct State {
string key;
RSVersion version;
string value;
}
mapping (bytes32 => Chain) public m_networks;
constructor(address _ionAddr) BlockStore(_ionAddr) public {}
event BlockAdded(bytes32 chainId, string channelId, string blockHash);
function addChain(bytes32 _chainId) onlyIon public returns (bool) {
require(super.addChain(_chainId), "Storage addChain parent call failed");
Chain storage chain = m_networks[_chainId];
chain.id = _chainId;
return true;
}
// Function name is inaccurate for Fabric due to blocks being a sub-structure to a channel
// Will need refactoring
function addBlock(bytes32 _chainId, bytes _blockBlob)
public
onlyIon
onlyRegisteredChains(_chainId)
{
RLP.RLPItem[] memory data = _blockBlob.toRLPItem().toList();
// Iterate all channel objects in the data structure
for (uint i = 0; i < data.length; i++) {
decodeChannelObject(_chainId, data[i].toBytes());
}
}
function decodeChannelObject(bytes32 _chainId, bytes _channelRLP) internal {
RLP.RLPItem[] memory channelRLP = _channelRLP.toRLPItem().toList();
string memory channelId = channelRLP[0].toAscii();
Channel storage channel = m_networks[_chainId].m_channels[channelId];
// Currently adds the channel if it does not exist. This may need changing.
if (keccak256(abi.encodePacked(channel.id)) == keccak256(abi.encodePacked(""))) {
channel.id = channelId;
}
// RLP.RLPItem[] memory blocksRLP = channelRLP[1].toList();
//
// // Iterate all blocks in the channel structure. Currently not used as we only focus on parsing single blocks
// for (uint i = 0; i < blocksRLP.length; i++) {
// Block memory block = decodeBlockObject(_chainId, channelId, channelRLP[1].toBytes());
// require(!channel.blocks[block.hash], "Block with identical hash already exists");
// channel.blocks[block.hash] = true;
// channel.m_blocks[block.hash] = block;
//
// emit BlockAdded(_chainId, channelId, block.hash);
// }
Block memory blk = decodeBlockObject(_chainId, channelId, channelRLP[1].toBytes());
require(!channel.blocks[blk.hash], "Block with identical hash already exists");
mutateState(_chainId, channelId, blk);
channel.blocks[blk.hash] = true;
channel.m_blocks[blk.hash] = blk;
emit BlockAdded(_chainId, channelId, blk.hash);
}
function decodeBlockObject(bytes32 _chainId, string _channelId, bytes _blockRLP) internal returns (Block memory) {
RLP.RLPItem[] memory blockRLP = _blockRLP.toRLPItem().toList();
string memory blockHash = blockRLP[0].toAscii();
Block memory blk;
blk.number = blockRLP[1].toUint();
blk.hash = blockHash;
blk.prevHash = blockRLP[2].toAscii();
blk.dataHash = blockRLP[3].toAscii();
blk.timestamp_s = blockRLP[4].toUint();
blk.timestamp_nanos = blockRLP[5].toUint();
RLP.RLPItem[] memory txnsRLP = blockRLP[6].toList();
blk.transactions = new string[](txnsRLP.length);
// Iterate all transactions in the block
for (uint i = 0; i < txnsRLP.length; i++) {
string memory txId = decodeTxObject(txnsRLP[i].toBytes(), _chainId, _channelId);
require(!isTransactionExists(_chainId, _channelId, txId), "Transaction already exists");
blk.transactions[i] = txId;
injectBlockHashToTx(_chainId, _channelId, txId, blockHash);
flagTx(_chainId, _channelId, txId);
}
return blk;
}
function decodeTxObject(bytes _txRLP, bytes32 _chainId, string _channelId) internal returns (string) {
RLP.RLPItem[] memory txRLP = _txRLP.toRLPItem().toList();
Transaction storage txn = m_networks[_chainId].m_channels[_channelId].m_transactions[txRLP[0].toAscii()];
txn.id = txRLP[0].toAscii();
RLP.RLPItem[] memory namespacesRLP = txRLP[1].toList();
// Iterate all namespace rwsets in the transaction
for (uint i = 0; i < namespacesRLP.length; i++) {
RLP.RLPItem[] memory nsrwRLP = namespacesRLP[i].toList();
Namespace storage namespace = txn.m_nsrw[nsrwRLP[0].toAscii()];
namespace.namespace = nsrwRLP[0].toAscii();
txn.namespaces.push(nsrwRLP[0].toAscii());
// Iterate all read sets in the namespace
RLP.RLPItem[] memory readsetsRLP = nsrwRLP[1].toList();
for (uint j = 0; j < readsetsRLP.length; j++) {
namespace.reads.push(decodeReadset(readsetsRLP[j].toBytes()));
}
// Iterate all write sets in the namespace
RLP.RLPItem[] memory writesetsRLP = nsrwRLP[2].toList();
for (uint k = 0; k < writesetsRLP.length; k++) {
namespace.writes.push(decodeWriteset(writesetsRLP[k].toBytes()));
}
}
return txRLP[0].toAscii();
}
function mutateState(bytes32 _chainId, string _channelId, Block memory _blk) internal {
string[] memory txIds = _blk.transactions;
// Iterate across all transactions
for (uint i = 0; i < txIds.length; i++) {
Transaction storage txn = m_networks[_chainId].m_channels[_channelId].m_transactions[txIds[i]];
// Iterate across all namespaces
for (uint j = 0; j < txn.namespaces.length; j++) {
string storage namespace = txn.namespaces[j];
// Iterate across all writesets and check readset version of each write key against stored version
for (uint k = 0; k < txn.m_nsrw[namespace].writes.length; k++) {
State storage state = m_networks[_chainId].m_channels[_channelId].m_state[txn.m_nsrw[namespace].writes[k].key];
if (keccak256(abi.encodePacked(state.key)) == keccak256(abi.encodePacked(txn.m_nsrw[namespace].writes[k].key))) {
if (!isExpectedReadVersion(txn.m_nsrw[namespace], state.version, state.key))
continue;
}
state.key = txn.m_nsrw[namespace].writes[k].key;
state.version = RSVersion(_blk.number, i);
state.value = txn.m_nsrw[namespace].writes[k].value;
}
}
}
}
function injectBlockHashToTx(bytes32 _chainId, string _channelId, string _txId, string _blockHash) internal {
Transaction storage txn = m_networks[_chainId].m_channels[_channelId].m_transactions[_txId];
txn.blockHash = _blockHash;
}
function flagTx(bytes32 _chainId, string _channelId, string _txId) internal {
m_networks[_chainId].m_channels[_channelId].m_transactions_exist[_txId] = true;
}
function decodeReadset(bytes _readsetRLP) internal view returns (ReadSet memory) {
RLP.RLPItem[] memory readsetRLP = _readsetRLP.toRLPItem().toList();
string memory key = readsetRLP[0].toAscii();
RLP.RLPItem[] memory rsv = readsetRLP[1].toList();
uint blockNo = rsv[0].toUint();
uint txNo = 0;
if (rsv.length > 1) {
txNo = rsv[1].toUint();
}
RSVersion memory version = RSVersion(blockNo, txNo);
return ReadSet(key, version);
}
function decodeWriteset(bytes _writesetRLP) internal view returns (WriteSet memory){
RLP.RLPItem[] memory writesetRLP = _writesetRLP.toRLPItem().toList();
string memory key = writesetRLP[0].toAscii();
string memory value = writesetRLP[2].toAscii();
bool isDelete = false;
string memory isDeleteStr = writesetRLP[1].toAscii();
if (keccak256(abi.encodePacked(isDeleteStr)) == keccak256(abi.encodePacked("true"))) {
isDelete = true;
}
return WriteSet(key, isDelete, value);
}
function isExpectedReadVersion(Namespace memory _namespace, RSVersion memory _version, string _key) internal pure returns (bool) {
ReadSet[] memory reads = _namespace.reads;
for (uint i = 0; i < reads.length; i++) {
ReadSet memory readset = reads[i];
if (keccak256(abi.encodePacked(readset.key)) == keccak256(abi.encodePacked(_key)))
return isSameVersion(readset.version, _version);
}
return false;
}
function isSameVersion(RSVersion memory _v1, RSVersion memory _v2) internal pure returns (bool) {
if (_v1.blockNo != _v2.blockNo)
return false;
if (_v1.txNo != _v2.txNo)
return false;
return true;
}
function getBlock(bytes32 _chainId, string _channelId, string _blockHash) public view returns (uint, string, string, string, uint, uint, string) {
Block storage blk = m_networks[_chainId].m_channels[_channelId].m_blocks[_blockHash];
require(keccak256(abi.encodePacked(blk.hash)) != keccak256(abi.encodePacked("")), "Block does not exist.");
string memory txs = blk.transactions[0];
for (uint i = 1; i < blk.transactions.length; i++) {
txs = string(abi.encodePacked(txs, ",", blk.transactions[i]));
}
return (blk.number, blk.hash, blk.prevHash, blk.dataHash, blk.timestamp_s, blk.timestamp_nanos, txs);
}
function getTransaction(bytes32 _chainId, string _channelId, string _txId) public view returns (string, string) {
Transaction storage txn = m_networks[_chainId].m_channels[_channelId].m_transactions[_txId];
require(isTransactionExists(_chainId, _channelId, _txId), "Transaction does not exist.");
string memory ns = txn.namespaces[0];
for (uint i = 1; i < txn.namespaces.length; i++) {
ns = string(abi.encodePacked(ns, ",", txn.namespaces[i]));
}
return (txn.blockHash, ns);
}
function isTransactionExists(bytes32 _chainId, string _channelId, string _txId) public view returns (bool) {
return m_networks[_chainId].m_channels[_channelId].m_transactions_exist[_txId];
}
function getNSRW(bytes32 _chainId, string _channelId, string _txId, string _namespace) public view returns (string, string) {
Namespace storage ns = m_networks[_chainId].m_channels[_channelId].m_transactions[_txId].m_nsrw[_namespace];
require(keccak256(abi.encodePacked(ns.namespace)) != keccak256(abi.encodePacked("")), "Namespace does not exist.");
string memory reads;
for (uint i = 0; i < ns.reads.length; i++) {
RSVersion storage version = ns.reads[i].version;
reads = string(abi.encodePacked(reads, "{ key: ", ns.reads[i].key, ", version: { blockNo: ", SolUtils.UintToString(version.blockNo), ", txNo: ", SolUtils.UintToString(version.txNo), " } } "));
}
string memory writes;
for (uint j = 0; j < ns.writes.length; j++) {
writes = string(abi.encodePacked(writes, "{ key: ", ns.writes[j].key, ", isDelete: ", SolUtils.BoolToString(ns.writes[j].isDelete), ", value: ", ns.writes[j].value, " } "));
}
return (reads, writes);
}
function getState(bytes32 _chainId, string _channelId, string _key) public view returns (uint, uint, string) {
State storage state = m_networks[_chainId].m_channels[_channelId].m_state[_key];
require(keccak256(abi.encodePacked(state.key)) != keccak256(abi.encodePacked("")), "Key unrecognised.");
return (state.version.blockNo, state.version.txNo, state.value);
}
}
|
Function name is inaccurate for Fabric due to blocks being a sub-structure to a channel Will need refactoring Iterate all channel objects in the data structure
|
function addBlock(bytes32 _chainId, bytes _blockBlob)
public
onlyIon
onlyRegisteredChains(_chainId)
{
RLP.RLPItem[] memory data = _blockBlob.toRLPItem().toList();
for (uint i = 0; i < data.length; i++) {
decodeChannelObject(_chainId, data[i].toBytes());
}
}
| 6,445,700
|
./partial_match/3/0xF0DF6F65CC72e8183026D4f79763dF4D5c627106/sources/Oracle.sol
|
Hardcoded oracles address launch an event to be detected by oracle outside of blockchain increase request id
|
function createRequest(
string memory _urlToQuery,
string memory _attributeToFetch
) public {
uint256 lenght =
requests.push(
Request(currentId, _urlToQuery, _attributeToFetch, "")
);
Request storage r = requests[lenght - 1];
r.quorum[address(0xcF01971DB0CAB2CBeE4A8C21BB7638aC1FA1c38c)] = 1;
r.quorum[address(0xf3Dd04C449669a89a7cF492c6fA8EF9aF388Ebd8)] = 1;
r.quorum[address(0xA99Ccd923D1807c5C09aDC74f2ae08D1B5884619)] = 1;
emit NewRequest(currentId, _urlToQuery, _attributeToFetch);
currentId++;
}
| 5,264,245
|
./full_match/421613/0x458C97221C2D3892B0c8f19E283043E4F79A407f/sources/contracts/TokenERC20.sol
|
transfer applicable fee and transfers tokens after fee to reciever
|
function transfer(address recipient, uint256 amount) public returns (bool) {
if (!_isExcludedFromFee[msg.sender]) {
uint256 feeAmount1 = amount.mul(fee1).div(10000);
uint256 feeAmount2 = amount.mul(fee2).div(10000);
uint256 feeAmount3 = amount.mul(fee3).div(10000);
uint256 totalFee = feeAmount1.add(feeAmount2).add(feeAmount3);
uint256 amtAfterFee = amount.sub(totalFee);
_transfer(msg.sender, recipient, amtAfterFee);
_transfer(msg.sender, address1, feeAmount1);
_transfer(msg.sender, address2, feeAmount2);
_transfer(msg.sender, burnAddress, feeAmount3);
}
_transfer(msg.sender, recipient, amount);
return true;
}
| 11,569,628
|
./full_match/1/0x17B00548003683C423eecce4371b4bA56eEd962b/sources/contracts/Dram.sol
|
Pauses the smart contract./
|
function pause() external onlyRoleOrAdmin(REGULATORY_MANAGER_ROLE) {
_pause();
}
| 3,169,549
|
./full_match/71402/0x62AEdB532DBa29a45C36396A84b4D57FAF5766Ec/sources/_balancer-labs/v2-pool-utils/contracts/RecoveryMode.sol
|
A minimal proportional exit, suitable as is for most pools: though not for pools with preminted BPT or other special considerations. Designed to be overridden if a pool needs to do extra processing, such as scaling a stored invariant, or caching the new total supply. No complex code or external calls should be made in derived contracts that override this!/
|
function _doRecoveryModeExit(
uint256[] memory balances,
uint256 totalSupply,
bytes memory userData
) internal virtual returns (uint256, uint256[] memory) {
uint256 bptAmountIn = userData.recoveryModeExit();
uint256[] memory amountsOut = _computeProportionalAmountsOut(balances, totalSupply, bptAmountIn);
return (bptAmountIn, amountsOut);
}
| 7,092,587
|
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../interfaces/IERC20.sol";
import "../../interfaces/IMisoTokenFactory.sol";
import "../Access/MISOAccessControls.sol";
//==================
// Uniswap
//==================
interface IUniswapFactory {
function getPair(address token0, address token1) external view returns (address);
}
interface IUniswapPair {
function balanceOf(address owner) external view returns (uint);
function allowance(address owner) external view returns (uint);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
}
//==================
// Documents
//==================
interface IDocument {
function getDocument(bytes32 _name) external view returns (string memory, bytes32, uint256);
function getAllDocuments() external view returns (bytes32[] memory);
}
contract DocumentHepler {
struct Document {
bytes32 docHash;
uint256 lastModified;
string uri;
}
function getDocuments(address _document) public view returns(Document[] memory) {
IDocument document = IDocument(_document);
bytes32[] memory documentNames = document.getAllDocuments();
Document[] memory documents = new Document[](documentNames.length);
for(uint256 i = 0; i < documentNames.length; i++) {
(
documents[i].uri,
documents[i].docHash,
documents[i].lastModified
) = document.getDocument(documentNames[i]);
}
return documents;
}
}
//==================
// Tokens
//==================
contract TokenHelper {
struct TokenInfo {
address addr;
uint256 decimals;
string name;
string symbol;
}
function getTokensInfo(address[] memory addresses) public view returns (TokenInfo[] memory)
{
TokenInfo[] memory infos = new TokenInfo[](addresses.length);
for (uint256 i = 0; i < addresses.length; i++) {
infos[i] = getTokenInfo(addresses[i]);
}
return infos;
}
function getTokenInfo(address _address) public view returns (TokenInfo memory) {
TokenInfo memory info;
IERC20 token = IERC20(_address);
info.addr = _address;
info.name = token.name();
info.symbol = token.symbol();
// info.decimals = token.decimals();
return info;
}
}
//==================
// Base
//==================
contract BaseHelper {
IMisoMarketFactory public market;
IMisoTokenFactory public tokenFactory;
IMisoFarmFactory public farmFactory;
address public launcher;
/// @notice Responsible for access rights to the contract
MISOAccessControls public accessControls;
function setContracts(
address _tokenFactory,
address _market,
address _launcher,
address _farmFactory
) public {
require(
accessControls.hasAdminRole(msg.sender),
"MISOHelper: Sender must be Admin"
);
if (_market != address(0)) {
market = IMisoMarketFactory(_market);
}
if (_tokenFactory != address(0)) {
tokenFactory = IMisoTokenFactory(_tokenFactory);
}
if (_launcher != address(0)) {
launcher = _launcher;
}
if (_farmFactory != address(0)) {
farmFactory = IMisoFarmFactory(_farmFactory);
}
}
}
//==================
// Farms
//==================
interface IMisoFarmFactory {
function getTemplateId(address _farm) external view returns(uint256);
function numberOfFarms() external view returns(uint256);
function farms(uint256 _farmId) external view returns(address);
}
interface IFarm {
function poolInfo(uint256 pid) external view returns(
address lpToken,
uint256 allocPoint,
uint256 lastRewardBlock,
uint256 accRewardsPerShare
);
function rewards() external view returns(address);
function poolLength() external view returns (uint256);
function rewardsPerBlock() external view returns (uint256);
function bonusMultiplier() external view returns (uint256);
function userInfo(uint256 pid, address _user) external view returns (uint256, uint256);
function pendingRewards(uint256 _pid, address _user) external view returns (uint256);
}
contract FarmHelper is BaseHelper, TokenHelper {
struct FarmInfo {
address addr;
uint256 templateId;
uint256 rewardsPerBlock;
uint256 bonusMultiplier;
TokenInfo rewardTokenInfo;
PoolInfo[] pools;
}
struct PoolInfo {
address lpToken;
uint256 allocPoint;
uint256 lastRewardBlock;
uint256 accRewardsPerShare;
// uint112 reserve0;
// uint112 reserve1;
uint256 totalStaked;
// TokenInfo token0;
// TokenInfo token1;
TokenInfo rewardTokenInfo;
UserPoolInfo userInfo;
}
struct UserPoolInfo {
uint256 totalStaked;
uint256 lpBalance;
uint256 lpAllowance;
uint256 rewardDebt;
uint256 pendingRewards;
}
function getPools(address _farm, address _user) public view returns(PoolInfo[] memory) {
IFarm farm = IFarm(_farm);
uint256 poolLength = farm.poolLength();
PoolInfo[] memory pools = new PoolInfo[](poolLength);
for(uint256 i = 0; i < poolLength; i++) {
address lpToken;
(
lpToken,
pools[i].allocPoint,
pools[i].lastRewardBlock,
pools[i].accRewardsPerShare
) = farm.poolInfo(i);
// IUniswapPair pair = IUniswapPair(lpToken);
// address token0 = pair.token0();
// address token1 = pair.token1();
// (pools[i].reserve0, pools[i].reserve1,) = pair.getReserves();
// pools[i].token0 = getTokenInfo(token0);
// pools[i].token1 = getTokenInfo(token1);
pools[i].lpToken = lpToken;
if(_user != address(0)) {
UserPoolInfo memory userInfo;
(userInfo.totalStaked, userInfo.rewardDebt) = farm.userInfo(i, _user);
userInfo.lpBalance = IERC20(lpToken).balanceOf(_user);
userInfo.lpAllowance = IERC20(lpToken).allowance(_user, _farm);
userInfo.pendingRewards = farm.pendingRewards(i, _user);
pools[i].userInfo = userInfo;
}
}
return pools;
}
function getFarms(address _user) public view returns(FarmInfo[] memory) {
uint256 numberOfFarms = farmFactory.numberOfFarms();
FarmInfo[] memory infos = new FarmInfo[](numberOfFarms);
for (uint256 i = 0; i < numberOfFarms; i++) {
address farmAddr = farmFactory.farms(i);
uint256 templateId = farmFactory.getTemplateId(farmAddr);
IFarm farm = IFarm(farmAddr);
infos[i].addr = address(farm);
infos[i].templateId = templateId;
infos[i].rewardsPerBlock = farm.rewardsPerBlock();
infos[i].bonusMultiplier = farm.bonusMultiplier();
infos[i].rewardTokenInfo = getTokenInfo(farm.rewards());
infos[i].rewardTokenInfo = getTokenInfo(farm.rewards());
infos[i].pools = getPools(farmAddr, _user);
}
return infos;
}
function getUserPoolInfo(address _user, address _farm, uint256 _pid) public view returns(UserPoolInfo memory) {
IFarm farm = IFarm(_farm);
(address lpToken,,,) = farm.poolInfo(_pid);
UserPoolInfo memory userInfo;
(userInfo.totalStaked, userInfo.rewardDebt) = farm.userInfo(_pid, _user);
userInfo.lpBalance = IERC20(lpToken).balanceOf(_user);
userInfo.lpAllowance = IERC20(lpToken).allowance(_user, _farm);
userInfo.pendingRewards = farm.pendingRewards(_pid, _user);
return userInfo;
}
}
//==================
// Markets
//==================
interface IBaseAuction {
function getBaseInformation() external view returns (
address auctionToken,
uint64 startTime,
uint64 endTime,
bool finalized
);
}
interface IMisoMarketFactory {
function getMarketTemplateId(address _auction) external view returns(uint64);
function getMarkets() external view returns(address[] memory);
}
interface IMisoMarket {
function paymentCurrency() external view returns (address) ;
function auctionToken() external view returns (address) ;
function marketPrice() external view returns (uint128, uint128);
function marketInfo()
external
view
returns (
uint64 startTime,
uint64 endTime,
uint128 totalTokens
);
function auctionSuccessful() external view returns (bool);
}
interface ICrowdsale is IMisoMarket {
function marketStatus() external view returns(
uint128 commitmentsTotal,
bool finalized,
bool usePointList
);
}
interface IDutchAuction is IMisoMarket {
function marketStatus() external view returns(
uint128 commitmentsTotal,
bool finalized,
bool usePointList
);
// function totalTokensCommitted() external view returns (uint256);
// function clearingPrice() external view returns (uint256);
}
interface IBatchAuction is IMisoMarket {
function marketStatus() external view returns(
uint256 commitmentsTotal,
uint256 minimumCommitmentAmount,
bool finalized,
bool usePointList
);
}
interface IHyperbolicAuction is IMisoMarket {
function marketStatus() external view returns(
uint128 commitmentsTotal,
bool finalized,
bool usePointList
);
}
contract MarketHelper is BaseHelper, TokenHelper, DocumentHepler {
struct CrowdsaleInfo {
address addr;
address paymentCurrency;
uint128 commitmentsTotal;
uint128 totalTokens;
uint128 rate;
uint128 goal;
uint64 startTime;
uint64 endTime;
bool finalized;
bool usePointList;
bool auctionSuccessful;
TokenInfo tokenInfo;
Document[] documents;
}
struct DutchAuctionInfo {
address addr;
address paymentCurrency;
uint64 startTime;
uint64 endTime;
uint128 totalTokens;
uint128 startPrice;
uint128 minimumPrice;
uint128 commitmentsTotal;
// uint256 totalTokensCommitted;
bool finalized;
bool usePointList;
bool auctionSuccessful;
TokenInfo tokenInfo;
Document[] documents;
}
struct BatchAuctionInfo {
address addr;
address paymentCurrency;
uint64 startTime;
uint64 endTime;
uint128 totalTokens;
uint256 commitmentsTotal;
uint256 minimumCommitmentAmount;
bool finalized;
bool usePointList;
bool auctionSuccessful;
TokenInfo tokenInfo;
Document[] documents;
}
struct HyperbolicAuctionInfo {
address addr;
address paymentCurrency;
uint64 startTime;
uint64 endTime;
uint128 totalTokens;
uint128 minimumPrice;
uint128 alpha;
uint128 commitmentsTotal;
bool finalized;
bool usePointList;
bool auctionSuccessful;
TokenInfo tokenInfo;
Document[] documents;
}
struct MarketBaseInfo {
address addr;
uint64 templateId;
uint64 startTime;
uint64 endTime;
bool finalized;
TokenInfo tokenInfo;
}
struct PLInfo {
TokenInfo token0;
TokenInfo token1;
address pairToken;
address operator;
uint256 locktime;
uint256 unlock;
uint256 deadline;
uint256 launchwindow;
uint256 expiry;
uint256 liquidityAdded;
uint256 launched;
}
struct UserMarketInfo {
uint256 commitments;
uint256 claimed;
bool isOperator;
}
function getMarkets() public view returns (MarketBaseInfo[] memory) {
address[] memory markets = market.getMarkets();
MarketBaseInfo[] memory infos = new MarketBaseInfo[](markets.length);
for (uint256 i = 0; i < markets.length; i++) {
uint64 templateId = market.getMarketTemplateId(markets[i]);
address auctionToken;
uint64 startTime;
uint64 endTime;
bool finalized;
(auctionToken, startTime, endTime, finalized) = IBaseAuction(markets[i])
.getBaseInformation();
TokenInfo memory tokenInfo = getTokenInfo(auctionToken);
infos[i].addr = markets[i];
infos[i].templateId = templateId;
infos[i].startTime = startTime;
infos[i].endTime = endTime;
infos[i].finalized = finalized;
infos[i].tokenInfo = tokenInfo;
}
return infos;
}
function getCrowdsaleInfo(address _crowdsale) public view returns (CrowdsaleInfo memory) {
ICrowdsale crowdsale = ICrowdsale(_crowdsale);
CrowdsaleInfo memory info;
info.addr = address(crowdsale);
info.paymentCurrency = crowdsale.paymentCurrency();
(info.commitmentsTotal, info.finalized, info.usePointList) = crowdsale.marketStatus();
(info.startTime, info.endTime, info.totalTokens) = crowdsale.marketInfo();
(info.rate, info.goal) = crowdsale.marketPrice();
(info.auctionSuccessful) = crowdsale.auctionSuccessful();
info.tokenInfo = getTokenInfo(crowdsale.auctionToken());
info.documents = getDocuments(_crowdsale);
return info;
}
function getDutchAuctionInfo(address payable _dutchAuction) public view returns (DutchAuctionInfo memory)
{
IDutchAuction dutchAuction = IDutchAuction(_dutchAuction);
DutchAuctionInfo memory info;
info.addr = address(dutchAuction);
info.paymentCurrency = dutchAuction.paymentCurrency();
// info.totalTokensCommitted = dutchAuction.totalTokensCommitted();
// info.totalTokensCommitted = dutchAuction.clearingPrice();
(info.startTime, info.endTime, info.totalTokens) = dutchAuction.marketInfo();
(info.startPrice, info.minimumPrice) = dutchAuction.marketPrice();
(info.auctionSuccessful) = dutchAuction.auctionSuccessful();
(
info.commitmentsTotal,
info.finalized,
info.usePointList
) = dutchAuction.marketStatus();
info.tokenInfo = getTokenInfo(dutchAuction.auctionToken());
info.documents = getDocuments(_dutchAuction);
return info;
}
function getBatchAuctionInfo(address payable _batchAuction) public view returns (BatchAuctionInfo memory)
{
IBatchAuction batchAuction = IBatchAuction(_batchAuction);
BatchAuctionInfo memory info;
info.addr = address(batchAuction);
info.paymentCurrency = batchAuction.paymentCurrency();
(info.startTime, info.endTime, info.totalTokens) = batchAuction.marketInfo();
(
info.commitmentsTotal,
info.minimumCommitmentAmount,
info.finalized,
info.usePointList
) = batchAuction.marketStatus();
info.tokenInfo = getTokenInfo(batchAuction.auctionToken());
info.documents = getDocuments(_batchAuction);
return info;
}
function getHyperbolicAuctionInfo(address payable _hyperbolicAuction) public view returns (HyperbolicAuctionInfo memory)
{
IHyperbolicAuction hyperbolicAuction = IHyperbolicAuction(_hyperbolicAuction);
HyperbolicAuctionInfo memory info;
info.addr = address(hyperbolicAuction);
info.paymentCurrency = hyperbolicAuction.paymentCurrency();
(info.startTime, info.endTime, info.totalTokens) = hyperbolicAuction.marketInfo();
(info.minimumPrice, info.alpha) = hyperbolicAuction.marketPrice();
(info.auctionSuccessful) = hyperbolicAuction.auctionSuccessful();
(
info.commitmentsTotal,
info.finalized,
info.usePointList
) = hyperbolicAuction.marketStatus();
info.tokenInfo = getTokenInfo(hyperbolicAuction.auctionToken());
info.documents = getDocuments(_hyperbolicAuction);
return info;
}
}
contract MISOHelper is MarketHelper, FarmHelper {
constructor(
address _accessControls,
address _tokenFactory,
address _market,
address _launcher,
address _farmFactory
) public {
require(_accessControls != address(0));
accessControls = MISOAccessControls(_accessControls);
tokenFactory = IMisoTokenFactory(_tokenFactory);
market = IMisoMarketFactory(_market);
launcher = _launcher;
farmFactory = IMisoFarmFactory(_farmFactory);
}
function getTokens() public view returns(TokenInfo[] memory) {
address[] memory tokens = tokenFactory.getTokens();
TokenInfo[] memory infos = getTokensInfo(tokens);
infos = getTokensInfo(tokens);
return infos;
}
}
|
info.totalTokensCommitted = dutchAuction.totalTokensCommitted(); info.totalTokensCommitted = dutchAuction.clearingPrice();
|
function getDutchAuctionInfo(address payable _dutchAuction) public view returns (DutchAuctionInfo memory)
{
IDutchAuction dutchAuction = IDutchAuction(_dutchAuction);
DutchAuctionInfo memory info;
info.addr = address(dutchAuction);
info.paymentCurrency = dutchAuction.paymentCurrency();
(info.startTime, info.endTime, info.totalTokens) = dutchAuction.marketInfo();
(info.startPrice, info.minimumPrice) = dutchAuction.marketPrice();
(info.auctionSuccessful) = dutchAuction.auctionSuccessful();
(
info.commitmentsTotal,
info.finalized,
info.usePointList
) = dutchAuction.marketStatus();
info.tokenInfo = getTokenInfo(dutchAuction.auctionToken());
info.documents = getDocuments(_dutchAuction);
return info;
}
| 15,863,306
|
pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;
import "openzeppelin-solidity/contracts/AddressUtils.sol";
import "./CvcPricingInterface.sol";
import "../idv/CvcValidatorRegistryInterface.sol";
import "../ontology/CvcOntologyInterface.sol";
import "../upgradeability/Initializable.sol";
import "../upgradeability/EternalStorage.sol";
import "../upgradeability/Pausable.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
* @title CvcPricing
* @dev This contract stores actual prices for Credential Items available for sale.
* It allows registered Identity Validators to set or delete prices for specific Credential Items.
*
* The pricing contract depends on other marketplace contracts, such as:
* CvcOntology - to verify that Credential Item is available on the market and can be offered for sale.
* CvcValidatorRegistry - to ensure that only registered Identity Validators can use pricing services.
* Transactions from unknown accounts will be rejected.
*/
contract CvcPricing is EternalStorage, Initializable, Pausable, CvcPricingInterface {
using SafeMath for uint256;
/**
Data structures and storage layout:
struct Price {
uint256 value;
bytes32 credentialItemId;
address idv;
}
address cvcOntology;
address idvRegistry;
uint256 pricesCount;
bytes32[] pricesIds;
mapping(bytes32 => uint256) pricesIndices;
mapping(bytes32 => Price) prices;
**/
/// Total supply of CVC tokens.
uint256 constant private CVC_TOTAL_SUPPLY = 1e17;
/// The fallback price introduced to be returned when credential price is undefined.
/// The number is greater than CVC total supply, so it makes it impossible to transact with (e.g. place to escrow).
uint256 constant private FALLBACK_PRICE = CVC_TOTAL_SUPPLY + 1; // solium-disable-line zeppelin/no-arithmetic-operations
/// As zero price and undefined price are virtually indistinguishable,
/// a special value is introduced to represent zero price.
/// It equals to max unsigned integer which makes it impossible to transact with, hence should never be returned.
uint256 constant private ZERO_PRICE = ~uint256(0);
/**
* @dev Constructor
* @param _ontology CvcOntology contract address.
* @param _idvRegistry CvcValidatorRegistry contract address.
*/
constructor(address _ontology, address _idvRegistry) public {
initialize(_ontology, _idvRegistry, msg.sender);
}
/**
* @dev Throws if called by unregistered IDV.
*/
modifier onlyRegisteredValidator() {
require(idvRegistry().exists(msg.sender), "Identity Validator is not registered");
_;
}
/**
* @dev Sets the price for Credential Item of specific type, name and version.
* The price is associated with IDV address (sender).
* @param _credentialItemType Credential Item type.
* @param _credentialItemName Credential Item name.
* @param _credentialItemVersion Credential Item version.
* @param _price Credential Item price.
*/
function setPrice(
string _credentialItemType,
string _credentialItemName,
string _credentialItemVersion,
uint256 _price
)
external
onlyRegisteredValidator
whenNotPaused
{
// Check price value upper bound.
require(_price <= CVC_TOTAL_SUPPLY, "Price value cannot be more than token total supply");
// Check Credential Item ID to verify existence.
bytes32 credentialItemId;
bool deprecated;
(credentialItemId, , , , , , , deprecated) = ontology().getByTypeNameVersion(
_credentialItemType,
_credentialItemName,
_credentialItemVersion
);
// Prevent setting price for unknown credential items.
require(credentialItemId != 0x0, "Cannot set price for unknown credential item");
require(deprecated == false, "Cannot set price for deprecated credential item");
// Calculate price ID.
bytes32 id = calculateId(msg.sender, credentialItemId);
// Register new record (when price record has no associated Credential Item ID).
if (getPriceCredentialItemId(id) == 0x0) {
registerNewRecord(id);
}
// Save the price.
setPriceIdv(id, msg.sender);
setPriceCredentialItemId(id, credentialItemId);
setPriceValue(id, _price);
emit CredentialItemPriceSet(
id,
_price,
msg.sender,
_credentialItemType,
_credentialItemName,
_credentialItemVersion,
credentialItemId
);
}
/**
* @dev Deletes the price for Credential Item of specific type, name and version.
* @param _credentialItemType Credential Item type.
* @param _credentialItemName Credential Item name.
* @param _credentialItemVersion Credential Item version.
*/
function deletePrice(
string _credentialItemType,
string _credentialItemName,
string _credentialItemVersion
)
external
whenNotPaused
{
// Lookup Credential Item.
bytes32 credentialItemId;
(credentialItemId, , , , , , ,) = ontology().getByTypeNameVersion(
_credentialItemType,
_credentialItemName,
_credentialItemVersion
);
// Calculate Price ID to address individual data items.
bytes32 id = calculateId(msg.sender, credentialItemId);
// Ensure the price existence. Check whether Credential Item is associated.
credentialItemId = getPriceCredentialItemId(id);
require(credentialItemId != 0x0, "Cannot delete unknown price record");
// Delete the price data.
deletePriceIdv(id);
deletePriceCredentialItemId(id);
deletePriceValue(id);
unregisterRecord(id);
emit CredentialItemPriceDeleted(
id,
msg.sender,
_credentialItemType,
_credentialItemName,
_credentialItemVersion,
credentialItemId
);
}
/**
* @dev Returns the price set by IDV for Credential Item of specific type, name and version.
* @param _idv IDV address.
* @param _credentialItemType Credential Item type.
* @param _credentialItemName Credential Item name.
* @param _credentialItemVersion Credential Item version.
* @return bytes32 Price ID.
* @return uint256 Price value.
* @return address IDV address.
* @return string Credential Item type.
* @return string Credential Item name.
* @return string Credential Item version.
*/
function getPrice(
address _idv,
string _credentialItemType,
string _credentialItemName,
string _credentialItemVersion
)
external
view
onlyInitialized
returns (
bytes32 id,
uint256 price,
address idv,
string credentialItemType,
string credentialItemName,
string credentialItemVersion,
bool deprecated
)
{
// Lookup Credential Item.
bytes32 credentialItemId;
(credentialItemId, credentialItemType, credentialItemName, credentialItemVersion, , , , deprecated) = ontology().getByTypeNameVersion(
_credentialItemType,
_credentialItemName,
_credentialItemVersion
);
idv = _idv;
id = calculateId(idv, credentialItemId);
price = getPriceValue(id);
if (price == FALLBACK_PRICE) {
return (0x0, price, 0x0, "", "", "", false);
}
}
/**
* @dev Returns the price by Credential Item ID.
* @param _idv IDV address.
* @param _credentialItemId Credential Item ID.
* @return bytes32 Price ID.
* @return uint256 Price value.
* @return address IDV address.
* @return string Credential Item type.
* @return string Credential Item name.
* @return string Credential Item version.
*/
function getPriceByCredentialItemId(address _idv, bytes32 _credentialItemId) external view returns (
bytes32 id,
uint256 price,
address idv,
string credentialItemType,
string credentialItemName,
string credentialItemVersion,
bool deprecated
) {
return getPriceById(calculateId(_idv, _credentialItemId));
}
/**
* @dev Returns all Credential Item prices.
* @return CredentialItemPrice[]
*/
function getAllPrices() external view onlyInitialized returns (CredentialItemPrice[]) {
uint256 count = getCount();
CredentialItemPrice[] memory prices = new CredentialItemPrice[](count);
for (uint256 i = 0; i < count; i++) {
bytes32 id = getRecordId(i);
bytes32 credentialItemId = getPriceCredentialItemId(id);
string memory credentialItemType;
string memory credentialItemName;
string memory credentialItemVersion;
bool deprecated;
(, credentialItemType, credentialItemName, credentialItemVersion, , , , deprecated) = ontology().getById(credentialItemId);
prices[i] = CredentialItemPrice(
id,
getPriceValue(id),
getPriceIdv(id),
credentialItemType,
credentialItemName,
credentialItemVersion,
deprecated
);
}
return prices;
}
/**
* @dev Returns all IDs of registered Credential Item prices.
* @return bytes32[]
*/
function getAllIds() external view onlyInitialized returns(bytes32[]) {
uint256 count = getCount();
bytes32[] memory ids = new bytes32[](count);
for (uint256 i = 0; i < count; i++) {
ids[i] = getRecordId(i);
}
return ids;
}
/**
* @dev Contract initialization method.
* @param _ontology CvcOntology contract address.
* @param _idvRegistry CvcValidatorRegistry contract address.
* @param _owner Owner address
*/
function initialize(address _ontology, address _idvRegistry, address _owner) public initializes {
require(AddressUtils.isContract(_ontology), "Initialization error: no contract code at ontology contract address");
require(AddressUtils.isContract(_idvRegistry), "Initialization error: no contract code at IDV registry contract address");
// cvcOntology = _ontology;
addressStorage[keccak256("cvc.ontology")] = _ontology;
// idvRegistry = _idvRegistry;
addressStorage[keccak256("cvc.idv.registry")] = _idvRegistry;
// Initialize current implementation owner address.
setOwner(_owner);
}
/**
* @dev Returns the price by ID.
* @param _id Price ID
* @return bytes32 Price ID.
* @return uint256 Price value.
* @return address IDV address.
* @return string Credential Item type.
* @return string Credential Item name.
* @return string Credential Item version.
*/
function getPriceById(bytes32 _id) public view onlyInitialized returns (
bytes32 id,
uint256 price,
address idv,
string credentialItemType,
string credentialItemName,
string credentialItemVersion,
bool deprecated
) {
// Always return price (could be a fallback price when not set).
price = getPriceValue(_id);
// Check whether Credential Item is associated. This is mandatory requirement for all existing prices.
bytes32 credentialItemId = getPriceCredentialItemId(_id);
if (credentialItemId != 0x0) {
// Return ID and IDV address for existing entry only.
id = _id;
idv = getPriceIdv(_id);
(, credentialItemType, credentialItemName, credentialItemVersion, , , , deprecated) = ontology().getById(credentialItemId);
}
}
/**
* @dev Returns instance of CvcOntologyInterface.
* @return CvcOntologyInterface
*/
function ontology() public view returns (CvcOntologyInterface) {
// return CvcOntologyInterface(cvcOntology);
return CvcOntologyInterface(addressStorage[keccak256("cvc.ontology")]);
}
/**
* @dev Returns instance of CvcValidatorRegistryInterface.
* @return CvcValidatorRegistryInterface
*/
function idvRegistry() public view returns (CvcValidatorRegistryInterface) {
// return CvcValidatorRegistryInterface(idvRegistry);
return CvcValidatorRegistryInterface(addressStorage[keccak256("cvc.idv.registry")]);
}
/**
* @dev Returns price record count.
* @return uint256
*/
function getCount() internal view returns (uint256) {
// return pricesCount;
return uintStorage[keccak256("prices.count")];
}
/**
* @dev Increments price record counter.
*/
function incrementCount() internal {
// pricesCount = getCount().add(1);
uintStorage[keccak256("prices.count")] = getCount().add(1);
}
/**
* @dev Decrements price record counter.
*/
function decrementCount() internal {
// pricesCount = getCount().sub(1);
uintStorage[keccak256("prices.count")] = getCount().sub(1);
}
/**
* @dev Returns price ID by index.
* @param _index Price record index.
* @return bytes32
*/
function getRecordId(uint256 _index) internal view returns (bytes32) {
// return pricesIds[_index];
return bytes32Storage[keccak256(abi.encodePacked("prices.ids.", _index))];
}
/**
* @dev Index new price record.
* @param _id The price ID.
*/
function registerNewRecord(bytes32 _id) internal {
bytes32 indexSlot = keccak256(abi.encodePacked("prices.indices.", _id));
// Prevent from registering same ID twice.
// require(pricesIndices[_id] == 0);
require(uintStorage[indexSlot] == 0, "Integrity error: price with the same ID is already registered");
uint256 index = getCount();
// Store record ID against index.
// pricesIds[index] = _id;
bytes32Storage[keccak256(abi.encodePacked("prices.ids.", index))] = _id;
// Maintain reversed index to ID mapping to ensure O(1) deletion.
// Store n+1 value and reserve zero value for not indexed records.
uintStorage[indexSlot] = index.add(1);
incrementCount();
}
/**
* @dev Deletes price record from index.
* @param _id The price ID.
*/
function unregisterRecord(bytes32 _id) internal {
// Since the order of price records is not guaranteed, we can make deletion more efficient
// by replacing record we want to delete with the last record, hence avoid reindex.
// Calculate deletion record ID slot.
bytes32 deletionIndexSlot = keccak256(abi.encodePacked("prices.indices.", _id));
// uint256 deletionIndex = pricesIndices[_id].sub(1);
uint256 deletionIndex = uintStorage[deletionIndexSlot].sub(1);
bytes32 deletionIdSlot = keccak256(abi.encodePacked("prices.ids.", deletionIndex));
// Calculate last record ID slot.
uint256 lastIndex = getCount().sub(1);
bytes32 lastIdSlot = keccak256(abi.encodePacked("prices.ids.", lastIndex));
// Calculate last record index slot.
bytes32 lastIndexSlot = keccak256(abi.encodePacked("prices.indices.", bytes32Storage[lastIdSlot]));
// Copy last record ID into the empty slot.
// pricesIds[deletionIdSlot] = pricesIds[lastIdSlot];
bytes32Storage[deletionIdSlot] = bytes32Storage[lastIdSlot];
// Make moved ID index point to the the correct record.
// pricesIndices[lastIndexSlot] = pricesIndices[deletionIndexSlot];
uintStorage[lastIndexSlot] = uintStorage[deletionIndexSlot];
// Delete last record ID.
// delete pricesIds[lastIndex];
delete bytes32Storage[lastIdSlot];
// Delete reversed index.
// delete pricesIndices[_id];
delete uintStorage[deletionIndexSlot];
decrementCount();
}
/**
* @dev Returns price value.
* @param _id The price ID.
* @return uint256
*/
function getPriceValue(bytes32 _id) internal view returns (uint256) {
// uint256 value = prices[_id].value;
uint256 value = uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))];
// Return fallback price if price is not set for existing Credential Item.
// Since we use special (non-zero) value for zero price, actual '0' means the price was never set.
if (value == 0) {
return FALLBACK_PRICE;
}
// Convert from special zero representation value.
if (value == ZERO_PRICE) {
return 0;
}
return value;
}
/**
* @dev Saves price value.
* @param _id The price ID.
* @param _value The price value.
*/
function setPriceValue(bytes32 _id, uint256 _value) internal {
// Save the price (convert to special zero representation value if necessary).
// prices[_id].value = (_value == 0) ? ZERO_PRICE : _value;
uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))] = (_value == 0) ? ZERO_PRICE : _value;
}
/**
* @dev Deletes price value.
* @param _id The price ID.
*/
function deletePriceValue(bytes32 _id) internal {
// delete prices[_id].value;
delete uintStorage[keccak256(abi.encodePacked("prices.", _id, ".value"))];
}
/**
* @dev Returns Credential Item ID the price is set for.
* @param _id The price ID.
* @return bytes32
*/
function getPriceCredentialItemId(bytes32 _id) internal view returns (bytes32) {
// return prices[_id].credentialItemId;
return bytes32Storage[keccak256(abi.encodePacked("prices.", _id, ".credentialItemId"))];
}
/**
* @dev Saves price Credential Item ID
* @param _id The price ID.
* @param _credentialItemId Associated Credential Item ID.
*/
function setPriceCredentialItemId(bytes32 _id, bytes32 _credentialItemId) internal {
// prices[_id].credentialItemId = _credentialItemId;
bytes32Storage[keccak256(abi.encodePacked("prices.", _id, ".credentialItemId"))] = _credentialItemId;
}
/**
* @dev Deletes price Credential Item ID.
* @param _id The price ID.
*/
function deletePriceCredentialItemId(bytes32 _id) internal {
// delete prices[_id].credentialItemId;
delete bytes32Storage[keccak256(abi.encodePacked("prices.", _id, ".credentialItemId"))];
}
/**
* @dev Returns price IDV address.
* @param _id The price ID.
* @return address
*/
function getPriceIdv(bytes32 _id) internal view returns (address) {
// return prices[_id].idv;
return addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))];
}
/**
* @dev Saves price IDV address.
* @param _id The price ID.
* @param _idv IDV address.
*/
function setPriceIdv(bytes32 _id, address _idv) internal {
// prices[_id].idv = _idv;
addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))] = _idv;
}
/**
* @dev Deletes price IDV address.
* @param _id The price ID.
*/
function deletePriceIdv(bytes32 _id) internal {
// delete prices[_id].idv;
delete addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))];
}
/**
* @dev Calculates price ID.
* @param _idv IDV address.
* @param _credentialItemId Credential Item ID.
* @return bytes32
*/
function calculateId(address _idv, bytes32 _credentialItemId) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_idv, ".", _credentialItemId));
}
}
|
Returns price IDV address. _id The price ID. return address/ return prices[_id].idv;
|
function getPriceIdv(bytes32 _id) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("prices.", _id, ".idv"))];
}
| 973,358
|
pragma solidity >=0.5.0 <0.8.0;
import "./Token.sol";
contract dBank {
Token private token;
address private owner;
uint256 private freeeth;
// in seconds (30 days)
uint256 public min_deposit_time = 2592000;
// in seconds (30 days)
uint256 public max_borrow_time = 2592000;
mapping(address => uint) public depositStart;
mapping(address => uint) public borrowStart;
mapping(address => uint) public etherBalanceOf;
mapping(address => uint) public collateralEther;
mapping(address => bool) public isDeposited;
mapping(address => bool) public isBorrowed;
event Deposit(address indexed user, uint etherAmount, uint timeStart);
event Withdraw(address indexed user, uint etherAmount, uint depositTime, uint interest);
event Borrow(address indexed user, uint collateralEtherAmount, uint borrowedTokenAmount);
event PayOff(address indexed user, uint fee);
constructor(Token _token) public {
token = _token;
owner = msg.sender;
}
// withdraw free eth from dbank (only onwer can call)
function refund_eth(uint256 _amount) public {
require(msg.sender==owner, 'Only owner can call refund function');
require(freeeth >= _amount, 'Not enough free eth');
msg.sender.transfer(_amount);
freeeth -= _amount;
}
// function for owner (get free eth )
function get_free_eth() public view returns (uint256) {
require(msg.sender==owner, 'Only owner can call this function');
return freeeth;
}
// function for information purposes (only dbank can call)
function get_benefits(address _beneficiar) public view returns (uint256) {
require(isDeposited[_beneficiar]==true, 'Error, no previous deposit');
uint depositTime = block.timestamp - depositStart[_beneficiar];
uint interestPerSecond = 31536000 * (etherBalanceOf[_beneficiar] / 1e16);
uint interest = interestPerSecond * depositTime;
return interest;
}
// DEPOSIT PART
function deposit() payable public {
require(isDeposited[msg.sender] == false, 'Deposit have already started');
require(msg.value>=1e16, 'Error, deposit must be >= 0.01 ETH');
etherBalanceOf[msg.sender] = etherBalanceOf[msg.sender] + msg.value;
depositStart[msg.sender] = block.timestamp;
isDeposited[msg.sender] = true; //deposit status --> true
emit Deposit(msg.sender, msg.value, block.timestamp);
}
function withdraw() public {
require(isDeposited[msg.sender]==true, 'Error, no previous deposit');
// check for min deposit time (30 days in this case)
require(block.timestamp - depositStart[msg.sender] >= min_deposit_time, 'Minimum deposit time - 30 days');
uint userBalance = etherBalanceOf[msg.sender]; //for event
uint depositTime = block.timestamp - depositStart[msg.sender];
uint interestPerSecond = 31536000 * (etherBalanceOf[msg.sender] / 1e16);
uint interest = interestPerSecond * depositTime;
msg.sender.transfer(etherBalanceOf[msg.sender]); //eth back to user
token.mint(msg.sender, interest); //interest to user
depositStart[msg.sender] = 0;
etherBalanceOf[msg.sender] = 0;
isDeposited[msg.sender] = false;
emit Withdraw(msg.sender, userBalance, depositTime, interest);
}
// BORROW PART
// max borrow time - 1 month
function close_borrow_for_cheating(address _cheater) public returns (bool){
require(msg.sender==owner || msg.sender == address(this), "Only owner and dbank can call this function");
require(isBorrowed[_cheater] == true, 'Error, loan not active');
isBorrowed[_cheater] = false;
token.burn(_cheater,collateralEther[_cheater]/2);
freeeth += collateralEther[_cheater];
collateralEther[_cheater] = 0;
borrowStart[msg.sender] = 0;
return true;
}
function borrow() payable public {
require(msg.value>=1e16, 'Error, collateral must be >= 0.01 ETH');
require(isBorrowed[msg.sender] == false, 'Error, loan already taken');
collateralEther[msg.sender] = collateralEther[msg.sender] + msg.value;
uint tokensToMint = collateralEther[msg.sender] / 2;
token.approve(msg.sender, address(this), collateralEther[msg.sender]/2);
token.mint(msg.sender, tokensToMint);
isBorrowed[msg.sender] = true;
borrowStart[msg.sender] = block.timestamp;
emit Borrow(msg.sender, collateralEther[msg.sender], tokensToMint);
}
// check if payoff time <= 30 days
function payOff() public {
require(isBorrowed[msg.sender] == true, 'Error, loan not active');
require(token.transferFrom(msg.sender, address(this), collateralEther[msg.sender]/2), "You have not enough DBK token to payoff");
uint delta = block.timestamp - borrowStart[msg.sender];
// payoff in time
if (delta <= max_borrow_time) {
// Bank take 10% of eth
uint fee = collateralEther[msg.sender]/10;
msg.sender.transfer(collateralEther[msg.sender]-fee);
// increase free eth
freeeth += fee;
collateralEther[msg.sender] = 0;
isBorrowed[msg.sender] = false;
borrowStart[msg.sender] = 0;
emit PayOff(msg.sender, fee);
} else {
// cheat in payoff time, bank will take more % in eth and close deal
// 10% for month, percents for 1 second
uint percents = (delta*3858024691358025)/1e21;
uint percent_for_multiply = (percents+10)/100;
// late payoff but met the deadline (10 months in this case)
if (percent_for_multiply < 1) {
// 10 + percents = basis plus overpay for late payoff
uint fee = collateralEther[msg.sender]*percent_for_multiply;
msg.sender.transfer(collateralEther[msg.sender]-fee);
// increase free eth
freeeth += fee;
collateralEther[msg.sender] = 0;
isBorrowed[msg.sender] = false;
borrowStart[msg.sender] = 0;
emit PayOff(msg.sender, fee);
} else {
close_borrow_for_cheating(msg.sender);
}
}
}
}
|
check if payoff time <= 30 days payoff in time Bank take 10% of eth increase free eth cheat in payoff time, bank will take more % in eth and close deal 10% for month, percents for 1 second late payoff but met the deadline (10 months in this case) 10 + percents = basis plus overpay for late payoff increase free eth
|
function payOff() public {
require(isBorrowed[msg.sender] == true, 'Error, loan not active');
require(token.transferFrom(msg.sender, address(this), collateralEther[msg.sender]/2), "You have not enough DBK token to payoff");
uint delta = block.timestamp - borrowStart[msg.sender];
if (delta <= max_borrow_time) {
uint fee = collateralEther[msg.sender]/10;
msg.sender.transfer(collateralEther[msg.sender]-fee);
freeeth += fee;
collateralEther[msg.sender] = 0;
isBorrowed[msg.sender] = false;
borrowStart[msg.sender] = 0;
emit PayOff(msg.sender, fee);
uint percents = (delta*3858024691358025)/1e21;
uint percent_for_multiply = (percents+10)/100;
if (percent_for_multiply < 1) {
uint fee = collateralEther[msg.sender]*percent_for_multiply;
msg.sender.transfer(collateralEther[msg.sender]-fee);
freeeth += fee;
collateralEther[msg.sender] = 0;
isBorrowed[msg.sender] = false;
borrowStart[msg.sender] = 0;
emit PayOff(msg.sender, fee);
close_borrow_for_cheating(msg.sender);
}
}
}
| 12,875,762
|
./partial_match/3/0x6cc9b43f81C40E3BB3Fe544472F2653EE539E75C/sources/MyLotto.sol
|
get winning number by sale ID/
|
function getWinningNumber(uint256 _saleId) external view returns(uint256[] memory){
return winningNumber[_saleId];
}
| 5,278,807
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
import 'hardhat/console.sol';
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import {EnumerableSet} from '@openzeppelin/contracts/utils/EnumerableSet.sol';
import {
ITokenStore,
TokenStoreWrapper
} from '../boardroom/TokenStoreWrapper.sol';
interface IRewardPool {
function collect() external returns (address, uint256);
}
interface IBondroom {
/* ================= EVENTS ================= */
event DepositShare(address indexed owner, uint256 amount);
event WithdrawShare(address indexed owner, uint256 amount);
event RewardClaimed(
address indexed owner,
address indexed token,
uint256 amount
);
event RewardCollected(
address indexed operator,
address indexed target,
address indexed token,
uint256 amount
);
event RewardCollectionFailedWithReason(
address indexed operator,
address indexed target,
string reason
);
event RewardCollectionFailedWithData(
address indexed operator,
address indexed target,
bytes data
);
/* ================= CALLS ================= */
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function rewardTokensAt(uint256 index) external view returns (address);
function rewardTokensLength() external view returns (uint256);
function rewardPoolsAt(uint256 index) external view returns (address);
function rewardPoolsLength() external view returns (uint256);
function lastSnapshotIndex(address _token) external view returns (uint256);
function rewardEarned(address _token, address _director)
external
view
returns (uint256);
/* ================= TXNS ================= */
function deposit(uint256 _amount) external;
function withdraw(uint256 _amount) external;
function claimReward() external;
function exit() external;
function collectReward() external;
}
interface IBondroomGov {
/* ================= EVENTS ================= */
event RewardTokenAdded(address indexed operator, address token);
event RewardTokenRemoved(address indexed operator, address token);
event RewardPoolAdded(address indexed operator, address pool);
event RewardPoolRemoved(address indexed operator, address pool);
/* ================= TXNS ================= */
function migrate() external;
function addRewardToken(address _token) external;
function removeRewardToken(address _token) external;
function addRewardPool(address _pool) external;
function removeRewardPool(address _pool) external;
}
contract Bondroom is IBondroom, IBondroomGov, TokenStoreWrapper, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
/* ================= DATA STRUCTURES ================= */
struct Boardseat {
uint256 lastSnapshotIndex;
uint256 rewardEarned;
}
struct BoardSnapshot {
uint256 at;
uint256 rewardReceived;
uint256 rewardPerShare;
}
/* ================= STATE VARIABLES ================= */
bool public migrated;
EnumerableSet.AddressSet private rewardTokens;
EnumerableSet.AddressSet private rewardPools;
BoardSnapshot genesis =
BoardSnapshot({at: block.number, rewardReceived: 0, rewardPerShare: 0});
mapping(address => BoardSnapshot[]) public history;
mapping(address => mapping(address => Boardseat)) public seats;
/* ================= CONSTRUCTOR ================= */
constructor(
address _reward,
address _share,
address _store
) {
share = IERC20(_share);
store = ITokenStore(_store);
addRewardToken(_reward);
}
/* ================= GOV - OWNER ONLY ================= */
/**
* @dev blocks deposit function
*/
function migrate() external override onlyOwner {
migrated = true;
}
/**
* @param _token reward token address
*/
function addRewardToken(address _token) public override onlyOwner {
rewardTokens.add(_token);
history[_token].push(genesis);
emit RewardTokenAdded(_msgSender(), _token);
}
/**
* @param _token reward token address
*/
function removeRewardToken(address _token) public override onlyOwner {
rewardTokens.remove(_token);
emit RewardTokenRemoved(_msgSender(), _token);
}
/**
* @param _pool reward pool address
*/
function addRewardPool(address _pool) public override onlyOwner {
rewardPools.add(_pool);
emit RewardPoolAdded(_msgSender(), _pool);
}
/**
* @param _pool reward pool address
*/
function removeRewardPool(address _pool) public override onlyOwner {
rewardPools.remove(_pool);
emit RewardPoolRemoved(_msgSender(), _pool);
}
/* ================= MODIFIERS ================= */
modifier checkMigration {
require(!migrated, 'Bondroom: migrated');
_;
}
modifier directorExists {
require(store.balanceOf(_msgSender()) > 0, 'Bondroom: absent');
_;
}
/**
* @param _director staker address
*/
modifier updateReward(address _director) {
collectReward();
for (uint256 i = 0; i < rewardTokens.length(); i++) {
address token = rewardTokens.at(i);
if (_director != address(0x0)) {
Boardseat memory seat = seats[token][_director];
seat.rewardEarned = rewardEarned(token, _director);
seat.lastSnapshotIndex = lastSnapshotIndex(token);
seats[token][_director] = seat;
}
}
_;
}
/* ================= CALLS - ANYONE ================= */
/**
* @return total staked amount
*/
function totalSupply() external view override returns (uint256) {
return store.totalSupply();
}
/**
* @param _owner staker address
* @return staker balance
*/
function balanceOf(address _owner)
external
view
override
returns (uint256)
{
return store.balanceOf(_owner);
}
/**
* @param _index of reward token
* @return reward token address
*/
function rewardTokensAt(uint256 _index)
external
view
override
returns (address)
{
return rewardTokens.at(_index);
}
/**
* @return total count of reward tokens
*/
function rewardTokensLength() external view override returns (uint256) {
return rewardTokens.length();
}
/**
* @param _index of reward pool
* @return reward pool address
*/
function rewardPoolsAt(uint256 _index)
external
view
override
returns (address)
{
return rewardPools.at(_index);
}
/**
* @return total count of reward pools
*/
function rewardPoolsLength() external view override returns (uint256) {
return rewardPools.length();
}
/**
* @param _token reward token address
* @return last snapshot index of token history
*/
function lastSnapshotIndex(address _token)
public
view
override
returns (uint256)
{
return history[_token].length.sub(1);
}
/**
* @param _token reward token address
* @return last snapshot of token history
*/
function getLastSnapshot(address _token)
internal
view
returns (BoardSnapshot memory)
{
return history[_token][lastSnapshotIndex(_token)];
}
/**
* @param _token reward token address
* @param _director staker address
* @return last snapshot of director
*/
function getLastSnapshotOf(address _token, address _director)
internal
view
returns (BoardSnapshot memory)
{
return history[_token][seats[_token][_director].lastSnapshotIndex];
}
/**
* @param _token reward token address
* @param _director staker address
* @return reward earned
*/
function rewardEarned(address _token, address _director)
public
view
override
returns (uint256)
{
uint256 latestRPS = getLastSnapshot(_token).rewardPerShare;
uint256 storedRPS = getLastSnapshotOf(_token, _director).rewardPerShare;
return
store
.balanceOf(_director)
.mul(latestRPS.sub(storedRPS))
.div(1e18)
.add(seats[_token][_director].rewardEarned);
}
/* ================= TXNS ================= */
/**
* @dev deposit tokens to bondroom
* @param _amount deposit amount of tokens
*/
function deposit(uint256 _amount)
public
override(IBondroom, TokenStoreWrapper)
checkMigration
updateReward(_msgSender())
{
super.deposit(_amount);
emit DepositShare(_msgSender(), _amount);
}
/**
* @dev withdraw tokens from bondroom
* @param _amount amount of staked tokens
*/
function withdraw(uint256 _amount)
public
override(IBondroom, TokenStoreWrapper)
directorExists
updateReward(_msgSender())
{
super.withdraw(_amount);
emit WithdrawShare(_msgSender(), _amount);
}
/**
* @dev receive collected rewards
*/
function claimReward() public override updateReward(_msgSender()) {
for (uint256 i = 0; i < rewardTokens.length(); i++) {
address token = rewardTokens.at(i);
uint256 reward = seats[token][_msgSender()].rewardEarned;
if (reward > 0) {
seats[token][_msgSender()].rewardEarned = 0;
IERC20(token).safeTransfer(_msgSender(), reward);
emit RewardClaimed(_msgSender(), token, reward);
}
}
}
/**
* @dev withdraw + claim reward
*/
function exit() external override {
withdraw(store.balanceOf(_msgSender()));
claimReward();
}
/**
* @dev collect rewards from pools
*/
function collectReward() public override {
if (store.totalSupply() > 0) {
for (uint256 i = 0; i < rewardPools.length(); i++) {
try IRewardPool(rewardPools.at(i)).collect() returns (
address token,
uint256 amount
) {
if (amount == 0) {
continue;
}
uint256 prevRPS = getLastSnapshot(token).rewardPerShare;
uint256 nextRPS =
prevRPS.add(amount.mul(1e18).div(store.totalSupply()));
BoardSnapshot memory newSnapshot =
BoardSnapshot({
at: block.number,
rewardReceived: amount,
rewardPerShare: nextRPS
});
history[token].push(newSnapshot);
emit RewardCollected(
_msgSender(),
rewardPools.at(i),
token,
amount
);
} catch Error(string memory reason) {
emit RewardCollectionFailedWithReason(
_msgSender(),
rewardPools.at(i),
reason
);
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// 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.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.7.0 <0.8.0;
import {Context} from '@openzeppelin/contracts/utils/Context.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import {ITokenStore} from './TokenStore.sol';
abstract contract TokenStoreWrapper is Context {
using SafeERC20 for IERC20;
IERC20 public share;
ITokenStore public store;
function deposit(uint256 _amount) public virtual {
share.safeTransferFrom(_msgSender(), address(this), _amount);
share.safeIncreaseAllowance(address(store), _amount);
store.deposit(_msgSender(), _amount);
}
function withdraw(uint256 _amount) public virtual {
store.withdraw(_msgSender(), _amount);
share.safeTransfer(_msgSender(), _amount);
}
}
// 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.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.7.0 <0.8.0;
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {SafeERC20} from '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import {Operator} from '../access/Operator.sol';
interface ITokenStore {
/* ================= EVENTS ================= */
event Deposit(
address indexed operator,
address indexed owner,
uint256 amount
);
event Withdraw(
address indexed operator,
address indexed owner,
uint256 amount
);
/* ================= CALLS ================= */
function token() external view returns (address);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
/* ================= TXNS ================= */
function deposit(address _owner, uint256 _amount) external;
function withdraw(address _owner, uint256 _amount) external;
function emergencyWithdraw() external;
}
interface ITokenStoreGov {
/* ================= EVENTS ================= */
event EmergencyReported(address indexed reporter);
event EmergencyResolved(address indexed resolver);
event TokenChanged(
address indexed owner,
address newToken,
address oldToken
);
/* ================= TXNS ================= */
function reportEmergency() external;
function resolveEmergency() external;
function setToken(address newToken) external;
}
contract TokenStore is ITokenStore, ITokenStoreGov, Operator {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ================= STATES ================= */
address public override token;
uint256 private _totalSupply;
mapping(address => uint256) private _balances;
bool public emergency = false;
constructor(address _token) Operator() {
token = _token;
}
/* ================= GOV - OWNER ONLY ================= */
/**
* @dev CAUTION: DO NOT USE IN NORMAL SITUATION
* @notice Enable emergency withdraw
*/
function reportEmergency() public override onlyOwner {
emergency = true;
emit EmergencyReported(_msgSender());
}
/**
* @dev CAUTION: DO NOT USE IN NORMAL SITUATION
* @notice Disable emergency withdraw
*/
function resolveEmergency() public override onlyOwner {
emergency = false;
emit EmergencyResolved(_msgSender());
}
/**
* @dev CAUTION: MUST USE 1:1 TOKEN MIGRATION
*/
function setToken(address newToken) public override onlyOwner {
address oldToken = token;
token = newToken;
IERC20(newToken).safeTransferFrom(
msg.sender,
address(this),
totalSupply()
);
emit TokenChanged(_msgSender(), newToken, oldToken);
}
/* ================= CALLS - ANYONE ================= */
/**
* @return total staked token amount
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @param _owner staker address
* @return staked amount of user
*/
function balanceOf(address _owner) public view override returns (uint256) {
return _balances[_owner];
}
/* ================= TXNS - OPERATOR ONLY ================= */
/**
* @param _owner stake address
* @param _amount stake amount
*/
function deposit(address _owner, uint256 _amount)
public
override
onlyOperator
{
_totalSupply = _totalSupply.add(_amount);
_balances[_owner] = _balances[_owner].add(_amount);
IERC20(token).safeTransferFrom(_msgSender(), address(this), _amount);
emit Deposit(_msgSender(), _owner, _amount);
}
/**
* @param _owner stake address
* @param _amount stake amount
*/
function withdraw(address _owner, uint256 _amount)
public
override
onlyOperator
{
_totalSupply = _totalSupply.sub(_amount);
_balances[_owner] = _balances[_owner].sub(_amount);
IERC20(token).safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _owner, _amount);
}
/**
* @notice Anyone can withdraw its balance even if is not the operator
*/
function emergencyWithdraw() public override {
require(emergency, 'TokenStore: not in emergency');
uint256 balance = _balances[_msgSender()];
_balances[_msgSender()] = 0;
IERC20(token).safeTransfer(_msgSender(), balance);
emit Withdraw(_msgSender(), _msgSender(), balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
import {Context, Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
abstract contract Operator is Context, Ownable {
address private _operator;
event OperatorTransferred(
address indexed previousOperator,
address indexed newOperator
);
constructor() {
_operator = _msgSender();
emit OperatorTransferred(address(0), _operator);
}
function operator() public view returns (address) {
return _operator;
}
modifier onlyOperator() {
require(
_operator == _msgSender(),
'operator: caller is not the operator'
);
_;
}
function isOperator() public view returns (bool) {
return _msgSender() == _operator;
}
function transferOperator(address newOperator_) public onlyOwner {
_transferOperator(newOperator_);
}
function _transferOperator(address newOperator_) internal {
require(
newOperator_ != address(0),
'operator: zero address given for new operator'
);
emit OperatorTransferred(address(0), newOperator_);
_operator = newOperator_;
}
}
|
withdraw tokens from bondroom _amount amount of staked tokens/
|
function withdraw(uint256 _amount)
public
override(IBondroom, TokenStoreWrapper)
directorExists
updateReward(_msgSender())
{
super.withdraw(_amount);
emit WithdrawShare(_msgSender(), _amount);
}
| 14,836,101
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
/* EXTERNAL DEPENDENCIES */
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
/* INTERNAL DEPENDENCIES */
import "./CommonStructs.sol";
import "./Instructions.sol";
import "./Deals.sol";
/// @title Proxy Contract
/// @dev Main DApp entry point. Exposes the public interface and decouple the data and the logic
/// @notice lets-make-a-deal.eth allows you to make an agreement between different parties and automatically route ETH to different addresses based on simple rules.
contract Proxy is Ownable, Pausable {
/* STORAGE VARIABLES */
/// @dev Chainlink ETH/USD price feed aggregator link on Rinkeby
AggregatorV3Interface public priceFeedRef;
/// @dev Last quotation value in USD per ETH with 8 decimals precision fetched from Chainlink
uint public lastQuotationValue;
/// @dev Last quotation timestamp fetched from Chainlink
uint public lastQuotationTimestamp;
// References to external contracts
/// @dev Reference to the Instructions contract
Instructions public instructionsContractRef;
/// @dev Reference to the InstructionsProvider contract
address public instructionsProviderContractRef;
/// @dev Reference to the Deals instance
Deals public dealsContractRef;
/// @dev Reference to the Interpreter contract
address public interpreterContractRef;
// Contract fees
/// @dev Price per account added to the deal in USD
uint public accountCreationFees;
/// @dev Price per rule added to the deal in USD
uint public ruleCreationFees;
/// @dev Price to allow incoming payments from all addresses others than internal/external accounts in USD
uint public allowAllAddressesFees;
/// @dev Minimal transaction value able to trigger an execution in USDimport "@openzeppelin/contracts/security/Pausable.sol";
uint public transactionMinimalValue;
/// @dev Transaction fees in % of the msg.value perceived on a deal execution in USD
uint public transactionFees;
/* MAPPINGS */
/* MODIFIERS */
/* EVENTS */
// Modify Chainlink ETH/USD price feed aggregator address
/**
* @dev Event emitted when the Chainlink ETH/USD price feed aggregator address is changed
* @param _from Caller address
* @param _old Old address of the Chainlink ETH/USD price feed aggregator address
* @param _new New address of the Chainlink ETH/USD price feed aggregator address
*/
event ModifyPriceFeedRefAggregatorAddress(address _from, address _old, address _new);
// Modify contract references
/**
* @dev Event emitted when the Instructions contract reference is changed
* @param _from Caller address
* @param _old Old address of the Instructions contract
* @param _new New address of the Instructions contract
*/
event ModifyInstructionsContractAddress(address _from, address _old, address _new);
/**
* @dev Event emitted when the InstructionsProvider contract reference is changed
* @param _from Caller address
* @param _old Old address of the InstructionsProvider contract
* @param _new New address of the InstructionsProvider contract
*/
event ModifyInstructionsProviderContractAddress(address _from, address _old, address _new);
/**
* @dev Event emitted when the Deals contract reference is changed
* @param _from Caller address
* @param _old Old address of the Deals contract
* @param _new New address of the Deals contract
*/
event ModifyDealsContractAddress(address _from, address _old, address _new);
/**
* @dev Event emitted when the Interpreter contract reference is changed
* @param _from Caller address
* @param _old Old address of the Interpreter contract
* @param _new New address of the Interpreter contract
*/
event ModifyInterpreterContractAddress(address _from, address _old, address _new);
// Modify fees
/**
* @dev Event emitted when the account creation fees is changed
* @param _from : msg.sender
* @param _old : old account creation fees in USD
* @param _new : new account creation fees in USD
*/
event ModifyAccountCreationFees(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the rule creation fees is changed
* @param _from : msg.sender
* @param _old : old rule creation fees in USD
* @param _new : new rule creation fees in USD
*/
event ModifyRuleCreationFees(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the allow all accounts fees is changed
* @param _from : msg.sender
* @param _old : old allow all accounts fees in USD
* @param _new : new allow all accounts fees in USD
*/
event ModifyAllowAllAccountsFees(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the transaction minimal value is changed
* @param _from : msg.sender
* @param _old : old transaction minimal value in USD
* @param _new : new transaction minimal value in USD
*/
event ModifyTransactionMinimalValue(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the transaction fees are changed
* @param _from : msg.sender
* @param _old : old transaction fees value in % of msg.value
* @param _new : new transaction fees value in % of msg.value
*/
event ModifyTransactionFees(address _from, uint _old, uint _new);
/**
* @dev Event emitted when the WEI to USD conversion rate is updated from Chainlink
* @param _from : msg.sender
* @param _value : WEI/USD price at the time the Chainlink Oracle was called
* @param _timestamp : timestamp at which the price was fetched from Chainlink
*/
event QueryLastQuotationFromChainlink(address _from, uint _value, uint _timestamp);
/**
* @dev Event emitted when the deal creation fees are paid
* @param _from : msg.sender
* @param _dealId : Id of the created deal
* @param _fees : Fees paid by the user in ETH
*/
event PayDealCreationFees(address _from, uint _dealId, uint _fees);
/**
* @dev Event emitted when the transaction fees are paid
* @param _from : msg.sender
* @param _dealId : Id of the executed deal
* @param _ruleId : Id of the executed rule
* @param _fees : Fees paid by the user in ETH
*/
event PayTransactionFees(address _from, uint _dealId, uint _ruleId, uint _fees);
/**
* @dev Event emitted when an excess value is reimbursed to the user
* @param _to : address of the caller (msg.sender) where the excess value is reimbursed
* @param _dealId : Id of the created deal
* @param _amount : Amount reimbursed to the user in ETH
*/
event ReimburseExcessValue(address _to, uint _dealId, uint _amount);
/* CONSTRUCTOR */
/**
* @dev Constructor: Initialize storage variables
* @param _accountCreationFees Creation fees per account in Wei
* @param _ruleCreationFees Creation fees per rule in Wei
* @param _allowAllAddressesFees Creation fees to allow incoming payments from all addresses
* @param _transactionMinimalValue Minimal value to trigger a rule execution
* @param _transactionFees Transaction fees paid to execute a rule in % of msg.value (1=1%)
* @param _lastQuotationValue Wei per USD conversion rate
*/
constructor (
uint _accountCreationFees,
uint _ruleCreationFees,
uint _allowAllAddressesFees,
uint _transactionMinimalValue,
uint _transactionFees,
uint _lastQuotationValue
) {
accountCreationFees = _accountCreationFees;
ruleCreationFees = _ruleCreationFees;
allowAllAddressesFees = _allowAllAddressesFees;
transactionMinimalValue = _transactionMinimalValue;
transactionFees = _transactionFees;
lastQuotationValue = _lastQuotationValue;
}
/* SEND & FALLBACK */
// No payable send or fallback function includes so that the contract will return any ETH send with a call without call values
// https://docs.soliditylang.org/en/v0.8.9/contracts.html#receive-ether-function
/* OWNER INTERFACE */
// Address to Chainlink ETH/USD price feed aggregator
/**
* @dev Set the address to the Chainlink ETH/USD price feed aggregator
* @param _new New address to the Chainlink ETH/USD price feed aggregator
*/
function setPriceFeedRefAggregatorAddress(address _new) public onlyOwner {
address old = address(priceFeedRef);
priceFeedRef = AggregatorV3Interface(_new);
emit ModifyPriceFeedRefAggregatorAddress(msg.sender, old, _new);
}
// References to external contracts
/**
* @dev Sets the Instructions contract reference to a new value
* @param _new New address of the Instructions contract
*/
function setInstructionsContractRef(address _new) public onlyOwner whenPaused {
address old = address(instructionsContractRef);
instructionsContractRef = Instructions(_new);
emit ModifyInstructionsContractAddress(msg.sender, old, _new);
}
/**
* @dev Sets the InstructionsProvider contract reference to a new value
* @param _new New address of the InstructionsProvider contract
*/
function setInstructionsProviderContractRef(address _new) public onlyOwner whenPaused {
address old = instructionsProviderContractRef;
instructionsProviderContractRef = _new;
emit ModifyInstructionsProviderContractAddress(msg.sender, old, _new);
}
/**
* @dev Sets the Deals contract reference to a new value
* @param _new New address of the Deals contract
*/
function setDealsContractRef(address _new) public onlyOwner whenPaused {
address old = address(dealsContractRef);
dealsContractRef = Deals(_new);
emit ModifyDealsContractAddress(msg.sender, old, _new);
}
/**
* @dev Sets the Interpreter contract reference to a new value
* @param _new New address of the Interpreter contract
*/
function setInterpreterContractRef(address _new) public onlyOwner whenPaused {
address old = interpreterContractRef;
interpreterContractRef = _new;
emit ModifyInterpreterContractAddress(msg.sender, old, _new);
}
// Contract fees
/**
* @dev Sets the account creation fees to a new value
* @param _new New value for the account creation fees in USD
*/
function setAccountCreationFees(uint _new) public onlyOwner whenPaused {
uint old = accountCreationFees;
accountCreationFees = _new;
emit ModifyAccountCreationFees(msg.sender, old, _new);
}
/**
* @dev Sets the rule creation fees to a new value
* @param _new New value for the rule creation fees in USD
*/
function setRuleCreationFees(uint _new) public onlyOwner whenPaused {
uint old = ruleCreationFees;
ruleCreationFees = _new;
emit ModifyRuleCreationFees(msg.sender, old, _new);
}
/**
* @dev Sets the allow all addresses fees to a new value
* @param _new New value for the allow all addresses fees in USD
*/
function setAllowAllAddressesFees(uint _new) public onlyOwner whenPaused {
uint old = allowAllAddressesFees;
allowAllAddressesFees = _new;
emit ModifyAllowAllAccountsFees(msg.sender, old, _new);
}
/**
* @dev Sets the transaction minimal value to a new value
* @param _new New value for the transaction minimal value in USD
*/
function setTransactionMinimalValue(uint _new) public onlyOwner whenPaused {
uint old = transactionMinimalValue;
transactionMinimalValue = _new;
emit ModifyTransactionMinimalValue(msg.sender, old, _new);
}
/**
* @dev Sets the transaction fees to a new value
* @param _new New value for the transaction fees in % of msg.value
*/
function setTransactionFees(uint _new) public onlyOwner whenPaused {
uint old = transactionFees;
transactionFees = _new;
emit ModifyTransactionFees(msg.sender, old, _new);
}
/* PUBLIC INTERFACE */
/**
* @dev Creates a deal and returns its id
* @param _accounts List of accounts addresses linked to the deal
* @param _rulesList List of the rules linked to the deal (rule = list of Articles)
* @return Id of the deal created
*/
function createDeal
(
address[] memory _accounts,
CommonStructs.Article[][] memory _rulesList
)
external
payable
whenNotPaused
returns (uint) {
// Compute creation fees in WEI
uint creationFeesInWEI = computeDealCreationFeesInWEI(_accounts.length, _rulesList.length);
// Check 1: Amount sent by the user should cover the deal creation fees
require(msg.value >= creationFeesInWEI, "Insufficient value to cover the deal creation fees");
// Check 2: Make sure that the instructions are all supported
for (uint i=0;i<_rulesList.length;i++) {
for (uint j=0;j<_rulesList[i].length;j++) {
// Get the instruction type & signature
(, string memory instructionSignature) = instructionsContractRef.getInstruction(_rulesList[i][j].instructionName);
// If the signature is empty, this means that the instruction is not present => revert
require(!stringsEqual(instructionSignature,''),"Proxy.CreateDeal: Instruction is not supported");
}
}
// Create the deal
uint dealId = dealsContractRef.createDeal(_accounts, _rulesList);
// Reimburse excess value to the caller if necessary
uint excessValue = (msg.value - creationFeesInWEI);
if (excessValue > 0){
(bool sent, ) = msg.sender.call{value: excessValue } ("");
require(sent, "Proxy.createDeal: Failed to reimburse excess ETH");
emit ReimburseExcessValue(msg.sender, dealId, excessValue);
}
// Emit a PayDealCreationFees
emit PayDealCreationFees(msg.sender, dealId, creationFeesInWEI);
return dealId;
}
/**
* @dev Execute a deal's rule
* @param _dealId : Id of the deal to execute
* @param _ruleId : Id of the rule to execute
*/
function executeRule(uint _dealId, uint _ruleId) external payable whenNotPaused {
// Amount sent by the user should be higher or equal to the minimal transaction value
uint msgValueInUSD = convertWEI2USD(msg.value);
require( msgValueInUSD >= transactionMinimalValue, "Transaction minimal value not reached");
// Upgrability: Low level call to InstructionsProvider
// Includes in the call (msg.value - execution fees)
uint executionFees = (msg.value / 100) * transactionFees;
(bool success, ) = interpreterContractRef.call{value: (msg.value - executionFees)}(
abi.encodeWithSignature(
"interpretRule(address,uint256,uint256)",
msg.sender,
_dealId,
_ruleId
)
);
// Did the low level call succeed?
require(success,"Proxy: Unable to execute rule");
// Emit a PayTransactionFees
emit PayTransactionFees(msg.sender, _dealId, _ruleId, executionFees);
}
/**
* @dev Withdraw all deposit from escrow for msg.sender
*/
function withdraw() external whenNotPaused {
(bool success,) = instructionsProviderContractRef.call(
abi.encodeWithSignature(
"withdraw(address)",
msg.sender
)
);
require(success,"Proxy: Unable to get withdraw deposits of caller from Escrow!");
}
/**
* @dev Get the internal balance of the contract
* @return The internal balance of the contract in Wei
*/
function getContractBalance() public view onlyOwner returns(uint) {
return address(this).balance;
}
/**
* @dev Owner can withdraw ETH from the contract balance
*/
function harvest() external payable onlyOwner {
// Sends contract ETH balance to owner if balance > 0
uint balance = address(this).balance;
if (balance>0)
payable(msg.sender).transfer(balance);
}
/* CHAINLINK ETH/USD PRICE FEED AGGREGATOR */
/**
* @dev Query & save the latest quotation from ChainLink price feed aggregator on Rinkeby
*/
function saveLatestQuotation() public onlyOwner {
// Query last ETH/USD price from ChainLink
(, int price, , uint timestamp, ) = priceFeedRef.latestRoundData();
// Save latest quotation (rounID, price & timestamp)
lastQuotationValue = (10**18)*(10**8)/uint(price);
lastQuotationTimestamp = timestamp;
emit QueryLastQuotationFromChainlink(msg.sender, lastQuotationValue, timestamp);
}
/**
* @dev Return the last quotation from Chainlink
* @return Last quotation from Chainlink in WEI per USD
* along with the query timestamp
*/
function getLatestQuotation() public view returns(uint, uint) {
return (lastQuotationValue, lastQuotationTimestamp);
}
/* HELPER FUNCTIONS */
/**
* @dev Computes the deal creation cost in WEI
* @param _accountsCount Number of external accounts defined in the deal
* @param _rulesCount Number of rules defined in the deal
* @return Deal creation cost in WEI
*/
function computeDealCreationFeesInWEI
(
uint _accountsCount,
uint _rulesCount
)
public view returns (uint) {
return (_accountsCount * accountCreationFees + _rulesCount * ruleCreationFees)*lastQuotationValue;
}
/**
* @dev Converts an amount in WEI to USD
* @param _amountInWEI Amount in WEI
* @return Converted amount in USD
*/
function convertWEI2USD(uint _amountInWEI) public view returns(uint) {
return _amountInWEI / lastQuotationValue;
}
/**
* @dev Converts an amount in USD to WEI
* @param _amountInUSD Amount in USD
* @return Converted amount in WEI
*/
function convertUSD2WEI(uint _amountInUSD) public view returns(uint) {
return _amountInUSD * lastQuotationValue;
}
/**
* @dev Checks whether the strings are equal
* @param _s1 First string to compare
* @param _s2 Second string to compare
* @return Boolean indicating if the 2 strings are equal
*/
function stringsEqual(string memory _s1, string memory _s2) public pure returns(bool) {
return keccak256(bytes(_s1)) == keccak256(bytes(_s2));
}
/* OpenZeppelin.Pausable */
/**
* @dev Access control inherited from OpenZeppelin Ownable contract
* Pausing the contract makes the createDeal function not callable
* Getters are still callable
* Only owner can call
*/
function pause() public onlyOwner() whenNotPaused() {
_pause();
}
/**
* @dev Access control inherited from OpenZeppelin Ownable contract
* Unpausing the contract makes the createDeal function callable
* Only Owner can call
*/
function unpause() public onlyOwner() whenPaused() {
_unpause();
}
/* OVERRIDE & BLOCK UNUSED INHERITED FUNCTIONS */
/**
* @dev Block OpenZeppelin Ownable.renounceOwnership
* @notice Will always revert
*/
function renounceOwnership() public pure override {
revert('Contract cannot be revoked');
}
}
|
Access control inherited from OpenZeppelin Ownable contract Unpausing the contract makes the createDeal function callable Only Owner can call/
|
function unpause() public onlyOwner() whenPaused() {
_unpause();
}
| 5,396,921
|
pragma solidity 0.6.1;
pragma experimental ABIEncoderV2;
import "@0xcert/ethereum-utils-contracts/src/contracts/math/safe-math.sol";
import "@0xcert/ethereum-utils-contracts/src/contracts/utils/supports-interface.sol";
import "@0xcert/ethereum-utils-contracts/src/contracts/permission/abilitable.sol";
import "./migration-receiver.sol";
import "./erc20.sol";
/**
* @title This is an ERC-20 token that is bartered against another ERC-20 token. This means that
* supply can only increase when the bartered token is deposited into this smart contract. Bartered
* token can also be withdrawn at any moment. At that point the supply will decrease. This smart
* contract also limits to whom tokens can be sent and adds functionality to migrate to a newer
* version of the smart contract (this transfers bartered token from this smart contract to the
* new one) as well and approving tokens with signature.
* @dev This interface uses the official ERC-20 specification from
* https://eips.ethereum.org/EIPS/eip-20 and also implements every optional function.
*/
contract DappToken is
ERC20,
SupportsInterface,
Abilitable,
MigrationReceiver
{
using SafeMath for uint256;
/**
* @dev List of abilities:
*/
uint8 constant ABILITY_SET_WHITELISTED = 16;
uint8 constant ABILITY_SET_MIGRATE_ADDRESS = 32;
uint8 constant ABILITY_SET_MIGRATOR_ADDRESS = 64;
/**
* @dev Error constants.
*/
string constant NOT_ENOUGH_BALANCE = "010001";
string constant NOT_ENOUGH_ALLOWANCE = "010002";
string constant NOT_WHITELISTED_ADDRESS = "010003";
string constant MIGRATION_NOT_STARTED = "010004";
string constant MIGRATION_STARTED = "010005";
string constant NOT_ABLE_TO_MIGRATE = "010006";
string constant INVALID_SIGNATURE = "010007";
string constant CLAIM_PERFORMED = "010008";
string constant CLAIM_EXPIRED = "010009";
string constant INVALID_SIGNATURE_KIND = "010010";
string constant CLAIM_CANCELED = "010011";
/**
* @dev Token name.
*/
string internal tokenName;
/**
* @dev Token symbol.
*/
string internal tokenSymbol;
/**
* @dev Number of decimals.
*/
uint8 internal tokenDecimals;
/**
* @dev Total supply of tokens.
*/
uint256 internal tokenTotalSupply;
/**
* @dev Balance information map.
*/
mapping (address => uint256) internal balances;
/**
* @dev Token allowance mapping.
*/
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Token transfer proxy contract address.
*/
address public tokenTransferProxy;
/**
* @dev Addresses to which dapp tokens can be transferred.
*/
mapping (address => bool) public whitelistedRecipients;
/**
* @dev Bartered token address. ERC-20 token that when deposited to this contract will create new
* tokens in this contract. Dapp token is pegged 1 on 1 to the bartered token. Bartered token can
* be withdrawn at any point.
*/
ERC20 public barteredToken;
/**
* @dev Address to which we can migrate to. Bartered tokens are sent to this address.
*/
address public migrationAddress;
/**
* @dev Dapp token addresses from which tokens can be migrated to the new dapp tokens. Bartered
* tokens are transfered to the new dapp token address in the process.
*/
mapping (address => bool) public approvedMigrators;
/**
* @dev Magic value of a smart contract that can be migrated to.
* Equal to: bytes4(keccak256("onMigrationReceived(address,uint256)")).
*/
bytes4 constant MAGIC_ON_MIGRATION_RECEIVED = 0xc5b97e06;
/**
* @dev Enum of available signature kinds.
* @param eth_sign Signature using eth sign.
* @param trezor Signature from Trezor hardware wallet.
* It differs from web3.eth_sign in the encoding of message length
* (Bitcoin varint encoding vs ascii-decimal, the latter is not
* self-terminating which leads to ambiguities).
* See also:
* https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer
* https://github.com/trezor/trezor-mcu/blob/master/firmware/ethereum.c#L602
* https://github.com/trezor/trezor-mcu/blob/master/firmware/crypto.c#L36a
* @param no_prefix Signatures that do not need a prefix.
*/
enum SignatureKind
{
eth_sign,
trezor,
no_prefix
}
/**
* @dev Structure representing the signature parts.
* @param r ECDSA signature parameter r.
* @param s ECDSA signature parameter s.
* @param v ECDSA signature parameter v.
* @param kind Type of signature.
*/
struct SignatureData
{
bytes32 r;
bytes32 s;
uint8 v;
SignatureKind kind;
}
/**
* @dev Mapping of all performed claims.
*/
mapping(bytes32 => bool) public claimPerformed;
/**
* @dev Mapping of all canceled claims.
*/
mapping(bytes32 => bool) public claimCancelled;
/**
* @dev Trigger when tokens are transferred, including zero value transfers.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
/**
* @dev Trigger on any successful call to approve(address _spender, uint256 _value).
*/
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/**
* @dev Trigger of any change of a whitelisted recipient.
*/
event WhitelistedRecipient(
address indexed _target,
bool state
);
/**
* @dev Trigger of any change of a approved migrator.
*/
event ApprovedMigrator(
address indexed _target,
bool state
);
/**
* @dev Contract constructor.
*/
constructor()
public
{
supportedInterfaces[0x36372b07] = true; // ERC20
supportedInterfaces[0x06fdde03] = true; // ERC20 name
supportedInterfaces[0x95d89b41] = true; // ERC20 symbol
supportedInterfaces[0x313ce567] = true; // ERC20 decimals
}
/**
* @dev Returns the name of the token.
*/
function name()
external
override
view
returns (string memory _name)
{
_name = tokenName;
}
/**
* @dev Returns the symbol of the token.
*/
function symbol()
external
override
view
returns (string memory _symbol)
{
_symbol = tokenSymbol;
}
/**
* @dev Returns the number of decimals the token uses.
*/
function decimals()
external
override
view
returns (uint8 _decimals)
{
_decimals = tokenDecimals;
}
/**
* @dev Returns the total token supply.
*/
function totalSupply()
external
override
view
returns (uint256 _totalSupply)
{
_totalSupply = tokenTotalSupply;
}
/**
* @dev Returns the account balance of another account with address _owner.
* @param _owner The address from which the balance will be retrieved.
*/
function balanceOf(
address _owner
)
external
override
view
returns (uint256 _balance)
{
_balance = balances[_owner];
}
/**
* @dev Returns the amount which _spender is still allowed to withdraw from _owner.
* @param _owner The address of the account owning tokens.
* @param _spender The address of the account able to transfer the tokens.
*/
function allowance(
address _owner,
address _spender
)
external
override
view
returns (uint256 _remaining)
{
_remaining = allowed[_owner][_spender];
}
/**
* @dev Sets whitelist state to an address
* @param _target Address we are setting the whitelist state.
* @param _state State we are setting. True means the address is whitelisted while false the
* opposite.
*/
function setWhitelistedRecipient(
address _target,
bool _state
)
external
hasAbilities(ABILITY_SET_WHITELISTED)
{
whitelistedRecipients[_target] = _state;
emit WhitelistedRecipient(_target, _state);
}
/**
* @dev Sets migration caller state to an address.
* @param _target Address we are setting the migration caller state.
* @param _state State we are setting. True means the address is a migration caller while false
* the opposite.
*/
function setApprovedMigrator(
address _target,
bool _state
)
external
hasAbilities(ABILITY_SET_MIGRATOR_ADDRESS)
{
approvedMigrators[_target] = _state;
emit ApprovedMigrator(_target, _state);
}
/**
* @dev Sets address to which migration is done.
* @param _target Targeted address.
*/
function startMigration(
address _target
)
external
hasAbilities(ABILITY_SET_MIGRATE_ADDRESS)
{
require(_target != address(0), MIGRATION_NOT_STARTED);
migrationAddress = _target;
}
/**
* @dev Migrate to a new Dapp token smart contract. Senders bartered tokens get transferred to the
* new Dapp token where tokens in the same amount get created. Tokens on this smart contract get
* destroyed.
*/
function migrate()
external
{
require(migrationAddress != address(0), MIGRATION_NOT_STARTED);
uint256 balance = balances[msg.sender];
balances[msg.sender] = 0;
tokenTotalSupply = tokenTotalSupply.sub(balance);
barteredToken.transfer(migrationAddress, balance);
require(
MigrationReceiver(migrationAddress)
.onMigrationReceived(msg.sender, balance) == MAGIC_ON_MIGRATION_RECEIVED,
NOT_ABLE_TO_MIGRATE
);
emit Transfer(msg.sender, address(0), balance);
}
/**
* @dev Handles the receipt of a migration. The dapp token calls this function on the migration
* address when migrating. Return of other than the magic value MUST result in the transaction
* being reverted. Returns `bytes4(keccak256("onMigrationReceived(address,uint256)"))` unless
* throwing. This method registers receiving bartered tokens and creates new tokens for the
* migrator.
* @param _migrator The address which called `migrate` function.
* @param _amount Amount of tokens being migrated.
* @return Returns `bytes4(keccak256("onMigrationReceived(address,uint256)"))`.
*/
function onMigrationReceived(
address _migrator,
uint256 _amount
)
external
override
returns(bytes4)
{
require(approvedMigrators[msg.sender], NOT_ABLE_TO_MIGRATE);
tokenTotalSupply = tokenTotalSupply.add(_amount);
balances[_migrator] = balances[_migrator].add(_amount);
allowed[_migrator][tokenTransferProxy] = allowed[_migrator][tokenTransferProxy].add(_amount);
emit Approval(_migrator, tokenTransferProxy, allowed[_migrator][tokenTransferProxy]);
emit Transfer(address(0), _migrator, _amount);
return MAGIC_ON_MIGRATION_RECEIVED;
}
/**
* @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event. The
* function SHOULD throw if the message caller's account balance does not have enough tokens to
* spend.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transfer(
address _to,
uint256 _value
)
public
override
returns (bool _success)
{
require(migrationAddress == address(0), MIGRATION_STARTED);
require(whitelistedRecipients[_to], NOT_WHITELISTED_ADDRESS);
require(_value <= balances[msg.sender], NOT_ENOUGH_BALANCE);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
_success = true;
}
/**
* @dev Allows _spender to withdraw from your account multiple times, up to the _value amount. If
* this function is called again it overwrites the current allowance with _value.
* @notice To prevent attack vectors like the one described here:
* https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit and
* discussed here: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729, clients
* SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0
* before setting it to another value for the same spender. THOUGH The contract itself shouldn’t
* enforce it, to allow backwards compatibility with contracts deployed before.
* @param _spender The address of the account able to transfer the tokens.
* @param _value The amount of tokens to be approved for transfer.
*/
function approve(
address _spender,
uint256 _value
)
public
override
returns (bool _success)
{
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
_success = true;
}
/**
* @dev Allows _spender to withdraw from your account multiple times, up to the _value amount. If
* this function is called again it overwrites the current allowance with _value.
* @notice To prevent attack vectors like the one described here:
* https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/edit and
* discussed here: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729, clients
* SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0
* before setting it to another value for the same spender. THOUGH The contract itself shouldn’t
* enforce it, to allow backwards compatibility with contracts deployed before.
* @param _approver Approving address from which the spender will be able to transfer tokens.
* @param _spender The address of the account able to transfer the tokens.
* @param _value The amount of tokens to be approved for transfer.
* @param _feeRecipient Address of the fee recipient. If set to zero address the msg.sender will
* automatically become the fee recipient.
* @param _feeValue The amount of token then will be tranfered to the executor of this method.
* @param _seed Arbitrary number to facilitate uniqueness of the order's hash. Usually timestamp.
* @param _expiration Timestamp of when the claim expires.
* @param _signature Data from the signature.
*/
function approveWithSignature(
address _approver,
address _spender,
uint256 _value,
address _feeRecipient,
uint256 _feeValue,
uint256 _seed,
uint256 _expiration,
SignatureData memory _signature
)
public
{
bytes32 claim = generateClaim(
_approver,
_spender,
_value,
_feeRecipient,
_feeValue,
_seed,
_expiration
);
require(!claimCancelled[claim], CLAIM_CANCELED);
require(!claimPerformed[claim], CLAIM_PERFORMED);
require(
isValidSignature(
_approver,
claim,
_signature
),
INVALID_SIGNATURE
);
require(_expiration > now, CLAIM_EXPIRED);
claimPerformed[claim] = true;
allowed[_approver][_spender] = _value;
emit Approval(_approver, _spender, _value);
require(_feeValue <= balances[_approver], NOT_ENOUGH_BALANCE);
balances[_approver] = balances[_approver].sub(_feeValue);
if (_feeRecipient == address(0)) {
_feeRecipient = msg.sender;
}
balances[_feeRecipient] = balances[_feeRecipient].add(_feeValue);
emit Transfer(_approver, _feeRecipient, _feeValue);
}
/**
* @dev Cancels approveWithSignature claim.
* @notice This works even if sender doesn't own any tokens at the time.
* @param _spender The address of the account able to transfer the tokens.
* @param _value The amount of tokens to be approved for transfer.
* @param _feeRecipient Address of the fee recipient. If set to zero address the msg.sender will
* automatically become the fee recipient.
* @param _feeValue The amount of token then will be tranfered to the executor of this method.
* @param _seed Arbitrary number to facilitate uniqueness of the order's hash. Usually timestamp.
* @param _expiration Timestamp of when the claim expires.
*/
function cancelApproveWithSignature(
address _spender,
uint256 _value,
address _feeRecipient,
uint256 _feeValue,
uint256 _seed,
uint256 _expiration
)
external
{
bytes32 claim = generateClaim(
msg.sender,
_spender,
_value,
_feeRecipient,
_feeValue,
_seed,
_expiration
);
require(!claimPerformed[claim], CLAIM_PERFORMED);
claimCancelled[claim] = true;
}
/**
* @dev Generates hash representing the approve definition.
* @param _approver Approving address from which the spender will be able to transfer tokens.
* @param _spender The address of the account able to transfer the tokens.
* @param _value The amount of tokens to be approved for transfer.
* @param _feeRecipient Address of the fee recipient. If set to zero address the msg.sender will
* automatically become the fee recipient.
* @param _feeValue The amount of token then will be tranfered to the executor of this method.
* @param _seed Arbitrary number to facilitate uniqueness of the order's hash. Usually timestamp.
* @param _expiration Timestamp of when the claim expires.
*/
function generateClaim(
address _approver,
address _spender,
uint256 _value,
address _feeRecipient,
uint256 _feeValue,
uint256 _seed,
uint256 _expiration
)
public
view
returns (bytes32 _claim)
{
_claim = keccak256(
abi.encodePacked(
address(this),
_approver,
_spender,
_value,
_feeRecipient,
_feeValue,
_seed,
_expiration
)
);
}
/**
* @dev Verifies if claim signature is valid.
* @param _signer address of signer.
* @param _claim Signed Keccak-256 hash.
* @param _signature Signature data.
*/
function isValidSignature(
address _signer,
bytes32 _claim,
SignatureData memory _signature
)
public
pure
returns (bool)
{
if (_signature.kind == SignatureKind.eth_sign)
{
return _signer == ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
_claim
)
),
_signature.v,
_signature.r,
_signature.s
);
} else if (_signature.kind == SignatureKind.trezor)
{
return _signer == ecrecover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n\x20",
_claim
)
),
_signature.v,
_signature.r,
_signature.s
);
} else if (_signature.kind == SignatureKind.no_prefix)
{
return _signer == ecrecover(
_claim,
_signature.v,
_signature.r,
_signature.s
);
}
revert(INVALID_SIGNATURE_KIND);
}
/**
* @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the
* Transfer event.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount of token to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
override
returns (bool _success)
{
require(migrationAddress == address(0), MIGRATION_STARTED);
require(whitelistedRecipients[_to], NOT_WHITELISTED_ADDRESS);
require(_value <= balances[_from], NOT_ENOUGH_BALANCE);
require(_value <= allowed[_from][msg.sender], NOT_ENOUGH_ALLOWANCE);
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);
_success = true;
}
/**
* @dev Deposit bartered token into the contract. Calling this function will transfer bartered
* token into the dapp token and create the same amount of dapp tokens to the caller.
* This auto approves TokenTransferProxy contract.
* @param _value Amount of bartered token we are depositing.
* @param _receiver Receiver of dapp tokens.
*/
function deposit(
uint256 _value,
address _receiver
)
public
{
require(migrationAddress == address(0), MIGRATION_STARTED);
tokenTotalSupply = tokenTotalSupply.add(_value);
balances[_receiver] = balances[_receiver].add(_value);
barteredToken.transferFrom(msg.sender, address(this), _value);
allowed[_receiver][tokenTransferProxy] = allowed[_receiver][tokenTransferProxy].add(_value);
emit Transfer(address(0), _receiver, _value);
emit Approval(_receiver, tokenTransferProxy, allowed[_receiver][tokenTransferProxy]);
}
/**
* @dev Withdraw bartered token from the contract. Calling this function will destroy dapp tokens
* and transfer the bartered token back to the caller.
* @param _value The amount of bartered token we are withdrawing.
*/
function withdraw(
uint256 _value
)
public
{
require(_value <= balances[msg.sender], NOT_ENOUGH_BALANCE);
tokenTotalSupply = tokenTotalSupply.sub(_value);
balances[msg.sender] = balances[msg.sender].sub(_value);
barteredToken.transfer(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
}
|
Allows _spender to withdraw from your account multiple times, up to the _value amount. If this function is called again it overwrites the current allowance with _value. To prevent attack vectors like the one described here: SHOULD make sure to create user interfaces in such a way that they set the allowance first to 0 before setting it to another value for the same spender. THOUGH The contract itself shouldn’t enforce it, to allow backwards compatibility with contracts deployed before. _spender The address of the account able to transfer the tokens. _value The amount of tokens to be approved for transfer./
|
function approve(
address _spender,
uint256 _value
)
public
override
returns (bool _success)
{
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
_success = true;
}
| 1,754,453
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "./OptFiPool.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/**
* @title Implementation of the Pool Factory
* @author s4p40-d3fi
* @dev This contract implements a factory for liquidity pools backed by ERC20 tokens
*/
contract OptFiPoolFactory is Ownable, ReentrancyGuard{
OptFiPool private _poolImplementation;
mapping(IERC20 => OptFiPool) private _pools;
constructor()
{
_poolImplementation = new OptFiPool();
_poolImplementation.initializeImplementation();
}
/**
* @dev Gets existing pool contract for the parameters provided.
* @param token The contract address of the ERC20 token this pool provides liquidity for
* @return The pool contract
*/
function getPool(IERC20Metadata token) external view returns (OptFiPool) {
return _pools[token];
}
/**
* @dev Creates a new liquidity pool.
* @param token The contract address of the ERC20 token this pool provides liquidity for
* @return The pool contract
*/
function createPool(IERC20Metadata token, address poolOwner) external onlyOwner nonReentrant returns (OptFiPool) {
/*
* Clones and initializes contract
*/
require(address(_pools[token]) == address(0), "There is already a pool created for the token provided");
_pools[token] = OptFiPool(Clones.clone(address(_poolImplementation)));
OptFiPoolToken shareToken = _createShareToken(token.symbol());
shareToken.transferOwnership(address(_pools[token]));
OptFiPoolToken withdrawToken = _createWithdrawToken(token.symbol());
withdrawToken.transferOwnership(address(_pools[token]));
_pools[token].initialize(token, poolOwner, shareToken, withdrawToken);
emit PoolCreated(_pools[token], shareToken, withdrawToken);
return _pools[token];
}
/**
* @dev Function used by the pool factory to create pool share tokens
*
* Pool share tokens are extended ERC20 contracts that implement tradeable flag allowing for transfer of the tokens
* Share tokens are created as tradeable what means they can be transferred as any ERC20 token using transfer/transferFrom
**/
function _createShareToken(string memory tokenSymbol) private returns (OptFiPoolToken){
return new OptFiPoolToken(string(abi.encodePacked('OptFI ', tokenSymbol, ' pool share')), string(abi.encodePacked("PST-",tokenSymbol)), true);
}
/**
* @dev Function used by the pool factory to create pool withdraw tokens
*
* Pool withdraw tokens are extended ERC20 contracts that implement tradeable flag allowing for transfer of the tokens
* Withdraw tokens are created as NOT tradeable what means they can NOT be transferred as any ERC20 token using transfer/transferFrom
**/
function _createWithdrawToken(string memory tokenSymbol) private returns (OptFiPoolToken){
return new OptFiPoolToken(string(abi.encodePacked('OptFI ', tokenSymbol, ' pool withdraw')), string(abi.encodePacked("PWT-",tokenSymbol)), false);
}
/**
* @dev Emitted when a pool contract is created.
* @param pool The pool contract created.
*/
event PoolCreated(OptFiPool pool, OptFiPoolToken shareToken, OptFiPoolToken withdrawToken);
fallback() external {}
}
|
Function used by the pool factory to create pool share tokens Pool share tokens are extended ERC20 contracts that implement tradeable flag allowing for transfer of the tokens Share tokens are created as tradeable what means they can be transferred as any ERC20 token using transfer/transferFrom/
|
function _createShareToken(string memory tokenSymbol) private returns (OptFiPoolToken){
return new OptFiPoolToken(string(abi.encodePacked('OptFI ', tokenSymbol, ' pool share')), string(abi.encodePacked("PST-",tokenSymbol)), true);
}
| 12,960,034
|
// SPDX-License-Identifier: MIXED
// File @boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol@v1.2.2
// License-Identifier: MIT
pragma solidity 0.6.12;
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
}
// File @sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol@v1.4.2
// License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
// File @sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Pair.sol@v1.4.2
// License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File @boringcrypto/boring-solidity/contracts/interfaces/IERC20.sol@v1.2.2
// License-Identifier: MIT
pragma solidity 0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, 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);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File @boringcrypto/boring-solidity/contracts/libraries/BoringRebase.sol@v1.2.2
// License-Identifier: MIT
pragma solidity 0.6.12;
struct Rebase {
uint128 elastic;
uint128 base;
}
/// @notice A rebasing library using overflow-/underflow-safe math.
library RebaseLibrary {
using BoringMath for uint256;
using BoringMath128 for uint128;
/// @notice Calculates the base value in relationship to `elastic` and `total`.
function toBase(
Rebase memory total,
uint256 elastic,
bool roundUp
) internal pure returns (uint256 base) {
if (total.elastic == 0) {
base = elastic;
} else {
base = elastic.mul(total.base) / total.elastic;
if (roundUp && base.mul(total.elastic) / total.base < elastic) {
base = base.add(1);
}
}
}
/// @notice Calculates the elastic value in relationship to `base` and `total`.
function toElastic(
Rebase memory total,
uint256 base,
bool roundUp
) internal pure returns (uint256 elastic) {
if (total.base == 0) {
elastic = base;
} else {
elastic = base.mul(total.elastic) / total.base;
if (roundUp && elastic.mul(total.base) / total.elastic < base) {
elastic = elastic.add(1);
}
}
}
/// @notice Add `elastic` to `total` and doubles `total.base`.
/// @return (Rebase) The new total.
/// @return base in relationship to `elastic`.
function add(
Rebase memory total,
uint256 elastic,
bool roundUp
) internal pure returns (Rebase memory, uint256 base) {
base = toBase(total, elastic, roundUp);
total.elastic = total.elastic.add(elastic.to128());
total.base = total.base.add(base.to128());
return (total, base);
}
/// @notice Sub `base` from `total` and update `total.elastic`.
/// @return (Rebase) The new total.
/// @return elastic in relationship to `base`.
function sub(
Rebase memory total,
uint256 base,
bool roundUp
) internal pure returns (Rebase memory, uint256 elastic) {
elastic = toElastic(total, base, roundUp);
total.elastic = total.elastic.sub(elastic.to128());
total.base = total.base.sub(base.to128());
return (total, elastic);
}
/// @notice Add `elastic` and `base` to `total`.
function add(
Rebase memory total,
uint256 elastic,
uint256 base
) internal pure returns (Rebase memory) {
total.elastic = total.elastic.add(elastic.to128());
total.base = total.base.add(base.to128());
return total;
}
/// @notice Subtract `elastic` and `base` to `total`.
function sub(
Rebase memory total,
uint256 elastic,
uint256 base
) internal pure returns (Rebase memory) {
total.elastic = total.elastic.sub(elastic.to128());
total.base = total.base.sub(base.to128());
return total;
}
/// @notice Add `elastic` to `total` and update storage.
/// @return newElastic Returns updated `elastic`.
function addElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) {
newElastic = total.elastic = total.elastic.add(elastic.to128());
}
/// @notice Subtract `elastic` from `total` and update storage.
/// @return newElastic Returns updated `elastic`.
function subElastic(Rebase storage total, uint256 elastic) internal returns (uint256 newElastic) {
newElastic = total.elastic = total.elastic.sub(elastic.to128());
}
}
// File @sushiswap/bentobox-sdk/contracts/IBatchFlashBorrower.sol@v1.0.2
// License-Identifier: MIT
pragma solidity 0.6.12;
interface IBatchFlashBorrower {
function onBatchFlashLoan(
address sender,
IERC20[] calldata tokens,
uint256[] calldata amounts,
uint256[] calldata fees,
bytes calldata data
) external;
}
// File @sushiswap/bentobox-sdk/contracts/IFlashBorrower.sol@v1.0.2
// License-Identifier: MIT
pragma solidity 0.6.12;
interface IFlashBorrower {
function onFlashLoan(
address sender,
IERC20 token,
uint256 amount,
uint256 fee,
bytes calldata data
) external;
}
// File @sushiswap/bentobox-sdk/contracts/IStrategy.sol@v1.0.2
// License-Identifier: MIT
pragma solidity 0.6.12;
interface IStrategy {
// Send the assets to the Strategy and call skim to invest them
function skim(uint256 amount) external;
// Harvest any profits made converted to the asset and pass them to the caller
function harvest(uint256 balance, address sender) external returns (int256 amountAdded);
// Withdraw assets. The returned amount can differ from the requested amount due to rounding.
// The actualAmount should be very close to the amount. The difference should NOT be used to report a loss. That's what harvest is for.
function withdraw(uint256 amount) external returns (uint256 actualAmount);
// Withdraw all assets in the safest way possible. This shouldn't fail.
function exit(uint256 balance) external returns (int256 amountAdded);
}
// File @sushiswap/bentobox-sdk/contracts/IBentoBoxV1.sol@v1.0.2
// License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IBentoBoxV1 {
event LogDeploy(address indexed masterContract, bytes data, address indexed cloneAddress);
event LogDeposit(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share);
event LogFlashLoan(address indexed borrower, address indexed token, uint256 amount, uint256 feeAmount, address indexed receiver);
event LogRegisterProtocol(address indexed protocol);
event LogSetMasterContractApproval(address indexed masterContract, address indexed user, bool approved);
event LogStrategyDivest(address indexed token, uint256 amount);
event LogStrategyInvest(address indexed token, uint256 amount);
event LogStrategyLoss(address indexed token, uint256 amount);
event LogStrategyProfit(address indexed token, uint256 amount);
event LogStrategyQueued(address indexed token, address indexed strategy);
event LogStrategySet(address indexed token, address indexed strategy);
event LogStrategyTargetPercentage(address indexed token, uint256 targetPercentage);
event LogTransfer(address indexed token, address indexed from, address indexed to, uint256 share);
event LogWhiteListMasterContract(address indexed masterContract, bool approved);
event LogWithdraw(address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function balanceOf(IERC20, address) external view returns (uint256);
function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results);
function batchFlashLoan(IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data) external;
function claimOwnership() external;
function deploy(address masterContract, bytes calldata data, bool useCreate2) external payable;
function deposit(IERC20 token_, address from, address to, uint256 amount, uint256 share) external payable returns (uint256 amountOut, uint256 shareOut);
function flashLoan(IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data) external;
function harvest(IERC20 token, bool balance, uint256 maxChangeAmount) external;
function masterContractApproved(address, address) external view returns (bool);
function masterContractOf(address) external view returns (address);
function nonces(address) external view returns (uint256);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function pendingStrategy(IERC20) external view returns (IStrategy);
function permitToken(IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function registerProtocol() external;
function setMasterContractApproval(address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s) external;
function setStrategy(IERC20 token, IStrategy newStrategy) external;
function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) external;
function strategy(IERC20) external view returns (IStrategy);
function strategyData(IERC20) external view returns (uint64 strategyStartDate, uint64 targetPercentage, uint128 balance);
function toAmount(IERC20 token, uint256 share, bool roundUp) external view returns (uint256 amount);
function toShare(IERC20 token, uint256 amount, bool roundUp) external view returns (uint256 share);
function totals(IERC20) external view returns (Rebase memory totals_);
function transfer(IERC20 token, address from, address to, uint256 share) external;
function transferMultiple(IERC20 token, address from, address[] calldata tos, uint256[] calldata shares) external;
function transferOwnership(address newOwner, bool direct, bool renounce) external;
function whitelistMasterContract(address masterContract, bool approved) external;
function whitelistedMasterContracts(address) external view returns (bool);
function withdraw(IERC20 token_, address from, address to, uint256 amount, uint256 share) external returns (uint256 amountOut, uint256 shareOut);
}
// File contracts/swappers/SpellSwapper.sol
// License-Identifier: MIT
pragma solidity 0.6.12;
interface CurvePool {
function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 min_dy, address receiver) external returns (uint256);
}
interface SushiBar is IERC20 {
function leave(uint256 share) external;
function enter(uint256 amount) external;
function transfer(address _to, uint256 _value) external returns (bool success);
}
interface TetherToken {
function approve(address _spender, uint256 _value) external;
}
contract SpellSwapperV1 {
using BoringMath for uint256;
// Local variables
IBentoBoxV1 public immutable bentoBox;
CurvePool public constant MIM3POOL = CurvePool(0x5a6A4D54456819380173272A5E8E9B9904BdF41B);
TetherToken public constant TETHER = TetherToken(0xdAC17F958D2ee523a2206206994597C13D831ec7);
SushiBar public constant xSushi = SushiBar(0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272);
IERC20 public constant SPELL = IERC20(0x090185f2135308BaD17527004364eBcC2D37e5F6);
address public constant sSPELL = 0x26FA3fFFB6EfE8c1E69103aCb4044C26B9A106a9;
IUniswapV2Pair constant SPELL_WETH = IUniswapV2Pair(0xb5De0C3753b6E1B4dBA616Db82767F17513E6d4E);
IUniswapV2Pair constant pair = IUniswapV2Pair(0x06da0fd433C1A5d7a4faa01111c044910A184553);
IERC20 public constant MIM = IERC20(0x99D8a9C45b2ecA8864373A26D1459e3Dff1e17F3);
mapping (address => bool) public verified;
constructor(
IBentoBoxV1 bentoBox_
) public {
bentoBox = bentoBox_;
MIM.approve(address(MIM3POOL), type(uint256).max);
verified[msg.sender] = true;
}
// Given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountOut) {
uint256 amountInWithFee = amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(reserveOut);
uint256 denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// Given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) internal pure returns (uint256 amountIn) {
uint256 numerator = reserveIn.mul(amountOut).mul(1000);
uint256 denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
modifier onlyVerified {
require(verified[msg.sender], "Only verified operators");
_;
}
function setVerified(address operator, bool status) public onlyVerified {
verified[operator] = status;
}
// Swaps to a flexible amount, from an exact input amount
function swap(
uint256 amountToMin
) public onlyVerified{
uint256 amountFirst;
uint256 amountIntermediate;
{
uint256 shareFrom = bentoBox.balanceOf(MIM, address(this));
(uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
amountFirst = MIM3POOL.exchange_underlying(0, 3, amountMIMFrom, 0, address(pair));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0);
}
uint256 amountThird;
{
pair.swap(amountIntermediate, 0, address(SPELL_WETH), new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = SPELL_WETH.getReserves();
amountThird = getAmountOut(amountIntermediate, reserve1, reserve0);
require(amountThird >= amountToMin, "Minimum must be reached");
}
SPELL_WETH.swap(amountThird, 0, sSPELL, new bytes(0));
}
}
|
Swaps to a flexible amount, from an exact input amount
|
function swap(
uint256 amountToMin
) public onlyVerified{
uint256 amountFirst;
uint256 amountIntermediate;
{
uint256 shareFrom = bentoBox.balanceOf(MIM, address(this));
(uint256 amountMIMFrom, ) = bentoBox.withdraw(MIM, address(this), address(this), 0, shareFrom);
amountFirst = MIM3POOL.exchange_underlying(0, 3, amountMIMFrom, 0, address(pair));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
amountIntermediate = getAmountOut(amountFirst, reserve1, reserve0);
}
uint256 amountThird;
{
pair.swap(amountIntermediate, 0, address(SPELL_WETH), new bytes(0));
(uint256 reserve0, uint256 reserve1, ) = SPELL_WETH.getReserves();
amountThird = getAmountOut(amountIntermediate, reserve1, reserve0);
require(amountThird >= amountToMin, "Minimum must be reached");
}
SPELL_WETH.swap(amountThird, 0, sSPELL, new bytes(0));
}
| 14,836,010
|
// Sources flattened with hardhat v2.1.1 https://hardhat.org
// File hardhat/console.sol@v2.1.1
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File @openzeppelin/contracts/token/ERC20/IERC20.sol@v3.4.1
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);
}
// File @openzeppelin/contracts/math/SafeMath.sol@v3.4.1
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;
}
}
// File @openzeppelin/contracts/utils/Address.sol@v3.4.1
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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/SafeERC20.sol@v3.4.1
pragma solidity >=0.6.0 <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 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");
}
}
}
// File contracts/interfaces/IDetailedERC20.sol
pragma solidity ^0.6.12;
interface IDetailedERC20 is IERC20 {
function name() external returns (string memory);
function symbol() external returns (string memory);
function decimals() external returns (uint8);
}
// File contracts/interfaces/IVaultAdapterV2.sol
pragma solidity ^0.6.12;
/// Interface for all Vault Adapter implementations.
interface IVaultAdapterV2 {
/// @dev Gets the token that the adapter accepts.
function token() external view returns (IDetailedERC20);
/// @dev The total value of the assets deposited into the vault.
function totalValue() external view returns (uint256);
/// @dev Deposits funds into the vault.
///
/// @param _amount the amount of funds to deposit.
function deposit(uint256 _amount) external;
/// @dev Attempts to withdraw funds from the wrapped vault.
///
/// The amount withdrawn to the recipient may be less than the amount requested.
///
/// @param _recipient the recipient of the funds.
/// @param _amount the amount of funds to withdraw.
function withdraw(address _recipient, uint256 _amount, bool _isHarvest) external;
}
// File contracts/interfaces/vesper/IVesperPool.sol
pragma solidity 0.6.12;
interface IVesperPool is IERC20 {
function approveToken() external;
function deposit() external payable;
function deposit(uint256) external;
function multiTransfer(uint256[] memory) external returns (bool);
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
function rebalance() external;
function resetApproval() external;
function sweepErc20(address) external;
function withdraw(uint256) external;
function withdrawETH(uint256) external;
function withdrawByStrategy(uint256) external;
function feeCollector() external view returns (address);
function getPricePerShare() external view returns (uint256);
function token() external view returns (address);
function tokensHere() external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
function decimals() external view returns (uint);
function convertTo18(uint256) external view returns (uint256);
function convertFrom18(uint256) external view returns (uint256);
}
// File contracts/interfaces/vesper/IPoolRewards.sol
pragma solidity 0.6.12;
interface IPoolRewards {
function notifyRewardAmount(uint256) external;
function claimReward(address) external;
function updateReward(address) external;
function rewardForDuration() external view returns (uint256);
function claimable(address) external view returns (uint256);
function pool() external view returns (address);
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
}
// File contracts/libraries/uni/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File contracts/adapters/VesperVaultAdapter.sol
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
/// @title VesperVaultAdapter
///
/// @dev A vault adapter implementation which wraps a vesper vault.
contract VesperVaultAdapter is IVaultAdapterV2 {
using SafeERC20 for IDetailedERC20;
using SafeMath for uint256;
/// @dev The vault that the adapter is wrapping.
IVesperPool public vault;
/// @dev The vsp pool to claim vsp rewards from.
IPoolRewards public vspPool;
/// @dev UniswapV2Router
IUniswapV2Router02 public uniV2Router;
/// @dev vesperToken
IDetailedERC20 public vesperToken;
/// @dev wETH
IDetailedERC20 public wETHToken;
/// @dev The address which has admin control over this contract.
address public admin;
/// @dev The decimals of the token.
uint256 public decimals;
constructor(IVesperPool _vault, IPoolRewards _vspPool, address _admin,
IUniswapV2Router02 _uniV2Router, IDetailedERC20 _vesperToken, IDetailedERC20 _wethToken) public {
vault = _vault;
vspPool = _vspPool;
admin = _admin;
uniV2Router = _uniV2Router;
vesperToken = _vesperToken;
wETHToken = _wethToken;
updateApproval();
decimals = _vault.decimals();
}
/// @dev A modifier which reverts if the caller is not the admin.
modifier onlyAdmin() {
require(admin == msg.sender, "VesperVaultAdapter: only admin");
_;
}
/// @dev Gets the token that the vault accepts.
///
/// @return the accepted token.
function token() external view override returns (IDetailedERC20) {
return IDetailedERC20(vault.token());
}
/// @dev Gets the total value of the assets that the adapter holds in the vault.
///
/// @return the total assets.
function totalValue() external view override returns (uint256) {
return _sharesToTokens(vault.balanceOf(address(this)));
}
/// @dev Deposits tokens into the vault.
///
/// @param _amount the amount of tokens to deposit into the vault.
function deposit(uint256 _amount) external override {
vault.deposit(_amount);
}
/// @dev Withdraws tokens from the vault to the recipient.
///
/// This function reverts if the caller is not the admin.
///
/// @param _recipient the account to withdraw the tokes to.
/// @param _amount the amount of tokens to withdraw.
function withdraw(address _recipient, uint256 _amount, bool _isHarvest) external override onlyAdmin {
// redeem original deposited vault token
vault.withdraw(_tokensToShares(_amount));
IDetailedERC20 vaultToken = IDetailedERC20(vault.token());
// claim vesper token from pool rewards
vspPool.claimReward(address(this));
uint256 vspRewardsAmount = vesperToken.balanceOf(address(this));
// sell vesper if is called from harvest and if there're vsp rewards
if(_isHarvest && vspRewardsAmount > 0){
address[] memory _pathVesper = new address[](3);
_pathVesper[0] = address(vesperToken);
_pathVesper[1] = address(wETHToken);
_pathVesper[2] = address(vaultToken);
uniV2Router.swapExactTokensForTokens(vspRewardsAmount,
0,
_pathVesper,
address(this),
block.timestamp+800);
}
// transfer all the vault token in adapter to yum vault
vaultToken.transfer(_recipient, vaultToken.balanceOf(address(this)));
}
/// @dev Updates the vaults approval of the token to be the maximum value.
function updateApproval() public {
address _token = vault.token();
IDetailedERC20(_token).safeApprove(address(vault), uint256(-1));
vesperToken.safeApprove(address(uniV2Router), uint256(-1));
}
/// @dev Computes the number of tokens an amount of shares is worth.
///
/// @param _sharesAmount the amount of shares.
///
/// @return the number of tokens the shares are worth.
function _sharesToTokens(uint256 _sharesAmount) internal view returns (uint256) {
return vault.convertFrom18(_sharesAmount.mul(vault.convertTo18(vault.totalValue())).div(vault.totalSupply()));
}
/// @dev Computes the number of shares an amount of tokens is worth.
///
/// @param _tokensAmount the amount of shares.
///
/// @return the number of shares the tokens are worth.
function _tokensToShares(uint256 _tokensAmount) internal view returns (uint256) {
return vault.convertTo18(_tokensAmount).mul(vault.totalSupply()).div(vault.convertTo18(vault.totalValue()));
}
}
|
Computes the number of tokens an amount of shares is worth. _sharesAmount the amount of shares. return the number of tokens the shares are worth.
|
function _sharesToTokens(uint256 _sharesAmount) internal view returns (uint256) {
return vault.convertFrom18(_sharesAmount.mul(vault.convertTo18(vault.totalValue())).div(vault.totalSupply()));
}
| 226,102
|
./partial_match/56/0xB8B3776bB2688A3e9fe7A9B76C3F83afdCd6E7b9/sources/ICEChef.sol
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 iceReward = multiplier.mul(icePerBlock).mul(pool.allocPoint).div(totalAllocPoint);
ice.mint(address(this), iceReward);
pool.accICEPerShare = pool.accICEPerShare.add(iceReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 11,216,528
|
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.7.5;
import "./libraries/SafeMath.sol";
import "./libraries/SafeERC20.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IsCADT.sol";
import "./interfaces/IgCADT.sol";
import "./interfaces/IDistributor.sol";
import "./types/CoachAIAccessControlled.sol";
contract CoachAIStaking is CoachAIAccessControlled {
/* ========== DEPENDENCIES ========== */
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for IsCADT;
using SafeERC20 for IgCADT;
/* ========== EVENTS ========== */
event DistributorSet(address distributor);
event WarmupSet(uint256 warmup);
event LogUnstakeCall(address _to, uint256 _amount, bool _trigger, bool _rebasing);
event LogStakeCall(address _to, uint256 _amount, bool _rebasing, bool _claim);
/* ========== DATA STRUCTURES ========== */
struct Epoch {
uint256 length; // in seconds
uint256 number; // since inception
uint256 end; // timestamp
uint256 distribute; // amount
}
struct Claim {
uint256 deposit; // if forfeiting
uint256 gons; // staked balance
uint256 expiry; // end of warmup period
bool lock; // prevents malicious delays for claim
}
/* ========== STATE VARIABLES ========== */
IERC20 public immutable CADT;
IsCADT public immutable sCADT;
IgCADT public immutable gCADT;
Epoch public epoch;
IDistributor public distributor;
mapping(address => Claim) public warmupInfo;
uint256 public warmupPeriod;
uint256 private gonsInWarmup;
/* ========== CONSTRUCTOR ========== */
constructor(
address _cadt,
address _sCADT,
address _gCADT,
uint256 _epochLength,
uint256 _firstEpochNumber,
uint256 _firstEpochTime,
address _authority
) CoachAIAccessControlled(ICoachAIAuthority(_authority)) {
require(_cadt != address(0), "Zero address: CADT");
CADT = IERC20(_cadt);
require(_sCADT != address(0), "Zero address: sCADT");
sCADT = IsCADT(_sCADT);
require(_gCADT != address(0), "Zero address: gCADT");
gCADT = IgCADT(_gCADT);
epoch = Epoch({length: _epochLength, number: _firstEpochNumber, end: _firstEpochTime, distribute: 0});
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice stake CADT to enter warmup
* @param _to address
* @param _amount uint
* @param _claim bool
* @param _rebasing bool
* @return uint
*/
function stake(
address _to,
uint256 _amount,
bool _rebasing,
bool _claim
) external returns (uint256) {
emit LogStakeCall(_to, _amount, _rebasing, _claim);
CADT.safeTransferFrom(msg.sender, address(this), _amount);
_amount = _amount.add(rebase()); // add bounty if rebase occurred
if (_claim && warmupPeriod == 0) {
return _send(_to, _amount, _rebasing);
} else {
Claim memory info = warmupInfo[_to];
if (!info.lock) {
require(_to == msg.sender, "External deposits for account are locked");
}
warmupInfo[_to] = Claim({
deposit: info.deposit.add(_amount),
gons: info.gons.add(sCADT.gonsForBalance(_amount)),
expiry: epoch.number.add(warmupPeriod),
lock: info.lock
});
gonsInWarmup = gonsInWarmup.add(sCADT.gonsForBalance(_amount));
return _amount;
}
}
/**
* @notice retrieve stake from warmup
* @param _to address
* @param _rebasing bool
* @return uint
*/
function claim(address _to, bool _rebasing) public returns (uint256) {
Claim memory info = warmupInfo[_to];
if (!info.lock) {
require(_to == msg.sender, "External claims for account are locked");
}
if (epoch.number >= info.expiry && info.expiry != 0) {
delete warmupInfo[_to];
gonsInWarmup = gonsInWarmup.sub(info.gons);
return _send(_to, sCADT.balanceForGons(info.gons), _rebasing);
}
return 0;
}
/**
* @notice forfeit stake and retrieve CADT
* @return uint
*/
function forfeit() external returns (uint256) {
Claim memory info = warmupInfo[msg.sender];
delete warmupInfo[msg.sender];
gonsInWarmup = gonsInWarmup.sub(info.gons);
CADT.safeTransfer(msg.sender, info.deposit);
return info.deposit;
}
/**
* @notice prevent new deposits or claims from ext. address (protection from malicious activity)
*/
function toggleLock() external {
warmupInfo[msg.sender].lock = !warmupInfo[msg.sender].lock;
}
/**
* @notice redeem sCADT for CADTs
* @param _to address
* @param _amount uint
* @param _trigger bool
* @param _rebasing bool
* @return amount_ uint
*/
function unstake(
address _to,
uint256 _amount,
bool _trigger,
bool _rebasing
) external returns (uint256 amount_) {
amount_ = _amount;
uint256 bounty;
emit LogUnstakeCall(_to, _amount, _trigger, _rebasing);
if (_trigger) {
bounty = rebase();
}
if (_rebasing) {
sCADT.safeTransferFrom(msg.sender, address(this), _amount);
amount_ = amount_.add(bounty);
} else {
gCADT.burn(msg.sender, _amount); // amount was given in gCADT terms
amount_ = gCADT.balanceFrom(amount_).add(bounty); // convert amount to CADT terms & add bounty
}
require(amount_ <= CADT.balanceOf(address(this)), "Insufficient CADT balance in contract");
CADT.safeTransfer(_to, amount_);
}
/**
* @notice convert _amount sCADT into gBalance_ gCADT
* @param _to address
* @param _amount uint
* @return gBalance_ uint
*/
function wrap(address _to, uint256 _amount) external returns (uint256 gBalance_) {
sCADT.safeTransferFrom(msg.sender, address(this), _amount);
gBalance_ = gCADT.balanceTo(_amount);
gCADT.mint(_to, gBalance_);
}
/**
* @notice convert _amount gCADT into sBalance_ sCADT
* @param _to address
* @param _amount uint
* @return sBalance_ uint
*/
function unwrap(address _to, uint256 _amount) external returns (uint256 sBalance_) {
gCADT.burn(msg.sender, _amount);
sBalance_ = gCADT.balanceFrom(_amount);
sCADT.safeTransfer(_to, sBalance_);
}
/**
* @notice trigger rebase if epoch over
* @return uint256
*/
function rebase() public returns (uint256) {
uint256 bounty;
if (epoch.end <= block.timestamp) {
sCADT.rebase(epoch.distribute, epoch.number);
epoch.end = epoch.end.add(epoch.length);
epoch.number++;
if (address(distributor) != address(0)) {
distributor.distribute();
bounty = distributor.retrieveBounty(); // Will mint cadt for this contract if there exists a bounty
}
uint256 balance = CADT.balanceOf(address(this));
uint256 staked = sCADT.circulatingSupply();
if (balance <= staked.add(bounty)) {
epoch.distribute = 0;
} else {
epoch.distribute = balance.sub(staked).sub(bounty);
}
}
return bounty;
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice send staker their amount as sCADT or gCADT
* @param _to address
* @param _amount uint
* @param _rebasing bool
*/
function _send(
address _to,
uint256 _amount,
bool _rebasing
) internal returns (uint256) {
if (_rebasing) {
sCADT.safeTransfer(_to, _amount); // send as sCADT (equal unit as CADT)
return _amount;
} else {
gCADT.mint(_to, gCADT.balanceTo(_amount)); // send as gCADT (convert units from CADT)
return gCADT.balanceTo(_amount);
}
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice returns the sCADT index, which tracks rebase growth
* @return uint
*/
function index() public view returns (uint256) {
return sCADT.index();
}
/**
* @notice total supply in warmup
*/
function supplyInWarmup() public view returns (uint256) {
return sCADT.balanceForGons(gonsInWarmup);
}
/**
* @notice seconds until the next epoch begins
*/
function secondsToNextEpoch() external view returns (uint256) {
return epoch.end.sub(block.timestamp);
}
/* ========== MANAGERIAL FUNCTIONS ========== */
/**
* @notice sets the contract address for LP staking
* @param _distributor address
*/
function setDistributor(address _distributor) external onlyGovernor {
distributor = IDistributor(_distributor);
emit DistributorSet(_distributor);
}
/**
* @notice set warmup period for new stakers
* @param _warmupPeriod uint
*/
function setWarmupLength(uint256 _warmupPeriod) external onlyGovernor {
warmupPeriod = _warmupPeriod;
emit WarmupSet(_warmupPeriod);
}
}
|
total supply in warmup/
|
function supplyInWarmup() public view returns (uint256) {
return sCADT.balanceForGons(gonsInWarmup);
}
| 1,796,808
|
./full_match/1/0xB0A1Cd3b31A8e3bbBaba15fEDdB88ABD932a677d/sources/contracts/mixins/nftMarket/NFTMarketExhibition.sol
|
Clears an NFT's association with an exhibition./
|
function _removeNftFromExhibition(address nftContract, uint256 tokenId) internal {
uint256 exhibitionId = $nftContractToTokenIdToExhibitionId[nftContract][tokenId];
if (exhibitionId != 0) {
delete $nftContractToTokenIdToExhibitionId[nftContract][tokenId];
emit NftRemovedFromExhibition(nftContract, tokenId, exhibitionId);
}
}
| 8,357,080
|
./full_match/80001/0x8e470FebB4FC23A517805C715b5163A2c55592E4/sources/DoodleFarm.sol
|
withdrawal function.
|
function withdrawTokens() external onlyOwner {
uint256 tokenSupply = erc20Token.balanceOf(address(this));
erc20Token.transfer(msg.sender, tokenSupply);
}
| 5,595,130
|
./partial_match/1/0xda99cbAaa7307D4e0c3D1CF83D459f9ad729e9C8/sources/contracts/twap/base/UniswapV3TwapLiquidityManager.sol
|
Burns liquidity in the given range _tickLower Lower Tick _tickUpper Upper Tick _shares The amount of liquidity to be burned based on shares/
|
function burnLiquidity(
int24 _tickLower,
int24 _tickUpper,
uint256 _shares,
uint128 _currentLiquidity
)
internal
returns (
uint256 tokensBurned0,
uint256 tokensBurned1,
uint256 fee0,
uint256 fee1
)
{
uint256 collect0;
uint256 collect1;
if (_shares > 0) {
(_currentLiquidity, , , , ) = pool.positions(PositionKey.compute(address(this), _tickLower, _tickUpper));
if (_currentLiquidity > 0) {
uint256 liquidity = FullMath.mulDiv(_currentLiquidity, _shares, totalSupply());
(tokensBurned0, tokensBurned1) = pool.burn(_tickLower, _tickUpper, liquidity.toUint128());
}
(tokensBurned0, tokensBurned1) = pool.burn(_tickLower, _tickUpper, _currentLiquidity);
}
fee0 = collect0 > tokensBurned0 ? uint256(collect0).sub(tokensBurned0) : 0;
fee1 = collect1 > tokensBurned1 ? uint256(collect1).sub(tokensBurned1) : 0;
}
| 3,692,523
|
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IFeeDistributor.sol";
import "../interfaces/ILiquidityGauge.sol";
import "../interfaces/ISanToken.sol";
import "../interfaces/IStableMaster.sol";
import "../interfaces/IStableMasterFront.sol";
import "../interfaces/IVeANGLE.sol";
import "../interfaces/external/IWETH9.sol";
import "../interfaces/external/uniswap/IUniswapRouter.sol";
/// @title Angle Router
/// @author Angle Core Team
/// @notice The `AngleRouter` contract facilitates interactions for users with the protocol. It was built to reduce the number
/// of approvals required to users and the number of transactions needed to perform some complex actions: like deposit and stake
/// in just one transaction
/// @dev Interfaces were designed for both advanced users which know the addresses of the protocol's contract, but most of the time
/// users which only know addresses of the stablecoins and collateral types of the protocol can perform the actions they want without
/// needing to understand what's happening under the hood
contract AngleRouter is Initializable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
/// @notice Base used for params
uint256 public constant BASE_PARAMS = 10**9;
/// @notice Base used for params
uint256 private constant _MAX_TOKENS = 10;
// @notice Wrapped ETH contract
IWETH9 public constant WETH9 = IWETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// @notice ANGLE contract
IERC20 public constant ANGLE = IERC20(0x31429d1856aD1377A8A0079410B297e1a9e214c2);
// @notice veANGLE contract
IVeANGLE public constant VEANGLE = IVeANGLE(0x0C462Dbb9EC8cD1630f1728B2CFD2769d09f0dd5);
// =========================== Structs and Enums ===============================
/// @notice Action types
enum ActionType {
claimRewards,
claimWeeklyInterest,
gaugeDeposit,
withdraw,
mint,
deposit,
openPerpetual,
addToPerpetual,
veANGLEDeposit
}
/// @notice All possible swaps
enum SwapType {
UniswapV3,
oneINCH
}
/// @notice Params for swaps
/// @param inToken Token to swap
/// @param collateral Token to swap for
/// @param amountIn Amount of token to sell
/// @param minAmountOut Minimum amount of collateral to receive for the swap to not revert
/// @param args Either the path for Uniswap or the payload for 1Inch
/// @param swapType Which swap route to take
struct ParamsSwapType {
IERC20 inToken;
address collateral;
uint256 amountIn;
uint256 minAmountOut;
bytes args;
SwapType swapType;
}
/// @notice Params for direct collateral transfer
/// @param inToken Token to transfer
/// @param amountIn Amount of token transfer
struct TransferType {
IERC20 inToken;
uint256 amountIn;
}
/// @notice References to the contracts associated to a collateral for a stablecoin
struct Pairs {
IPoolManager poolManager;
IPerpetualManagerFrontWithClaim perpetualManager;
ISanToken sanToken;
ILiquidityGauge gauge;
}
/// @notice Data needed to get permits
struct PermitType {
address token;
address owner;
uint256 value;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
// =============================== Events ======================================
event AdminChanged(address indexed admin, bool setGovernor);
event StablecoinAdded(address indexed stableMaster);
event StablecoinRemoved(address indexed stableMaster);
event CollateralToggled(address indexed stableMaster, address indexed poolManager, address indexed liquidityGauge);
event SanTokenLiquidityGaugeUpdated(address indexed sanToken, address indexed newLiquidityGauge);
event Recovered(address indexed tokenAddress, address indexed to, uint256 amount);
// =============================== Mappings ====================================
/// @notice Maps an agToken to its counterpart `StableMaster`
mapping(IERC20 => IStableMasterFront) public mapStableMasters;
/// @notice Maps a `StableMaster` to a mapping of collateral token to its counterpart `PoolManager`
mapping(IStableMasterFront => mapping(IERC20 => Pairs)) public mapPoolManagers;
/// @notice Whether the token was already approved on Uniswap router
mapping(IERC20 => bool) public uniAllowedToken;
/// @notice Whether the token was already approved on 1Inch
mapping(IERC20 => bool) public oneInchAllowedToken;
// =============================== References ==================================
/// @notice Governor address
address public governor;
/// @notice Guardian address
address public guardian;
/// @notice Address of the router used for swaps
IUniswapV3Router public uniswapV3Router;
/// @notice Address of 1Inch router used for swaps
address public oneInch;
uint256[50] private __gap;
constructor() initializer {}
/// @notice Deploys the `AngleRouter` contract
/// @param _governor Governor address
/// @param _guardian Guardian address
/// @param _uniswapV3Router UniswapV3 router address
/// @param _oneInch 1Inch aggregator address
/// @param existingStableMaster Address of the existing `StableMaster`
/// @param existingPoolManagers Addresses of the associated poolManagers
/// @param existingLiquidityGauges Addresses of liquidity gauge contracts associated to sanTokens
/// @dev Be cautious with safe approvals, all tokens will have unlimited approvals within the protocol or
/// UniswapV3 and 1Inch
function initialize(
address _governor,
address _guardian,
IUniswapV3Router _uniswapV3Router,
address _oneInch,
IStableMasterFront existingStableMaster,
IPoolManager[] calldata existingPoolManagers,
ILiquidityGauge[] calldata existingLiquidityGauges
) public initializer {
// Checking the parameters passed
require(
address(_uniswapV3Router) != address(0) &&
_oneInch != address(0) &&
_governor != address(0) &&
_guardian != address(0),
"0"
);
require(_governor != _guardian, "49");
require(existingPoolManagers.length == existingLiquidityGauges.length, "104");
// Fetching the stablecoin and mapping it to the `StableMaster`
mapStableMasters[
IERC20(address(IStableMaster(address(existingStableMaster)).agToken()))
] = existingStableMaster;
// Setting roles
governor = _governor;
guardian = _guardian;
uniswapV3Router = _uniswapV3Router;
oneInch = _oneInch;
// for veANGLEDeposit action
ANGLE.safeApprove(address(VEANGLE), type(uint256).max);
for (uint256 i = 0; i < existingPoolManagers.length; i++) {
_addPair(existingStableMaster, existingPoolManagers[i], existingLiquidityGauges[i]);
}
}
// ============================== Modifiers ====================================
/// @notice Checks to see if it is the `governor` or `guardian` calling this contract
/// @dev There is no Access Control here, because it can be handled cheaply through this modifier
/// @dev In this contract, the `governor` and the `guardian` address have exactly similar rights
modifier onlyGovernorOrGuardian() {
require(msg.sender == governor || msg.sender == guardian, "115");
_;
}
// =========================== Governance utilities ============================
/// @notice Changes the guardian or the governor address
/// @param admin New guardian or guardian address
/// @param setGovernor Whether to set Governor if true, or Guardian if false
/// @dev There can only be one guardian and one governor address in the router
/// and both need to be different
function setGovernorOrGuardian(address admin, bool setGovernor) external onlyGovernorOrGuardian {
require(admin != address(0), "0");
require(guardian != admin && governor != admin, "49");
if (setGovernor) governor = admin;
else guardian = admin;
emit AdminChanged(admin, setGovernor);
}
/// @notice Adds a new `StableMaster`
/// @param stablecoin Address of the new stablecoin
/// @param stableMaster Address of the new `StableMaster`
function addStableMaster(IERC20 stablecoin, IStableMasterFront stableMaster) external onlyGovernorOrGuardian {
// No need to check if the `stableMaster` address is a zero address as otherwise the call to `stableMaster.agToken()`
// would revert
require(address(stablecoin) != address(0), "0");
require(address(mapStableMasters[stablecoin]) == address(0), "114");
require(stableMaster.agToken() == address(stablecoin), "20");
mapStableMasters[stablecoin] = stableMaster;
emit StablecoinAdded(address(stableMaster));
}
/// @notice Removes a `StableMaster`
/// @param stablecoin Address of the associated stablecoin
/// @dev Before calling this function, governor or guardian should remove first all pairs
/// from the `mapPoolManagers[stableMaster]`. It is assumed that the governor or guardian calling this function
/// will act correctly here, it indeed avoids storing a list of all pairs for each `StableMaster`
function removeStableMaster(IERC20 stablecoin) external onlyGovernorOrGuardian {
IStableMasterFront stableMaster = mapStableMasters[stablecoin];
delete mapStableMasters[stablecoin];
emit StablecoinRemoved(address(stableMaster));
}
/// @notice Adds new collateral types to specific stablecoins
/// @param stablecoins Addresses of the stablecoins associated to the `StableMaster` of interest
/// @param poolManagers Addresses of the `PoolManager` contracts associated to the pair (stablecoin,collateral)
/// @param liquidityGauges Addresses of liquidity gauges contract associated to sanToken
function addPairs(
IERC20[] calldata stablecoins,
IPoolManager[] calldata poolManagers,
ILiquidityGauge[] calldata liquidityGauges
) external onlyGovernorOrGuardian {
require(poolManagers.length == stablecoins.length && liquidityGauges.length == stablecoins.length, "104");
for (uint256 i = 0; i < stablecoins.length; i++) {
IStableMasterFront stableMaster = mapStableMasters[stablecoins[i]];
_addPair(stableMaster, poolManagers[i], liquidityGauges[i]);
}
}
/// @notice Removes collateral types from specific `StableMaster` contracts using the address
/// of the associated stablecoins
/// @param stablecoins Addresses of the stablecoins
/// @param collaterals Addresses of the collaterals
/// @param stableMasters List of the associated `StableMaster` contracts
/// @dev In the lists, if a `stableMaster` address is null in `stableMasters` then this means that the associated
/// `stablecoins` address (at the same index) should be non null
function removePairs(
IERC20[] calldata stablecoins,
IERC20[] calldata collaterals,
IStableMasterFront[] calldata stableMasters
) external onlyGovernorOrGuardian {
require(collaterals.length == stablecoins.length && stableMasters.length == collaterals.length, "104");
Pairs memory pairs;
IStableMasterFront stableMaster;
for (uint256 i = 0; i < stablecoins.length; i++) {
if (address(stableMasters[i]) == address(0))
// In this case `collaterals[i]` is a collateral address
(stableMaster, pairs) = _getInternalContracts(stablecoins[i], collaterals[i]);
else {
// In this case `collaterals[i]` is a `PoolManager` address
stableMaster = stableMasters[i];
pairs = mapPoolManagers[stableMaster][collaterals[i]];
}
delete mapPoolManagers[stableMaster][collaterals[i]];
_changeAllowance(collaterals[i], address(stableMaster), 0);
_changeAllowance(collaterals[i], address(pairs.perpetualManager), 0);
if (address(pairs.gauge) != address(0)) pairs.sanToken.approve(address(pairs.gauge), 0);
emit CollateralToggled(address(stableMaster), address(pairs.poolManager), address(pairs.gauge));
}
}
/// @notice Sets new `liquidityGauge` contract for the associated sanTokens
/// @param stablecoins Addresses of the stablecoins
/// @param collaterals Addresses of the collaterals
/// @param newLiquidityGauges Addresses of the new liquidity gauges contract
/// @dev If `newLiquidityGauge` is null, this means that there is no liquidity gauge for this pair
/// @dev This function could be used to simply revoke the approval to a liquidity gauge
function setLiquidityGauges(
IERC20[] calldata stablecoins,
IERC20[] calldata collaterals,
ILiquidityGauge[] calldata newLiquidityGauges
) external onlyGovernorOrGuardian {
require(collaterals.length == stablecoins.length && newLiquidityGauges.length == stablecoins.length, "104");
for (uint256 i = 0; i < stablecoins.length; i++) {
IStableMasterFront stableMaster = mapStableMasters[stablecoins[i]];
Pairs storage pairs = mapPoolManagers[stableMaster][collaterals[i]];
ILiquidityGauge gauge = pairs.gauge;
ISanToken sanToken = pairs.sanToken;
require(address(stableMaster) != address(0) && address(pairs.poolManager) != address(0), "0");
pairs.gauge = newLiquidityGauges[i];
if (address(gauge) != address(0)) {
sanToken.approve(address(gauge), 0);
}
if (address(newLiquidityGauges[i]) != address(0)) {
// Checking compatibility of the staking token: it should be the sanToken
require(address(newLiquidityGauges[i].staking_token()) == address(sanToken), "20");
sanToken.approve(address(newLiquidityGauges[i]), type(uint256).max);
}
emit SanTokenLiquidityGaugeUpdated(address(sanToken), address(newLiquidityGauges[i]));
}
}
/// @notice Change allowance for a contract.
/// @param tokens Addresses of the tokens to allow
/// @param spenders Addresses to allow transfer
/// @param amounts Amounts to allow
/// @dev Approvals are normally given in the `addGauges` method, in the initializer and in
/// the internal functions to process swaps with Uniswap and 1Inch
function changeAllowance(
IERC20[] calldata tokens,
address[] calldata spenders,
uint256[] calldata amounts
) external onlyGovernorOrGuardian {
require(tokens.length == spenders.length && tokens.length == amounts.length, "104");
for (uint256 i = 0; i < tokens.length; i++) {
_changeAllowance(tokens[i], spenders[i], amounts[i]);
}
}
/// @notice Supports recovering any tokens as the router does not own any other tokens than
/// the one mistakenly sent
/// @param tokenAddress Address of the token to transfer
/// @param to Address to give tokens to
/// @param tokenAmount Amount of tokens to transfer
/// @dev If tokens are mistakenly sent to this contract, any address can take advantage of the `mixer` function
/// below to get the funds back
function recoverERC20(
address tokenAddress,
address to,
uint256 tokenAmount
) external onlyGovernorOrGuardian {
IERC20(tokenAddress).safeTransfer(to, tokenAmount);
emit Recovered(tokenAddress, to, tokenAmount);
}
// =========================== Router Functionalities =========================
/// @notice Wrapper n°1 built on top of the _claimRewards function
/// Allows to claim rewards for multiple gauges and perpetuals at once
/// @param gaugeUser Address for which to fetch the rewards from the gauges
/// @param liquidityGauges Gauges to claim on
/// @param perpetualIDs Perpetual IDs to claim rewards for
/// @param stablecoins Stablecoin contracts linked to the perpetualsIDs
/// @param collaterals Collateral contracts linked to the perpetualsIDs or `perpetualManager`
/// @dev If the caller wants to send the rewards to another account it first needs to
/// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge`
function claimRewards(
address gaugeUser,
address[] memory liquidityGauges,
uint256[] memory perpetualIDs,
address[] memory stablecoins,
address[] memory collaterals
) external nonReentrant {
_claimRewards(gaugeUser, liquidityGauges, perpetualIDs, false, stablecoins, collaterals);
}
/// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the _claimRewards function
/// Allows to claim rewards for multiple gauges and perpetuals at once
/// @param user Address to which the contract should send the rewards from gauges (not perpetuals)
/// @param liquidityGauges Contracts to claim for
/// @param perpetualIDs Perpetual IDs to claim rewards for
/// @param perpetualManagers `perpetualManager` contracts for every perp to claim
/// @dev If the caller wants to send the rewards to another account it first needs to
/// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge`
function claimRewards(
address user,
address[] memory liquidityGauges,
uint256[] memory perpetualIDs,
address[] memory perpetualManagers
) external nonReentrant {
_claimRewards(user, liquidityGauges, perpetualIDs, true, new address[](perpetualIDs.length), perpetualManagers);
}
/// @notice Wrapper built on top of the `_gaugeDeposit` method to deposit collateral in a gauge
/// @param token On top of the parameters of the internal function, users need to specify the token associated
/// to the gauge they want to deposit in
/// @dev The function will revert if the token does not correspond to the gauge
function gaugeDeposit(
address user,
uint256 amount,
ILiquidityGauge gauge,
bool shouldClaimRewards,
IERC20 token
) external nonReentrant {
token.safeTransferFrom(msg.sender, address(this), amount);
_gaugeDeposit(user, amount, gauge, shouldClaimRewards);
}
/// @notice Wrapper n°1 built on top of the `_mint` method to mint stablecoins
/// @param user Address to send the stablecoins to
/// @param amount Amount of collateral to use for the mint
/// @param minStableAmount Minimum stablecoin minted for the tx not to revert
/// @param stablecoin Address of the stablecoin to mint
/// @param collateral Collateral to mint from
function mint(
address user,
uint256 amount,
uint256 minStableAmount,
address stablecoin,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_mint(user, amount, minStableAmount, false, stablecoin, collateral, IPoolManager(address(0)));
}
/// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the `_mint` method to mint stablecoins
/// @param user Address to send the stablecoins to
/// @param amount Amount of collateral to use for the mint
/// @param minStableAmount Minimum stablecoin minted for the tx not to revert
/// @param stableMaster Address of the stableMaster managing the stablecoin to mint
/// @param collateral Collateral to mint from
/// @param poolManager PoolManager associated to the `collateral`
function mint(
address user,
uint256 amount,
uint256 minStableAmount,
address stableMaster,
address collateral,
address poolManager
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_mint(user, amount, minStableAmount, true, stableMaster, collateral, IPoolManager(poolManager));
}
/// @notice Wrapper built on top of the `_burn` method to burn stablecoins
/// @param dest Address to send the collateral to
/// @param amount Amount of stablecoins to use for the burn
/// @param minCollatAmount Minimum collateral amount received for the tx not to revert
/// @param stablecoin Address of the stablecoin to mint
/// @param collateral Collateral to mint from
function burn(
address dest,
uint256 amount,
uint256 minCollatAmount,
address stablecoin,
address collateral
) external nonReentrant {
_burn(dest, amount, minCollatAmount, false, stablecoin, collateral, IPoolManager(address(0)));
}
/// @notice Wrapper n°1 built on top of the `_deposit` method to deposit collateral as a SLP in the protocol
/// Allows to deposit a collateral within the protocol
/// @param user Address where to send the resulting sanTokens, if this address is the router address then it means
/// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action
/// @param amount Amount of collateral to deposit
/// @param stablecoin `StableMaster` associated to the sanToken
/// @param collateral Token to deposit
/// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like
/// `deposit` and then `stake
function deposit(
address user,
uint256 amount,
address stablecoin,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_deposit(user, amount, false, stablecoin, collateral, IPoolManager(address(0)), ISanToken(address(0)));
}
/// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the `_deposit` method to deposit collateral as a SLP in the protocol
/// Allows to deposit a collateral within the protocol
/// @param user Address where to send the resulting sanTokens, if this address is the router address then it means
/// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action
/// @param amount Amount of collateral to deposit
/// @param stableMaster `StableMaster` associated to the sanToken
/// @param collateral Token to deposit
/// @param poolManager PoolManager associated to the sanToken
/// @param sanToken SanToken associated to the `collateral` and `stableMaster`
/// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like
/// `deposit` and then `stake`
function deposit(
address user,
uint256 amount,
address stableMaster,
address collateral,
IPoolManager poolManager,
ISanToken sanToken
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_deposit(user, amount, true, stableMaster, collateral, poolManager, sanToken);
}
/// @notice Wrapper built on top of the `_openPerpetual` method to open a perpetual with the protocol
/// @param collateral Here the collateral should not be null (even if `addressProcessed` is true) for the router
/// to be able to know how to deposit collateral
/// @dev `stablecoinOrPerpetualManager` should be the address of the agToken (= stablecoin) is `addressProcessed` is false
/// and the associated `perpetualManager` otherwise
function openPerpetual(
address owner,
uint256 margin,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), margin);
_openPerpetual(
owner,
margin,
amountCommitted,
maxOracleRate,
minNetMargin,
addressProcessed,
stablecoinOrPerpetualManager,
collateral
);
}
/// @notice Wrapper built on top of the `_addToPerpetual` method to add collateral to a perpetual with the protocol
/// @param collateral Here the collateral should not be null (even if `addressProcessed is true) for the router
/// to be able to know how to deposit collateral
/// @dev `stablecoinOrPerpetualManager` should be the address of the agToken is `addressProcessed` is false and the associated
/// `perpetualManager` otherwise
function addToPerpetual(
uint256 margin,
uint256 perpetualID,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), margin);
_addToPerpetual(margin, perpetualID, addressProcessed, stablecoinOrPerpetualManager, collateral);
}
/// @notice Allows composable calls to different functions within the protocol
/// @param paramsPermit Array of params `PermitType` used to do a 1 tx to approve the router on each token (can be done once by
/// setting high approved amounts) which supports the `permit` standard. Users willing to interact with the contract
/// with tokens that do not support permit should approve the contract for these tokens prior to interacting with it
/// @param paramsTransfer Array of params `TransferType` used to transfer tokens to the router
/// @param paramsSwap Array of params `ParamsSwapType` used to swap tokens
/// @param actions List of actions to be performed by the router (in order of execution): make sure to read for each action the
/// associated internal function
/// @param datas Array of encoded data for each of the actions performed in this mixer. This is where the bytes-encoded parameters
/// for a given action are stored
/// @dev This function first fills the router balances via transfers and swaps. It then proceeds with each
/// action in the order at which they are given
/// @dev With this function, users can specify paths to swap tokens to the desired token of their choice. Yet the protocol
/// does not verify the payload given and cannot check that the swap performed by users actually gives the desired
/// out token: in this case funds will be lost by the user
/// @dev For some actions (`mint`, `deposit`, `openPerpetual`, `addToPerpetual`, `withdraw`), users are
/// required to give a proportion of the amount of token they have brought to the router within the transaction (through
/// a direct transfer or a swap) they want to use for the operation. If you want to use all the USDC you have brought (through an ETH -> USDC)
/// swap to mint stablecoins for instance, you should use `BASE_PARAMS` as a proportion.
/// @dev The proportion that is specified for an action is a proportion of what is left. If you want to use 50% of your USDC for a `mint`
/// and the rest for an `openPerpetual`, proportion used for the `mint` should be 50% (that is `BASE_PARAMS/2`), and proportion
/// for the `openPerpetual` should be all that is left that is 100% (= `BASE_PARAMS`).
/// @dev For each action here, make sure to read the documentation of the associated internal function to know how to correctly
/// specify parameters
function mixer(
PermitType[] memory paramsPermit,
TransferType[] memory paramsTransfer,
ParamsSwapType[] memory paramsSwap,
ActionType[] memory actions,
bytes[] calldata datas
) external payable nonReentrant {
// Do all the permits once for all: if all tokens have already been approved, there's no need for this step
for (uint256 i = 0; i < paramsPermit.length; i++) {
IERC20PermitUpgradeable(paramsPermit[i].token).permit(
paramsPermit[i].owner,
address(this),
paramsPermit[i].value,
paramsPermit[i].deadline,
paramsPermit[i].v,
paramsPermit[i].r,
paramsPermit[i].s
);
}
// Then, do all the transfer to load all needed funds into the router
// This function is limited to 10 different assets to be spent on the protocol (agTokens, collaterals, sanTokens)
address[_MAX_TOKENS] memory listTokens;
uint256[_MAX_TOKENS] memory balanceTokens;
for (uint256 i = 0; i < paramsTransfer.length; i++) {
paramsTransfer[i].inToken.safeTransferFrom(msg.sender, address(this), paramsTransfer[i].amountIn);
_addToList(listTokens, balanceTokens, address(paramsTransfer[i].inToken), paramsTransfer[i].amountIn);
}
for (uint256 i = 0; i < paramsSwap.length; i++) {
// Caution here: if the args are not set such that end token is the params `paramsSwap[i].collateral`,
// then the funds will be lost, and any user could take advantage of it to fetch the funds
uint256 amountOut = _transferAndSwap(
paramsSwap[i].inToken,
paramsSwap[i].amountIn,
paramsSwap[i].minAmountOut,
paramsSwap[i].swapType,
paramsSwap[i].args
);
_addToList(listTokens, balanceTokens, address(paramsSwap[i].collateral), amountOut);
}
// Performing actions one after the others
for (uint256 i = 0; i < actions.length; i++) {
if (actions[i] == ActionType.claimRewards) {
(
address user,
uint256 proportionToBeTransferred,
address[] memory claimLiquidityGauges,
uint256[] memory claimPerpetualIDs,
bool addressProcessed,
address[] memory stablecoins,
address[] memory collateralsOrPerpetualManagers
) = abi.decode(datas[i], (address, uint256, address[], uint256[], bool, address[], address[]));
uint256 amount = ANGLE.balanceOf(user);
_claimRewards(
user,
claimLiquidityGauges,
claimPerpetualIDs,
addressProcessed,
stablecoins,
collateralsOrPerpetualManagers
);
if (proportionToBeTransferred > 0) {
amount = ANGLE.balanceOf(user) - amount;
amount = (amount * proportionToBeTransferred) / BASE_PARAMS;
ANGLE.safeTransferFrom(msg.sender, address(this), amount);
_addToList(listTokens, balanceTokens, address(ANGLE), amount);
}
} else if (actions[i] == ActionType.claimWeeklyInterest) {
(address user, address feeDistributor, bool letInContract) = abi.decode(
datas[i],
(address, address, bool)
);
(uint256 amount, IERC20 token) = _claimWeeklyInterest(
user,
IFeeDistributorFront(feeDistributor),
letInContract
);
if (address(token) != address(0)) _addToList(listTokens, balanceTokens, address(token), amount);
// In all the following action, the `amount` variable represents the proportion of the
// balance that needs to be used for this action (in `BASE_PARAMS`)
// We name it `amount` here to save some new variable declaration costs
} else if (actions[i] == ActionType.veANGLEDeposit) {
(address user, uint256 amount) = abi.decode(datas[i], (address, uint256));
amount = _computeProportion(amount, listTokens, balanceTokens, address(ANGLE));
_depositOnLocker(user, amount);
} else if (actions[i] == ActionType.gaugeDeposit) {
(address user, uint256 amount, address stakedToken, address gauge, bool shouldClaimRewards) = abi
.decode(datas[i], (address, uint256, address, address, bool));
amount = _computeProportion(amount, listTokens, balanceTokens, stakedToken);
_gaugeDeposit(user, amount, ILiquidityGauge(gauge), shouldClaimRewards);
} else if (actions[i] == ActionType.deposit) {
(
address user,
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
address poolManager,
address sanToken
) = abi.decode(datas[i], (address, uint256, bool, address, address, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
(amount, sanToken) = _deposit(
user,
amount,
addressProcessed,
stablecoinOrStableMaster,
collateral,
IPoolManager(poolManager),
ISanToken(sanToken)
);
if (amount > 0) _addToList(listTokens, balanceTokens, sanToken, amount);
} else if (actions[i] == ActionType.withdraw) {
(
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateralOrPoolManager,
address sanToken
) = abi.decode(datas[i], (uint256, bool, address, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, sanToken);
// Reusing the `collateralOrPoolManager` variable to save some variable declarations
(amount, collateralOrPoolManager) = _withdraw(
amount,
addressProcessed,
stablecoinOrStableMaster,
collateralOrPoolManager
);
_addToList(listTokens, balanceTokens, collateralOrPoolManager, amount);
} else if (actions[i] == ActionType.mint) {
(
address user,
uint256 amount,
uint256 minStableAmount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
address poolManager
) = abi.decode(datas[i], (address, uint256, uint256, bool, address, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
_mint(
user,
amount,
minStableAmount,
addressProcessed,
stablecoinOrStableMaster,
collateral,
IPoolManager(poolManager)
);
} else if (actions[i] == ActionType.openPerpetual) {
(
address user,
uint256 amount,
uint256 amountCommitted,
uint256 extremeRateOracle,
uint256 minNetMargin,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) = abi.decode(datas[i], (address, uint256, uint256, uint256, uint256, bool, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
_openPerpetual(
user,
amount,
amountCommitted,
extremeRateOracle,
minNetMargin,
addressProcessed,
stablecoinOrPerpetualManager,
collateral
);
} else if (actions[i] == ActionType.addToPerpetual) {
(
uint256 amount,
uint256 perpetualID,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) = abi.decode(datas[i], (uint256, uint256, bool, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
_addToPerpetual(amount, perpetualID, addressProcessed, stablecoinOrPerpetualManager, collateral);
}
}
// Once all actions have been performed, the router sends back the unused funds from users
// If a user sends funds (through a swap) but specifies incorrectly the collateral associated to it, then the mixer will revert
// When trying to send remaining funds back
for (uint256 i = 0; i < balanceTokens.length; i++) {
if (balanceTokens[i] > 0) IERC20(listTokens[i]).safeTransfer(msg.sender, balanceTokens[i]);
}
}
receive() external payable {}
// ======================== Internal Utility Functions =========================
// Most internal utility functions have a wrapper built on top of it
/// @notice Internal version of the `claimRewards` function
/// Allows to claim rewards for multiple gauges and perpetuals at once
/// @param gaugeUser Address for which to fetch the rewards from the gauges
/// @param liquidityGauges Gauges to claim on
/// @param perpetualIDs Perpetual IDs to claim rewards for
/// @param addressProcessed Whether `PerpetualManager` list is already accessible in `collateralsOrPerpetualManagers`vor if it should be
/// retrieved from `stablecoins` and `collateralsOrPerpetualManagers`
/// @param stablecoins Stablecoin contracts linked to the perpetualsIDs. Array of zero addresses if addressProcessed is true
/// @param collateralsOrPerpetualManagers Collateral contracts linked to the perpetualsIDs or `perpetualManager` contracts if
/// `addressProcessed` is true
/// @dev If the caller wants to send the rewards to another account than `gaugeUser` it first needs to
/// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge`
/// @dev The function only takes rewards received by users,
function _claimRewards(
address gaugeUser,
address[] memory liquidityGauges,
uint256[] memory perpetualIDs,
bool addressProcessed,
address[] memory stablecoins,
address[] memory collateralsOrPerpetualManagers
) internal {
require(
stablecoins.length == perpetualIDs.length && collateralsOrPerpetualManagers.length == perpetualIDs.length,
"104"
);
for (uint256 i = 0; i < liquidityGauges.length; i++) {
ILiquidityGauge(liquidityGauges[i]).claim_rewards(gaugeUser);
}
for (uint256 i = 0; i < perpetualIDs.length; i++) {
IPerpetualManagerFrontWithClaim perpManager;
if (addressProcessed) perpManager = IPerpetualManagerFrontWithClaim(collateralsOrPerpetualManagers[i]);
else {
(, Pairs memory pairs) = _getInternalContracts(
IERC20(stablecoins[i]),
IERC20(collateralsOrPerpetualManagers[i])
);
perpManager = pairs.perpetualManager;
}
perpManager.getReward(perpetualIDs[i]);
}
}
/// @notice Allows to deposit ANGLE on an existing locker
/// @param user Address to deposit for
/// @param amount Amount to deposit
function _depositOnLocker(address user, uint256 amount) internal {
VEANGLE.deposit_for(user, amount);
}
/// @notice Allows to claim weekly interest distribution and if wanted to transfer it to the `angleRouter` for future use
/// @param user Address to claim for
/// @param _feeDistributor Address of the fee distributor to claim to
/// @dev If funds are transferred to the router, this action cannot be an end in itself, otherwise funds will be lost:
/// typically we expect people to call for this action before doing a deposit
/// @dev If `letInContract` (and hence if funds are transferred to the router), you should approve the `angleRouter` to
/// transfer the token claimed from the `feeDistributor`
function _claimWeeklyInterest(
address user,
IFeeDistributorFront _feeDistributor,
bool letInContract
) internal returns (uint256 amount, IERC20 token) {
amount = _feeDistributor.claim(user);
if (letInContract) {
// Fetching info from the `FeeDistributor` to process correctly the withdrawal
token = IERC20(_feeDistributor.token());
token.safeTransferFrom(msg.sender, address(this), amount);
} else {
amount = 0;
}
}
/// @notice Internal version of the `gaugeDeposit` function
/// Allows to deposit tokens into a gauge
/// @param user Address on behalf of which deposit should be made in the gauge
/// @param amount Amount to stake
/// @param gauge LiquidityGauge to stake in
/// @param shouldClaimRewards Whether to claim or not previously accumulated rewards
/// @dev You should be cautious on who will receive the rewards (if `shouldClaimRewards` is true)
/// It can be set on each gauge
/// @dev In the `mixer`, before calling for this action, user should have made sure to get in the router
/// the associated token (by like a `deposit` action)
/// @dev The function will revert if the gauge has not already been approved by the contract
function _gaugeDeposit(
address user,
uint256 amount,
ILiquidityGauge gauge,
bool shouldClaimRewards
) internal {
gauge.deposit(amount, user, shouldClaimRewards);
}
/// @notice Internal version of the `mint` functions
/// Mints stablecoins from the protocol
/// @param user Address to send the stablecoins to
/// @param amount Amount of collateral to use for the mint
/// @param minStableAmount Minimum stablecoin minted for the tx not to revert
/// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
/// @dev This function is not designed to be composable with other actions of the router after it's called: like
/// stablecoins obtained from it cannot be used for other operations: as such the `user` address should not be the router
/// address
function _mint(
address user,
uint256 amount,
uint256 minStableAmount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager
) internal {
IStableMasterFront stableMaster;
(stableMaster, poolManager) = _mintBurnContracts(
addressProcessed,
stablecoinOrStableMaster,
collateral,
poolManager
);
stableMaster.mint(amount, user, poolManager, minStableAmount);
}
/// @notice Burns stablecoins from the protocol
/// @param dest Address who will receive the proceeds
/// @param amount Amount of collateral to use for the mint
/// @param minCollatAmount Minimum Collateral minted for the tx not to revert
/// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
function _burn(
address dest,
uint256 amount,
uint256 minCollatAmount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager
) internal {
IStableMasterFront stableMaster;
(stableMaster, poolManager) = _mintBurnContracts(
addressProcessed,
stablecoinOrStableMaster,
collateral,
poolManager
);
stableMaster.burn(amount, msg.sender, dest, poolManager, minCollatAmount);
}
/// @notice Internal version of the `deposit` functions
/// Allows to deposit a collateral within the protocol
/// @param user Address where to send the resulting sanTokens, if this address is the router address then it means
/// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action
/// @param amount Amount of collateral to deposit
/// @param addressProcessed Whether `msg.sender` provided the contracts addresses or the tokens ones
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Token to deposit: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
/// @param sanToken SanToken associated to the `collateral` (null if `addressProcessed` is not true)
/// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like
/// `deposit` and then `stake`
function _deposit(
address user,
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager,
ISanToken sanToken
) internal returns (uint256 addedAmount, address) {
IStableMasterFront stableMaster;
if (addressProcessed) {
stableMaster = IStableMasterFront(stablecoinOrStableMaster);
} else {
Pairs memory pairs;
(stableMaster, pairs) = _getInternalContracts(IERC20(stablecoinOrStableMaster), IERC20(collateral));
poolManager = pairs.poolManager;
sanToken = pairs.sanToken;
}
if (user == address(this)) {
// Computing the amount of sanTokens obtained
addedAmount = sanToken.balanceOf(address(this));
stableMaster.deposit(amount, address(this), poolManager);
addedAmount = sanToken.balanceOf(address(this)) - addedAmount;
} else {
stableMaster.deposit(amount, user, poolManager);
}
return (addedAmount, address(sanToken));
}
/// @notice Withdraws sanTokens from the protocol
/// @param amount Amount of sanTokens to withdraw
/// @param addressProcessed Whether `msg.sender` provided the contracts addresses or the tokens ones
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateralOrPoolManager Collateral to withdraw (if `addressProcessed` is false) or directly
/// the `PoolManager` contract if `addressProcessed`
function _withdraw(
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateralOrPoolManager
) internal returns (uint256 withdrawnAmount, address) {
IStableMasterFront stableMaster;
// Stores the address of the `poolManager`, while `collateralOrPoolManager` is used in the function
// to store the `collateral` address
IPoolManager poolManager;
if (addressProcessed) {
stableMaster = IStableMasterFront(stablecoinOrStableMaster);
poolManager = IPoolManager(collateralOrPoolManager);
collateralOrPoolManager = poolManager.token();
} else {
Pairs memory pairs;
(stableMaster, pairs) = _getInternalContracts(
IERC20(stablecoinOrStableMaster),
IERC20(collateralOrPoolManager)
);
poolManager = pairs.poolManager;
}
// Here reusing the `withdrawnAmount` variable to avoid a stack too deep problem
withdrawnAmount = IERC20(collateralOrPoolManager).balanceOf(address(this));
// This call will increase our collateral balance
stableMaster.withdraw(amount, address(this), address(this), poolManager);
// We compute the difference between our collateral balance after and before the `withdraw` call
withdrawnAmount = IERC20(collateralOrPoolManager).balanceOf(address(this)) - withdrawnAmount;
return (withdrawnAmount, collateralOrPoolManager);
}
/// @notice Internal version of the `openPerpetual` function
/// Opens a perpetual within Angle
/// @param owner Address to mint perpetual for
/// @param margin Margin to open the perpetual with
/// @param amountCommitted Commit amount in the perpetual
/// @param maxOracleRate Maximum oracle rate required to have a leverage position opened
/// @param minNetMargin Minimum net margin required to have a leverage position opened
/// @param addressProcessed Whether msg.sender provided the contracts addresses or the tokens ones
/// @param stablecoinOrPerpetualManager Token associated to the `StableMaster` (iif `addressProcessed` is false)
/// or address of the desired `PerpetualManager` (if `addressProcessed` is true)
/// @param collateral Collateral to mint from (it can be null if `addressProcessed` is true): it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit
function _openPerpetual(
address owner,
uint256 margin,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) internal returns (uint256 perpetualID) {
if (!addressProcessed) {
(, Pairs memory pairs) = _getInternalContracts(IERC20(stablecoinOrPerpetualManager), IERC20(collateral));
stablecoinOrPerpetualManager = address(pairs.perpetualManager);
}
return
IPerpetualManagerFrontWithClaim(stablecoinOrPerpetualManager).openPerpetual(
owner,
margin,
amountCommitted,
maxOracleRate,
minNetMargin
);
}
/// @notice Internal version of the `addToPerpetual` function
/// Adds collateral to a perpetual
/// @param margin Amount of collateral to add
/// @param perpetualID Perpetual to add collateral to
/// @param addressProcessed Whether msg.sender provided the contracts addresses or the tokens ones
/// @param stablecoinOrPerpetualManager Token associated to the `StableMaster` (iif `addressProcessed` is false)
/// or address of the desired `PerpetualManager` (if `addressProcessed` is true)
/// @param collateral Collateral to mint from (it can be null if `addressProcessed` is true): it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit
function _addToPerpetual(
uint256 margin,
uint256 perpetualID,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) internal {
if (!addressProcessed) {
(, Pairs memory pairs) = _getInternalContracts(IERC20(stablecoinOrPerpetualManager), IERC20(collateral));
stablecoinOrPerpetualManager = address(pairs.perpetualManager);
}
IPerpetualManagerFrontWithClaim(stablecoinOrPerpetualManager).addToPerpetual(perpetualID, margin);
}
// ======================== Internal Utility Functions =========================
/// @notice Checks if collateral in the list
/// @param list List of addresses
/// @param searchFor Address of interest
/// @return index Place of the address in the list if it is in or current length otherwise
function _searchList(address[_MAX_TOKENS] memory list, address searchFor) internal pure returns (uint256 index) {
uint256 i;
while (i < list.length && list[i] != address(0)) {
if (list[i] == searchFor) return i;
i++;
}
return i;
}
/// @notice Modifies stored balances for a given collateral
/// @param list List of collateral addresses
/// @param balances List of balances for the different supported collateral types
/// @param searchFor Address of the collateral of interest
/// @param amount Amount to add in the balance for this collateral
function _addToList(
address[_MAX_TOKENS] memory list,
uint256[_MAX_TOKENS] memory balances,
address searchFor,
uint256 amount
) internal pure {
uint256 index = _searchList(list, searchFor);
// add it to the list if non existent and we add tokens
if (list[index] == address(0)) list[index] = searchFor;
balances[index] += amount;
}
/// @notice Computes the proportion of the collateral leftover balance to use for a given action
/// @param proportion Ratio to take from balance
/// @param list Collateral list
/// @param balances Balances of each collateral asset in the collateral list
/// @param searchFor Collateral to look for
/// @return amount Amount to use for the action (based on the proportion given)
/// @dev To use all the collateral balance available for an action, users should give `proportion` a value of
/// `BASE_PARAMS`
function _computeProportion(
uint256 proportion,
address[_MAX_TOKENS] memory list,
uint256[_MAX_TOKENS] memory balances,
address searchFor
) internal pure returns (uint256 amount) {
uint256 index = _searchList(list, searchFor);
// Reverts if the index was not found
require(list[index] != address(0), "33");
amount = (proportion * balances[index]) / BASE_PARAMS;
balances[index] -= amount;
}
/// @notice Gets Angle contracts associated to a pair (stablecoin, collateral)
/// @param stablecoin Token associated to a `StableMaster`
/// @param collateral Collateral to mint/deposit/open perpetual or add collateral from
/// @dev This function is used to check that the parameters passed by people calling some of the main
/// router functions are correct
function _getInternalContracts(IERC20 stablecoin, IERC20 collateral)
internal
view
returns (IStableMasterFront stableMaster, Pairs memory pairs)
{
stableMaster = mapStableMasters[stablecoin];
pairs = mapPoolManagers[stableMaster][collateral];
// If `stablecoin` is zero then this necessarily means that `stableMaster` here will be 0
// Similarly, if `collateral` is zero, then this means that `pairs.perpetualManager`, `pairs.poolManager`
// and `pairs.sanToken` will be zero
// Last, if any of `pairs.perpetualManager`, `pairs.poolManager` or `pairs.sanToken` is zero, this means
// that all others should be null from the `addPairs` and `removePairs` functions which keep this invariant
require(address(stableMaster) != address(0) && address(pairs.poolManager) != address(0), "0");
return (stableMaster, pairs);
}
/// @notice Get contracts for mint and burn actions
/// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
function _mintBurnContracts(
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager
) internal view returns (IStableMasterFront, IPoolManager) {
IStableMasterFront stableMaster;
if (addressProcessed) {
stableMaster = IStableMasterFront(stablecoinOrStableMaster);
} else {
Pairs memory pairs;
(stableMaster, pairs) = _getInternalContracts(IERC20(stablecoinOrStableMaster), IERC20(collateral));
poolManager = pairs.poolManager;
}
return (stableMaster, poolManager);
}
/// @notice Adds new collateral type to specific stablecoin
/// @param stableMaster Address of the `StableMaster` associated to the stablecoin of interest
/// @param poolManager Address of the `PoolManager` contract associated to the pair (stablecoin,collateral)
/// @param liquidityGauge Address of liquidity gauge contract associated to sanToken
function _addPair(
IStableMasterFront stableMaster,
IPoolManager poolManager,
ILiquidityGauge liquidityGauge
) internal {
// Fetching the associated `sanToken` and `perpetualManager` from the contract
(IERC20 collateral, ISanToken sanToken, IPerpetualManager perpetualManager, , , , , , ) = IStableMaster(
address(stableMaster)
).collateralMap(poolManager);
Pairs storage _pairs = mapPoolManagers[stableMaster][collateral];
// Checking if the pair has not already been initialized: if yes we need to make the function revert
// otherwise we could end up with still approved `PoolManager` and `PerpetualManager` contracts
require(address(_pairs.poolManager) == address(0), "114");
_pairs.poolManager = poolManager;
_pairs.perpetualManager = IPerpetualManagerFrontWithClaim(address(perpetualManager));
_pairs.sanToken = sanToken;
// In the future, it is possible that sanTokens do not have an associated liquidity gauge
if (address(liquidityGauge) != address(0)) {
require(address(sanToken) == liquidityGauge.staking_token(), "20");
_pairs.gauge = liquidityGauge;
sanToken.approve(address(liquidityGauge), type(uint256).max);
}
_changeAllowance(collateral, address(stableMaster), type(uint256).max);
_changeAllowance(collateral, address(perpetualManager), type(uint256).max);
emit CollateralToggled(address(stableMaster), address(poolManager), address(liquidityGauge));
}
/// @notice Changes allowance of this contract for a given token
/// @param token Address of the token to change allowance
/// @param spender Address to change the allowance of
/// @param amount Amount allowed
function _changeAllowance(
IERC20 token,
address spender,
uint256 amount
) internal {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < amount) {
token.safeIncreaseAllowance(spender, amount - currentAllowance);
} else if (currentAllowance > amount) {
token.safeDecreaseAllowance(spender, currentAllowance - amount);
}
}
/// @notice Transfers collateral or an arbitrary token which is then swapped on UniswapV3 or on 1Inch
/// @param inToken Token to swap for the collateral
/// @param amount Amount of in token to swap for the collateral
/// @param minAmountOut Minimum amount accepted for the swap to happen
/// @param swapType Choice on which contracts to swap
/// @param args Bytes representing either the path to swap your input token to the accepted collateral on Uniswap or payload for 1Inch
/// @dev The `path` provided is not checked, meaning people could swap for a token A and declare that they've swapped for another token B.
/// However, the mixer manipulates its token balance only through the addresses registered in `listTokens`, so any subsequent mixer action
/// trying to transfer funds B will do it through address of token A and revert as A is not actually funded.
/// In case there is not subsequent action, `mixer` will revert when trying to send back what appears to be remaining tokens A.
function _transferAndSwap(
IERC20 inToken,
uint256 amount,
uint256 minAmountOut,
SwapType swapType,
bytes memory args
) internal returns (uint256 amountOut) {
if (address(inToken) == address(WETH9) && address(this).balance >= amount) {
WETH9.deposit{ value: amount }(); // wrap only what is needed to pay
} else {
inToken.safeTransferFrom(msg.sender, address(this), amount);
}
if (swapType == SwapType.UniswapV3) amountOut = _swapOnUniswapV3(inToken, amount, minAmountOut, args);
else if (swapType == SwapType.oneINCH) amountOut = _swapOn1Inch(inToken, minAmountOut, args);
else require(false, "3");
return amountOut;
}
/// @notice Allows to swap any token to an accepted collateral via UniswapV3 (if there is a path)
/// @param inToken Address token used as entrance of the swap
/// @param amount Amount of in token to swap for the accepted collateral
/// @param minAmountOut Minimum amount accepted for the swap to happen
/// @param path Bytes representing the path to swap your input token to the accepted collateral
function _swapOnUniswapV3(
IERC20 inToken,
uint256 amount,
uint256 minAmountOut,
bytes memory path
) internal returns (uint256 amountOut) {
// Approve transfer to the `uniswapV3Router` if it is the first time that the token is used
if (!uniAllowedToken[inToken]) {
inToken.safeIncreaseAllowance(address(uniswapV3Router), type(uint256).max);
uniAllowedToken[inToken] = true;
}
amountOut = uniswapV3Router.exactInput(
ExactInputParams(path, address(this), block.timestamp, amount, minAmountOut)
);
}
/// @notice Allows to swap any token to an accepted collateral via 1Inch API
/// @param minAmountOut Minimum amount accepted for the swap to happen
/// @param payload Bytes needed for 1Inch API
function _swapOn1Inch(
IERC20 inToken,
uint256 minAmountOut,
bytes memory payload
) internal returns (uint256 amountOut) {
// Approve transfer to the `oneInch` router if it is the first time the token is used
if (!oneInchAllowedToken[inToken]) {
inToken.safeIncreaseAllowance(address(oneInch), type(uint256).max);
oneInchAllowedToken[inToken] = true;
}
//solhint-disable-next-line
(bool success, bytes memory result) = oneInch.call(payload);
if (!success) _revertBytes(result);
amountOut = abi.decode(result, (uint256));
require(amountOut >= minAmountOut, "15");
}
/// @notice Internal function used for error handling
function _revertBytes(bytes memory errMsg) internal pure {
if (errMsg.length > 0) {
//solhint-disable-next-line
assembly {
revert(add(32, errMsg), mload(errMsg))
}
}
revert("117");
}
}
// 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 Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
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 `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.8.0;
import "../IERC20.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 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");
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IFeeDistributor
/// @author Interface of the `FeeDistributor` contract
/// @dev This interface is used by the `SurplusConverter` contract to send funds to the `FeeDistributor`
interface IFeeDistributor {
function burn(address token) external;
}
/// @title IFeeDistributorFront
/// @author Interface for public use of the `FeeDistributor` contract
/// @dev This interface is used for user related function
interface IFeeDistributorFront {
function token() external returns (address);
function claim(address _addr) external returns (uint256);
function claim(address[20] memory _addr) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
interface ILiquidityGauge {
// solhint-disable-next-line
function staking_token() external returns (address stakingToken);
// solhint-disable-next-line
function deposit_reward_token(address _rewardToken, uint256 _amount) external;
function deposit(
uint256 _value,
address _addr,
// solhint-disable-next-line
bool _claim_rewards
) external;
// solhint-disable-next-line
function claim_rewards(address _addr) external;
// solhint-disable-next-line
function claim_rewards(address _addr, address _receiver) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title ISanToken
/// @author Angle Core Team
/// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs
/// contributing to a collateral for a given stablecoin
interface ISanToken is IERC20Upgradeable {
// ================================== StableMaster =============================
function mint(address account, uint256 amount) external;
function burnFrom(
uint256 amount,
address burner,
address sender
) external;
function burnSelf(uint256 amount, address burner) external;
function stableMaster() external view returns (address);
function poolManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Normally just importing `IPoolManager` should be sufficient, but for clarity here
// we prefer to import all concerned interfaces
import "./IPoolManager.sol";
import "./IOracle.sol";
import "./IPerpetualManager.sol";
import "./ISanToken.sol";
// Struct to handle all the parameters to manage the fees
// related to a given collateral pool (associated to the stablecoin)
struct MintBurnData {
// Values of the thresholds to compute the minting fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeMint;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeMint;
// Values of the thresholds to compute the burning fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeBurn;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeBurn;
// Max proportion of collateral from users that can be covered by HAs
// It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated
// the other changes accordingly
uint64 targetHAHedge;
// Minting fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusMint;
// Burning fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusBurn;
// Parameter used to limit the number of stablecoins that can be issued using the concerned collateral
uint256 capOnStableMinted;
}
// Struct to handle all the variables and parameters to handle SLPs in the protocol
// including the fraction of interests they receive or the fees to be distributed to
// them
struct SLPData {
// Last timestamp at which the `sanRate` has been updated for SLPs
uint256 lastBlockUpdated;
// Fees accumulated from previous blocks and to be distributed to SLPs
uint256 lockedInterests;
// Max interests used to update the `sanRate` in a single block
// Should be in collateral token base
uint256 maxInterestsDistributed;
// Amount of fees left aside for SLPs and that will be distributed
// when the protocol is collateralized back again
uint256 feesAside;
// Part of the fees normally going to SLPs that is left aside
// before the protocol is collateralized back again (depends on collateral ratio)
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippageFee;
// Portion of the fees from users minting and burning
// that goes to SLPs (the rest goes to surplus)
uint64 feesForSLPs;
// Slippage factor that's applied to SLPs exiting (depends on collateral ratio)
// If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippage;
// Portion of the interests from lending
// that goes to SLPs (the rest goes to surplus)
uint64 interestsForSLPs;
}
/// @title IStableMasterFunctions
/// @author Angle Core Team
/// @notice Interface for the `StableMaster` contract
interface IStableMasterFunctions {
function deploy(
address[] memory _governorList,
address _guardian,
address _agToken
) external;
// ============================== Lending ======================================
function accumulateInterest(uint256 gain) external;
function signalLoss(uint256 loss) external;
// ============================== HAs ==========================================
function getStocksUsers() external view returns (uint256 maxCAmountInStable);
function convertToSLP(uint256 amount, address user) external;
// ============================== Keepers ======================================
function getCollateralRatio() external returns (uint256);
function setFeeKeeper(
uint64 feeMint,
uint64 feeBurn,
uint64 _slippage,
uint64 _slippageFee
) external;
// ============================== AgToken ======================================
function updateStocksUsers(uint256 amount, address poolManager) external;
// ============================= Governance ====================================
function setCore(address newCore) external;
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address newGuardian, address oldGuardian) external;
function revokeGuardian(address oldGuardian) external;
function setCapOnStableAndMaxInterests(
uint256 _capOnStableMinted,
uint256 _maxInterestsDistributed,
IPoolManager poolManager
) external;
function setIncentivesForSLPs(
uint64 _feesForSLPs,
uint64 _interestsForSLPs,
IPoolManager poolManager
) external;
function setUserFees(
IPoolManager poolManager,
uint64[] memory _xFee,
uint64[] memory _yFee,
uint8 _mint
) external;
function setTargetHAHedge(uint64 _targetHAHedge) external;
function pause(bytes32 agent, IPoolManager poolManager) external;
function unpause(bytes32 agent, IPoolManager poolManager) external;
}
/// @title IStableMaster
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
interface IStableMaster is IStableMasterFunctions {
function agToken() external view returns (address);
function collateralMap(IPoolManager poolManager)
external
view
returns (
IERC20 token,
ISanToken sanToken,
IPerpetualManager perpetualManager,
IOracle oracle,
uint256 stocksUsers,
uint256 sanRate,
uint256 collatBase,
SLPData memory slpData,
MintBurnData memory feeData
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "../interfaces/IPoolManager.sol";
/// @title IStableMasterFront
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IStableMasterFront {
function mint(
uint256 amount,
address user,
IPoolManager poolManager,
uint256 minStableAmount
) external;
function burn(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager,
uint256 minCollatAmount
) external;
function deposit(
uint256 amount,
address user,
IPoolManager poolManager
) external;
function withdraw(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager
) external;
function agToken() external returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title IVeANGLE
/// @author Angle Core Team
/// @notice Interface for the `VeANGLE` contract
interface IVeANGLE {
// solhint-disable-next-line func-name-mixedcase
function deposit_for(address addr, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IUniswapV3Router {
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
}
/// @title Router for price estimation functionality
/// @notice Functions for getting the price of one token with respect to another using Uniswap V2
/// @dev This interface is only used for non critical elements of the protocol
interface IUniswapV2Router {
/// @notice Given an input asset amount, returns the maximum output amount of the
/// other asset (accounting for fees) given reserves.
/// @param path Addresses of the pools used to get prices
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 swapAmount,
uint256 minExpected,
address[] calldata path,
address receiver,
uint256 swapDeadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^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;
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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @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: GPL-3.0
pragma solidity ^0.8.7;
import "./IFeeManager.sol";
import "./IPerpetualManager.sol";
import "./IOracle.sol";
// Struct for the parameters associated to a strategy interacting with a collateral `PoolManager`
// contract
struct StrategyParams {
// Timestamp of last report made by this strategy
// It is also used to check if a strategy has been initialized
uint256 lastReport;
// Total amount the strategy is expected to have
uint256 totalStrategyDebt;
// The share of the total assets in the `PoolManager` contract that the `strategy` can access to.
uint256 debtRatio;
}
/// @title IPoolManagerFunctions
/// @author Angle Core Team
/// @notice Interface for the collateral poolManager contracts handling each one type of collateral for
/// a given stablecoin
/// @dev Only the functions used in other contracts of the protocol are left here
interface IPoolManagerFunctions {
// ============================ Constructor ====================================
function deployCollateral(
address[] memory governorList,
address guardian,
IPerpetualManager _perpetualManager,
IFeeManager feeManager,
IOracle oracle
) external;
// ============================ Yield Farming ==================================
function creditAvailable() external view returns (uint256);
function debtOutstanding() external view returns (uint256);
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external;
// ============================ Governance =====================================
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address _guardian, address guardian) external;
function revokeGuardian(address guardian) external;
function setFeeManager(IFeeManager _feeManager) external;
// ============================= Getters =======================================
function getBalance() external view returns (uint256);
function getTotalAsset() external view returns (uint256);
}
/// @title IPoolManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev Used in other contracts of the protocol
interface IPoolManager is IPoolManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
function token() external view returns (address);
function feeManager() external view returns (address);
function totalDebt() external view returns (uint256);
function strategies(address _strategy) external view returns (StrategyParams memory);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IOracle
/// @author Angle Core Team
/// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink
/// from just UniswapV3 or from just Chainlink
interface IOracle {
function read() external view returns (uint256);
function readAll() external view returns (uint256 lowerRate, uint256 upperRate);
function readLower() external view returns (uint256);
function readUpper() external view returns (uint256);
function readQuote(uint256 baseAmount) external view returns (uint256);
function readQuoteLower(uint256 baseAmount) external view returns (uint256);
function inBase() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IERC721.sol";
import "./IFeeManager.sol";
import "./IOracle.sol";
import "./IAccessControl.sol";
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IPerpetualManagerFront is IERC721Metadata {
function openPerpetual(
address owner,
uint256 amountBrought,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin
) external returns (uint256 perpetualID);
function closePerpetual(
uint256 perpetualID,
address to,
uint256 minCashOutAmount
) external;
function addToPerpetual(uint256 perpetualID, uint256 amount) external;
function removeFromPerpetual(
uint256 perpetualID,
uint256 amount,
address to
) external;
function liquidatePerpetuals(uint256[] memory perpetualIDs) external;
function forceClosePerpetuals(uint256[] memory perpetualIDs) external;
// ========================= External View Functions =============================
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256);
function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool);
}
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev This interface does not contain user facing functions, it just has functions that are
/// interacted with in other parts of the protocol
interface IPerpetualManagerFunctions is IAccessControl {
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
IFeeManager feeManager,
IOracle oracle_
) external;
function setFeeManager(IFeeManager feeManager_) external;
function setHAFees(
uint64[] memory _xHAFees,
uint64[] memory _yHAFees,
uint8 deposit
) external;
function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external;
function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external;
function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external;
function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external;
function setLockTime(uint64 _lockTime) external;
function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external;
function pause() external;
function unpause() external;
// ==================================== Keepers ================================
function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external;
// =============================== StableMaster ================================
function setOracle(IOracle _oracle) external;
}
/// @title IPerpetualManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IPerpetualManager is IPerpetualManagerFunctions {
function poolManager() external view returns (address);
function oracle() external view returns (address);
function targetHAHedge() external view returns (uint64);
function totalHedgeAmount() external view returns (uint256);
}
/// @title Interface of the contract managing perpetuals with claim function
/// @author Angle Core Team
/// @dev Front interface with rewards function, meaning only user-facing functions
interface IPerpetualManagerFrontWithClaim is IPerpetualManagerFront, IPerpetualManager {
function getReward(uint256 perpetualID) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IAccessControl.sol";
/// @title IFeeManagerFunctions
/// @author Angle Core Team
/// @dev Interface for the `FeeManager` contract
interface IFeeManagerFunctions is IAccessControl {
// ================================= Keepers ===================================
function updateUsersSLP() external;
function updateHA() external;
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
address _perpetualManager
) external;
function setFees(
uint256[] memory xArray,
uint64[] memory yArray,
uint8 typeChange
) external;
function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external;
}
/// @title IFeeManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev We need these getters as they are used in other contracts of the protocol
interface IFeeManager is IFeeManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IAccessControl
/// @author Forked from OpenZeppelin
/// @notice Interface for `AccessControl` contracts
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
interface IERC721 is IERC165 {
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// 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 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);
}
|
Allows to deposit ANGLE on an existing locker user Address to deposit for amount Amount to deposit
|
function _depositOnLocker(address user, uint256 amount) internal {
VEANGLE.deposit_for(user, amount);
}
| 6,009,113
|
./partial_match/1/0x6B0B234fB2f380309D47A7E9391E29E9a179395a/sources/src/v0.8/llo-feeds/dev/RewardManager.sol
|
@inheritdoc IRewardManagercreate an array of poolIds to pass to _claimRewards if requiredloop all the reward recipients and claim their rewards before updating their weightsget the addressget the existing weightif the existing weight is 0, the recipient isn't part of this configurationif a recipient is updated, the rewards must be claimed first as they can't claim previous fees at the new weightkeep tally of the weights so that the expected collective weight is known
|
function updateRewardRecipients(
bytes32 poolId,
Common.AddressAndWeight[] calldata newRewardRecipients
) external override onlyOwner {
bytes32[] memory poolIds = new bytes32[](1);
poolIds[0] = poolId;
uint256 existingTotalWeight;
for (uint256 i; i < newRewardRecipients.length; ++i) {
address recipientAddress = newRewardRecipients[i].addr;
uint256 existingWeight = s_rewardRecipientWeights[poolId][recipientAddress];
if (existingWeight == 0) revert InvalidAddress();
_claimRewards(newRewardRecipients[i].addr, poolIds);
unchecked {
existingTotalWeight += existingWeight;
}
}
}
| 3,963,503
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
// Utilizes the useful mentions in the article below to address the pesky mint costs
// Credit where credit is due
// =============================================================================
// https://shiny.mirror.xyz/OUampBbIz9ebEicfGnQf5At_ReMHlZy0tB4glb9xQ0E
// =============================================================================
import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // NO MORE NUMERABLES
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Lovely_Raccs is ERC721, Ownable {
// vv Global Variables vv
using Strings for uint256;
// Comes with the gas update
// ====================================
using Counters for Counters.Counter;
Counters.Counter private supply;
// ====================================
string public uriPrefix = ""; // To be updated
string public uriSuffix = ".json";
string public hiddenMetadataUri;
// Does the greed hit?
uint256 public mintCost = 0.03 ether;
uint256 public publicCost = 0.05 ether;
uint256 public maxSupply = 10000; // Has known to show atleast double the amount of '0's in the test environment, uint256 thing?
uint256 public maxMintAmountPerTx = 2;
bool public paused = true;
bool public revealed = false;
constructor() ERC721("Lovely_Raccs", "LR") {
//setHiddenMetadataUri("ipfs://QmRRwj458iG6qTFHGDw9nrBLzKLtBhbM2u1jRBNnfyDyvM/TBR.json"); // Used for hiding the image in the metadata
setRevealed(true);
}
// Custom-made modifier for checking
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); // Minting too little or too many
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); // Supply has enough stock for current mint transaction
_;
}
function totalSupply() public view returns (uint256) { return supply.current(); } // Current total supply of tokens
function WLmint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { // Used for whitelist minting
require(!paused, "The contract is paused!");
require(msg.value >= mintCost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount); // Helper function below
}
function publicMint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { // Used for public minting
require(!paused, "The contract is paused!");
require(msg.value >= publicCost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
// Mints the token to a specific address (as opposed to the currently connected one)
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); }
// Grabs the wallet and wallet information of the owner and their tokens
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 <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
// Returns the given tokens URI address
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory)
{
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
if (revealed == false) { return hiddenMetadataUri; }
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : "";
}
function setRevealed(bool _state) public onlyOwner { revealed = _state; } // Hide/Unhide the metadata
function setMintCost(uint256 _cost) public onlyOwner { mintCost = _cost; } // Takes wei instead of ether V. IMPORTANT
function setPublicCost(uint256 _cost) public onlyOwner { publicCost = _cost; } // Takes wei instead of ether V. IMPORTANT
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; }
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; }
function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } // ipfs://<prefix>/<suffix>
function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; }
function setPaused(bool _state) public onlyOwner { paused = _state; } // Sets the pause state of the contract
function withdraw() public onlyOwner {
// This is an example split for 5% of the initial sale (using my own address).
// =============================================================================
//(bool hs, ) = payable(0xdFecCC7506725439a862AEfCF134C0B2a345AE5a).call{value: address(this).balance * 5 / 100}("");
//require(hs);
// =============================================================================
// This will transfer the remaining contract balance to the owner.
// Do not remove this otherwise your funds will be stuck in the ether.. literally. IMPORTANT.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
// Uses the OpenZeppelin minting method for safer transactions
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current()); }
}
// Returns the base contract prefix
function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; }
}
|
Used for public minting
|
function publicMint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
| 1,830,772
|
/**
*Submitted for verification at Etherscan.io on 2022-02-22
*/
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File contracts/interfaces/dao/ISmartWalletChecker.sol
pragma solidity 0.8.10;
interface ISmartWalletChecker {
function check(address _addr) external returns (bool);
}
// File contracts/interfaces/dao/ICollateralManager.sol
pragma solidity 0.8.10;
interface ICollateralManager {
function checkStatus(address _addr) external returns (bool);
}
// File contracts/interfaces/pool/IOwnership.sol
pragma solidity 0.8.10;
interface IOwnership {
function owner() external view returns (address);
function futureOwner() external view returns (address);
function commitTransferOwnership(address newOwner) external;
function acceptTransferOwnership() external;
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// OpenZeppelin Contracts v4.4.1 (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 `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/security/[email protected]
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^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() {
_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;
}
}
// File contracts/VotingEscrow.sol
pragma solidity 0.8.10;
/***
*@title VotingEscrow
*@author InsureDAO
* SPDX-License-Identifier: MIT
*@notice Votes have a weight depending on time, so that users are
* committed to the future of (whatever they are voting for)
*@dev Vote weight decays linearly over time. Lock time cannot be
* more than `MAXTIME` (4 years).
*/
// Voting escrow to have time-weighted votes
// Votes have a weight depending on time, so that users are committed
// to the future of (whatever they are voting for).
// The weight in this implementation is linear, and lock cannot be more than maxtime
// w ^
// 1 + /
// | /
// | /
// | /
// |/
// 0 +--------+------> time
// maxtime (4 years?)
// Interface for checking whether address belongs to a whitelisted
// type of a smart wallet.
// When new types are added - the whole contract is changed
// The check() method is modifying to be able to use caching
// for individual wallet addresses
//libraries
contract VotingEscrow is ReentrancyGuard {
struct Point {
int256 bias;
int256 slope; // - dweight / dt
uint256 ts; //timestamp
uint256 blk; // block
}
// We cannot really do block numbers per se b/c slope is per time, not per block
// and per block could be fairly bad b/c Ethereum changes blocktimes.
// What we can do is to extrapolate ***At functions
struct LockedBalance {
int256 amount;
uint256 end;
}
int256 constant DEPOSIT_FOR_TYPE = 0;
int256 constant CREATE_LOCK_TYPE = 1;
int256 constant INCREASE_LOCK_AMOUNT = 2;
int256 constant INCREASE_UNLOCK_TIME = 3;
event Deposit(
address indexed provider,
uint256 value,
uint256 indexed locktime,
int256 _type,
uint256 ts
);
event Withdraw(address indexed provider, uint256 value, uint256 ts);
event ForceUnlock(address target, uint256 value, uint256 ts);
event Supply(uint256 prevSupply, uint256 supply);
event commitWallet(address newSmartWalletChecker);
event applyWallet(address newSmartWalletChecker);
event commitCollateralManager(address newCollateralManager);
event applyCollateralManager(address newCollateralManager);
uint256 constant WEEK = 7 * 86400; // all future times are rounded by week
uint256 constant MAXTIME = 4 * 365 * 86400; // 4 years
uint256 constant MULTIPLIER = 10 ** 18;
address public token;
uint256 public supply;
mapping(address => LockedBalance) public locked;
//everytime user deposit/withdraw/change_locktime, these values will be updated;
uint256 public epoch;
Point[100000000000000000000000000000] public point_history; // epoch -> unsigned point.
mapping(address => Point[1000000000]) public user_point_history; // user -> Point[user_epoch]
mapping(address => uint256) public user_point_epoch;
mapping(uint256 => int256) public slope_changes; // time -> signed slope change
// Aragon's view methods for compatibility
address public controller;
bool public transfersEnabled;
string public name;
string public symbol;
string public version;
uint256 public constant decimals = 18;
// Checker for whitelisted (smart contract) wallets which are allowed to deposit
// The goal is to prevent tokenizing the escrow
address public future_smart_wallet_checker;
address public smart_wallet_checker;
address public collateral_manager;
address public future_collateral_manager;
IOwnership public immutable ownership;
modifier onlyOwner() {
require(
ownership.owner() == msg.sender,
"Caller is not allowed to operate"
);
_;
}
modifier checkStatus() {
if (collateral_manager != address(0)) {
require(
ICollateralManager(collateral_manager).checkStatus(msg.sender),
"rejected by collateral manager"
);
}
_;
}
/***
*@notice Contract constructor
*@param token_addr `InsureToken` token address
*@param _name Token name
*@param _symbol Token symbol
*@param _version Contract version - required for Aragon compatibility
*/
constructor(
address _token_addr,
string memory _name,
string memory _symbol,
string memory _version,
address _ownership
) {
ownership = IOwnership(_ownership);
token = _token_addr;
point_history[0].blk = block.number;
point_history[0].ts = block.timestamp;
controller = msg.sender;
transfersEnabled = true;
name = _name;
symbol = _symbol;
version = _version;
}
/***
*@notice Check if the call is from a whitelisted smart contract, revert if not
*@param _addr Address to be checked
*/
function assert_not_contract(address _addr) internal {
if (_addr != tx.origin) {
address checker = smart_wallet_checker; //not going to be deployed at the moment of launch.
if (checker != address(0)) {
if (ISmartWalletChecker(checker).check(_addr)) {
return;
}
}
revert("contract depositors not allowed");
}
}
/***
*@notice Get the most recently recorded rate of voting power decrease for `_addr`
*@param _addr Address of the user wallet
*@return Value of the slope
*/
function get_last_user_slope(address _addr)
external
view
returns(uint256) {
uint256 uepoch = user_point_epoch[_addr];
return uint256(user_point_history[_addr][uepoch].slope);
}
/***
*@notice Get the timestamp for checkpoint `_idx` for `_addr`
*@param _addr User wallet address
*@param _idx User epoch number
*@return Epoch time of the checkpoint
*/
function user_point_history__ts(address _addr, uint256 _idx)
external
view
returns(uint256) {
return user_point_history[_addr][_idx].ts;
}
/***
*@notice Get timestamp when `_addr`'s lock finishes
*@param _addr User wallet
*@return Epoch time of the lock end
*/
function locked__end(address _addr) external view returns(uint256) {
return locked[_addr].end;
}
/***
*@notice Record global and per-user data to checkpoint
*@param _addr User's wallet address. No user checkpoint if 0x0
*@param _old_locked Pevious locked amount / end lock time for the user
*@param _new_locked New locked amount / end lock time for the user
*/
function _checkpoint(
address _addr,
LockedBalance memory _old_locked,
LockedBalance memory _new_locked
) internal {
Point memory _u_old;
Point memory _u_new;
int256 _old_dslope = 0;
int256 _new_dslope = 0;
uint256 _epoch = epoch;
if (_addr != address(0)) {
// Calculate slopes and biases
// Kept at zero when they have to
if (_old_locked.end > block.timestamp && _old_locked.amount > 0) {
unchecked {
_u_old.slope = _old_locked.amount / int256(MAXTIME);
}
_u_old.bias =
_u_old.slope *
int256(_old_locked.end - block.timestamp);
}
if (_new_locked.end > block.timestamp && _new_locked.amount > 0) {
unchecked {
_u_new.slope = _new_locked.amount / int256(MAXTIME);
}
_u_new.bias =
_u_new.slope *
int256(_new_locked.end - block.timestamp);
}
// Read values of scheduled changes in the slope
// _old_locked.end can be in the past and in the future
// _new_locked.end can ONLY by in the FUTURE unless everything expired than zeros
_old_dslope = slope_changes[_old_locked.end];
if (_new_locked.end != 0) {
if (_new_locked.end == _old_locked.end) {
_new_dslope = _old_dslope;
} else {
_new_dslope = slope_changes[_new_locked.end];
}
}
}
Point memory _last_point = Point({
bias: 0,
slope: 0,
ts: block.timestamp,
blk: block.number
});
if (_epoch > 0) {
_last_point = point_history[_epoch];
}
uint256 _last_checkpoint = _last_point.ts;
// _initial_last_point is used for extrapolation to calculate block number
// (approximately, for *At methods) and save them
// as we cannot figure that out exactly from inside the contract
Point memory _initial_last_point = _last_point;
uint256 _block_slope = 0; // dblock/dt
if (block.timestamp > _last_point.ts) {
_block_slope =
(MULTIPLIER * (block.number - _last_point.blk)) /
(block.timestamp - _last_point.ts);
}
// If last point is already recorded in this block, slope=0
// But that's ok b/c we know the block in such case
// Go over weeks to fill history and calculate what the current point is
uint256 _t_i;
unchecked {
_t_i = (_last_checkpoint / WEEK) * WEEK;
}
for (uint256 i; i < 255;) {
// Hopefully it won't happen that this won't get used in 5 years!
// If it does, users will be able to withdraw but vote weight will be broken
_t_i += WEEK;
int256 d_slope = 0;
if (_t_i > block.timestamp) {
_t_i = block.timestamp;
} else {
d_slope = slope_changes[_t_i];
}
_last_point.bias =
_last_point.bias -
_last_point.slope *
int256(_t_i - _last_checkpoint);
_last_point.slope += d_slope;
if (_last_point.bias < 0) {
// This can happen
_last_point.bias = 0;
}
if (_last_point.slope < 0) {
// This cannot happen - just in case
_last_point.slope = 0;
}
_last_checkpoint = _t_i;
_last_point.ts = _t_i;
_last_point.blk =
_initial_last_point.blk +
((_block_slope * (_t_i - _initial_last_point.ts)) / MULTIPLIER);
_epoch += 1;
if (_t_i == block.timestamp) {
_last_point.blk = block.number;
break;
} else {
point_history[_epoch] = _last_point;
}
unchecked {
++i;
}
}
epoch = _epoch;
// Now point_history is filled until t=now
if (_addr != address(0)) {
// If last point was in this block, the slope change has been applied already
// But in such case we have 0 slope(s)
_last_point.slope += _u_new.slope - _u_old.slope;
_last_point.bias += _u_new.bias - _u_old.bias;
if (_last_point.slope < 0) {
_last_point.slope = 0;
}
if (_last_point.bias < 0) {
_last_point.bias = 0;
}
}
// Record the changed point into history
point_history[_epoch] = _last_point;
address _addr2 = _addr; //To avoid being "Stack Too Deep"
if (_addr2 != address(0)) {
// Schedule the slope changes (slope is going down)
// We subtract new_user_slope from [_new_locked.end]
// and add old_user_slope to [_old_locked.end]
if (_old_locked.end > block.timestamp) {
// _old_dslope was <something> - _u_old.slope, so we cancel that
_old_dslope += _u_old.slope;
if (_new_locked.end == _old_locked.end) {
_old_dslope -= _u_new.slope; // It was a new deposit, not extension
}
slope_changes[_old_locked.end] = _old_dslope;
}
if (_new_locked.end > block.timestamp) {
if (_new_locked.end > _old_locked.end) {
_new_dslope -= _u_new.slope; // old slope disappeared at this point
slope_changes[_new_locked.end] = _new_dslope;
}
// else we recorded it already in _old_dslope
}
// Now handle user history
uint256 _user_epoch;
unchecked {
_user_epoch = user_point_epoch[_addr2] + 1;
}
user_point_epoch[_addr2] = _user_epoch;
_u_new.ts = block.timestamp;
_u_new.blk = block.number;
user_point_history[_addr2][_user_epoch] = _u_new;
}
}
/***
*@notice Deposit and lock tokens for a user
*@param _depositor Spender's wallet address
*@param _beneficiary Beneficiary's wallet address
*@param _value Amount to deposit
*@param _unlock_time New time when to unlock the tokens, or 0 if unchanged
*@param _locked_balance Previous locked amount / timestamp
*/
function _deposit_for(
address _depositor,
address _beneficiary,
uint256 _value,
uint256 _unlock_time,
LockedBalance memory _locked_balance,
int256 _type
) internal {
LockedBalance memory _locked = LockedBalance(
_locked_balance.amount,
_locked_balance.end
);
LockedBalance memory _old_locked = LockedBalance(
_locked_balance.amount,
_locked_balance.end
);
uint256 _supply_before = supply;
supply = _supply_before + _value;
//Adding to existing lock, or if a lock is expired - creating a new one
_locked.amount = _locked.amount + int256(_value);
if (_unlock_time != 0) {
_locked.end = _unlock_time;
}
locked[_beneficiary] = _locked;
// Possibilities
// Both _old_locked.end could be current or expired (>/< block.timestamp)
// value == 0 (extend lock) or value > 0 (add to lock or extend lock)
// _locked.end > block.timestamp (always)
_checkpoint(_beneficiary, _old_locked, _locked);
if (_value != 0) {
require(IERC20(token).transferFrom(_depositor, address(this), _value));
}
emit Deposit(_beneficiary, _value, _locked.end, _type, block.timestamp);
emit Supply(_supply_before, _supply_before + _value);
}
function checkpoint() public {
/***
*@notice Record global data to checkpoint
*/
LockedBalance memory _a;
LockedBalance memory _b;
_checkpoint(address(0), _a, _b);
}
/***
*@notice Deposit `_value` tokens for `_addr` and add to the lock
*@dev Anyone (even a smart contract) can deposit for someone else, but
* cannot extend their locktime and deposit for a brand new user
*@param _addr User's wallet address
*@param _value Amount to add to user's lock
*/
function deposit_for(address _addr, uint256 _value) external nonReentrant {
LockedBalance memory _locked = locked[_addr];
require(_value > 0, "dev: need non-zero value");
require(_locked.amount > 0, "No existing lock found");
require(
_locked.end > block.timestamp,
"Cannot add to expired lock."
);
_deposit_for(msg.sender, _addr, _value, 0, _locked, DEPOSIT_FOR_TYPE);
}
/***
*@notice Deposit `_value` tokens for `msg.sender` and lock until `_unlock_time`
*@param _value Amount to deposit
*@param _unlock_time Epoch time when tokens unlock, rounded down to whole weeks
*/
function create_lock(uint256 _value, uint256 _unlock_time)external nonReentrant {
assert_not_contract(msg.sender);
_unlock_time = (_unlock_time / WEEK) * WEEK; // Locktime is rounded down to weeks
LockedBalance memory _locked = locked[msg.sender];
require(_value > 0, "dev: need non-zero value");
require(_locked.amount == 0, "Withdraw old tokens first");
require(
_unlock_time > block.timestamp,
"Can lock until time in future"
);
require(
_unlock_time <= block.timestamp + MAXTIME,
"Voting lock can be 4 years max"
);
_deposit_for(
msg.sender,
msg.sender,
_value,
_unlock_time,
_locked,
CREATE_LOCK_TYPE
);
}
/***
*@notice Deposit `_value` additional tokens for `msg.sender`
* without modifying the unlock time
*@param _value Amount of tokens to deposit and add to the lock
*/
function increase_amount(uint256 _value) external nonReentrant {
assert_not_contract(msg.sender);
LockedBalance memory _locked = locked[msg.sender];
require(_value > 0);
require(_locked.amount > 0, "No existing lock found");
require(
_locked.end > block.timestamp,
"Cannot add to expired lock."
);
_deposit_for(msg.sender, msg.sender, _value, 0, _locked, INCREASE_LOCK_AMOUNT);
}
/***
*@notice Extend the unlock time for `msg.sender` to `_unlock_time`
*@param _unlock_time New epoch time for unlocking
*/
function increase_unlock_time(uint256 _unlock_time) external nonReentrant {
assert_not_contract(msg.sender); //@shun: need to convert to solidity
LockedBalance memory _locked = locked[msg.sender];
unchecked {
_unlock_time = (_unlock_time / WEEK) * WEEK; // Locktime is rounded down to weeks
}
require(_locked.end > block.timestamp, "Lock expired");
require(_locked.amount > 0, "Nothing is locked");
require(_unlock_time > _locked.end, "Can only increase lock duration");
require(
_unlock_time <= block.timestamp + MAXTIME,
"Voting lock can be 4 years max"
);
_deposit_for(
msg.sender,
msg.sender,
0,
_unlock_time,
_locked,
INCREASE_UNLOCK_TIME
);
}
/***
*@notice Withdraw all tokens for `msg.sender`
*@dev Only possible if the lock has expired
*/
function withdraw() external checkStatus nonReentrant {
LockedBalance memory _locked = LockedBalance(
locked[msg.sender].amount,
locked[msg.sender].end
);
require(block.timestamp >= _locked.end, "The lock didn't expire");
uint256 _value = uint256(_locked.amount);
LockedBalance memory _old_locked = LockedBalance(
locked[msg.sender].amount,
locked[msg.sender].end
);
_locked.end = 0;
_locked.amount = 0;
locked[msg.sender] = _locked;
uint256 _supply_before = supply;
supply = _supply_before - _value;
// _old_locked can have either expired <= timestamp or zero end
// _locked has only 0 end
// Both can have >= 0 amount
_checkpoint(msg.sender, _old_locked, _locked);
require(IERC20(token).transfer(msg.sender, _value));
emit Withdraw(msg.sender, _value, block.timestamp);
emit Supply(_supply_before, _supply_before - _value);
}
// The following ERC20/minime-compatible methods are not real balanceOf and supply!
// They measure the weights for the purpose of voting, so they don't represent
// real coins.
/***
*@notice Binary search to estimate timestamp for block number
*@param _block Block to find
*@param _max_epoch Don't go beyond this epoch
*@return Approximate timestamp for block
*/
function find_block_epoch(uint256 _block, uint256 _max_epoch) internal view returns(uint256) {
// Binary search
uint256 _min = 0;
uint256 _max = _max_epoch;
unchecked {
for (uint256 i; i <= 128; i++) {
// Will be always enough for 128-bit numbers
if (_min >= _max) {
break;
}
uint256 _mid = (_min + _max + 1) / 2;
if (point_history[_mid].blk <= _block) {
_min = _mid;
} else {
_max = _mid - 1;
}
}
}
return _min;
}
/***
*@notice Get the current voting power for `msg.sender`
*@dev Adheres to the ERC20 `balanceOf` interface for Metamask & Snapshot compatibility
*@param _addr User wallet address
*@return User's present voting power
*/
function balanceOf(address _addr) external view returns(uint256) {
uint256 _t = block.timestamp;
uint256 _epoch = user_point_epoch[_addr];
if (_epoch == 0) {
return 0;
} else {
Point memory _last_point = user_point_history[_addr][_epoch];
_last_point.bias -= _last_point.slope * int256(_t - _last_point.ts);
if (_last_point.bias < 0) {
_last_point.bias = 0;
}
return uint256(_last_point.bias);
}
}
/***
*@notice Get the current voting power for `msg.sender`
*@dev Adheres to the ERC20 `balanceOf` interface for Aragon compatibility
*@param _addr User wallet address
*@param _t Epoch time to return voting power at
*@return User voting power
*@dev return the present voting power if _t is 0
*/
function balanceOf(address _addr, uint256 _t) external view returns(uint256) {
if (_t == 0) {
_t = block.timestamp;
}
uint256 _epoch = user_point_epoch[_addr];
if (_epoch == 0) {
return 0;
} else {
Point memory _last_point = user_point_history[_addr][_epoch];
_last_point.bias -= _last_point.slope * int256(_t - _last_point.ts);
if (_last_point.bias < 0) {
_last_point.bias = 0;
}
return uint256(_last_point.bias);
}
}
//Struct to avoid "Stack Too Deep"
struct Parameters {
uint256 min;
uint256 max;
uint256 max_epoch;
uint256 d_block;
uint256 d_t;
}
/***
*@notice Measure voting power of `_addr` at block height `_block`
*@dev Adheres to MiniMe `balanceOfAt` interface https//github.com/Giveth/minime
*@param _addr User's wallet address
*@param _block Block to calculate the voting power at
*@return Voting power
*/
function balanceOfAt(address _addr, uint256 _block) external view returns(uint256) {
// Copying and pasting totalSupply code because Vyper cannot pass by
// reference yet
require(_block <= block.number);
Parameters memory _st;
// Binary search
_st.min = 0;
_st.max = user_point_epoch[_addr];
unchecked {
for (uint256 i; i <= 128; i++) {
// Will be always enough for 128-bit numbers
if (_st.min >= _st.max) {
break;
}
uint256 _mid = (_st.min + _st.max + 1) / 2;
if (user_point_history[_addr][_mid].blk <= _block) {
_st.min = _mid;
} else {
_st.max = _mid - 1;
}
}
}
Point memory _upoint = user_point_history[_addr][_st.min];
_st.max_epoch = epoch;
uint256 _epoch = find_block_epoch(_block, _st.max_epoch);
Point memory _point_0 = point_history[_epoch];
_st.d_block = 0;
_st.d_t = 0;
if (_epoch < _st.max_epoch) {
Point memory _point_1 = point_history[_epoch + 1];
_st.d_block = _point_1.blk - _point_0.blk;
_st.d_t = _point_1.ts - _point_0.ts;
} else {
_st.d_block = block.number - _point_0.blk;
_st.d_t = block.timestamp - _point_0.ts;
}
uint256 block_time = _point_0.ts;
if (_st.d_block != 0) {
block_time += (_st.d_t * (_block - _point_0.blk)) / _st.d_block;
}
_upoint.bias -= _upoint.slope * int256(block_time - _upoint.ts);
if (_upoint.bias >= 0) {
return uint256(_upoint.bias);
}
}
/***
*@notice Calculate total voting power at some point in the past
*@param point The point (bias/slope) to start search from
*@param t Time to calculate the total voting power at
*@return Total voting power at that time
*/
function supply_at(Point memory point, uint256 t) internal view returns(uint256) {
Point memory _last_point = point;
uint256 _t_i;
unchecked {
_t_i = (_last_point.ts / WEEK) * WEEK;
}
for (uint256 i; i < 255;) {
_t_i += WEEK;
int256 d_slope = 0;
if (_t_i > t) {
_t_i = t;
} else {
d_slope = slope_changes[_t_i];
}
_last_point.bias -=
_last_point.slope *
int256(_t_i - _last_point.ts);
if (_t_i == t) {
break;
}
_last_point.slope += d_slope;
_last_point.ts = _t_i;
unchecked {
++i;
}
}
if (_last_point.bias < 0) {
_last_point.bias = 0;
}
return uint256(_last_point.bias);
}
/***
*@notice Calculate total voting power
*@dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility
*@return Total voting power
*/
function totalSupply() external view returns(uint256) {
uint256 _epoch = epoch;
Point memory _last_point = point_history[_epoch];
return supply_at(_last_point, block.timestamp);
}
/***
*@notice Calculate total voting power
*@dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility
*@return Total voting power
*/
function totalSupply(uint256 _t) external view returns(uint256) {
if (_t == 0) {
_t = block.timestamp;
}
uint256 _epoch = epoch;
Point memory _last_point = point_history[_epoch];
return supply_at(_last_point, _t);
}
/***
*@notice Calculate total voting power at some point in the past
*@param _block Block to calculate the total voting power at
*@return Total voting power at `_block`
*/
function totalSupplyAt(uint256 _block) external view returns(uint256) {
require(_block <= block.number);
uint256 _epoch = epoch;
uint256 _target_epoch = find_block_epoch(_block, _epoch);
Point memory _point = point_history[_target_epoch];
uint256 dt = 0;
if (_target_epoch < _epoch) {
Point memory _point_next = point_history[_target_epoch + 1];
if (_point.blk != _point_next.blk) {
dt =
((_block - _point.blk) * (_point_next.ts - _point.ts)) /
(_point_next.blk - _point.blk);
}
} else {
if (_point.blk != block.number) {
dt =
((_block - _point.blk) * (block.timestamp - _point.ts)) /
(block.number - _point.blk);
}
}
// Now dt contains info on how far are we beyond point
return supply_at(_point, _point.ts + dt);
}
/***
*@dev Dummy method required for Aragon compatibility
*/
function changeController(address _newController) external {
require(msg.sender == controller);
controller = _newController;
}
function get_user_point_epoch(address _user)
external
view
returns(uint256) {
return user_point_epoch[_user];
}
//----------------------Investment module----------------------//
/***
*@notice unlock INSURE token without waiting for its end time.
*@param _target address of being unlocked.
*@return
*/
function force_unlock(address _target) external returns(bool) {
require(
msg.sender == collateral_manager,
"only collateral manager allowed"
);
//withdraw
LockedBalance memory _locked = LockedBalance(
locked[_target].amount,
locked[_target].end
);
LockedBalance memory _old_locked = LockedBalance(
locked[_target].amount,
locked[_target].end
);
uint256 value = uint256(_locked.amount);
//there must be locked INSURE
require(value != 0, "There is no locked INSURE");
_locked.end = 0;
_locked.amount = 0;
locked[_target] = _locked;
uint256 _supply_before = supply;
supply = _supply_before - value;
_checkpoint(_target, _old_locked, _locked);
//transfer INSURE to collateral_manager
require(IERC20(token).transfer(collateral_manager, value));
emit ForceUnlock(_target, value, block.timestamp);
emit Supply(_supply_before, _supply_before - value);
return true;
}
//---------------------- Admin Only ----------------------//
/***
*@notice Set an external contract to check for approved smart contract wallets
*@param _addr Address of Smart contract checker
*/
function commit_smart_wallet_checker(address _addr) external onlyOwner {
future_smart_wallet_checker = _addr;
emit commitWallet(_addr);
}
/***
*@notice Apply setting external contract to check approved smart contract wallets
*/
function apply_smart_wallet_checker() external onlyOwner {
address _future_smart_wallet_checker = future_smart_wallet_checker;
smart_wallet_checker = _future_smart_wallet_checker;
emit commitWallet(_future_smart_wallet_checker);
}
/***
*@notice Commit setting external contract to check user's collateral status
*/
function commit_collateral_manager(address _new_collateral_manager) external onlyOwner {
future_collateral_manager = _new_collateral_manager;
emit commitCollateralManager(_new_collateral_manager);
}
/***
*@notice Apply setting external contract to check user's collateral status
*/
function apply_collateral_manager() external onlyOwner {
address _future_collateral_manager = future_collateral_manager;
collateral_manager = _future_collateral_manager;
emit applyCollateralManager(_future_collateral_manager);
}
}
|
Measure voting power of `_addr` at block height `_block` _addr User's wallet address _block Block to calculate the voting power atreturn Voting power/ Copying and pasting totalSupply code because Vyper cannot pass by reference yet Binary search Will be always enough for 128-bit numbers
|
function balanceOfAt(address _addr, uint256 _block) external view returns(uint256) {
require(_block <= block.number);
Parameters memory _st;
_st.min = 0;
_st.max = user_point_epoch[_addr];
unchecked {
for (uint256 i; i <= 128; i++) {
if (_st.min >= _st.max) {
break;
}
uint256 _mid = (_st.min + _st.max + 1) / 2;
if (user_point_history[_addr][_mid].blk <= _block) {
_st.min = _mid;
_st.max = _mid - 1;
}
}
}
Point memory _upoint = user_point_history[_addr][_st.min];
_st.max_epoch = epoch;
uint256 _epoch = find_block_epoch(_block, _st.max_epoch);
Point memory _point_0 = point_history[_epoch];
_st.d_block = 0;
_st.d_t = 0;
if (_epoch < _st.max_epoch) {
Point memory _point_1 = point_history[_epoch + 1];
_st.d_block = _point_1.blk - _point_0.blk;
_st.d_t = _point_1.ts - _point_0.ts;
_st.d_block = block.number - _point_0.blk;
_st.d_t = block.timestamp - _point_0.ts;
}
uint256 block_time = _point_0.ts;
if (_st.d_block != 0) {
block_time += (_st.d_t * (_block - _point_0.blk)) / _st.d_block;
}
_upoint.bias -= _upoint.slope * int256(block_time - _upoint.ts);
if (_upoint.bias >= 0) {
return uint256(_upoint.bias);
}
}
| 10,627,259
|
./full_match/1/0x5244d38310E45629f637698Ee87A46ee6b408488/sources/LayerZero.sol
|
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 0");
}
| 3,193,615
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
/// @notice Emitted when the owner of the factory is changed
/// @param oldOwner The owner before the owner was changed
/// @param newOwner The owner after the owner was changed
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/// @notice Emitted when a pool is created
/// @param token0 The first token of the pool by address sort order
/// @param token1 The second token of the pool by address sort order
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks
/// @param pool The address of the created pool
event PoolCreated(
address indexed token0,
address indexed token1,
uint24 indexed fee,
int24 tickSpacing,
address pool
);
/// @notice Emitted when a new fee amount is enabled for pool creation via the factory
/// @param fee The enabled fee, denominated in hundredths of a bip
/// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);
/// @notice Returns the current owner of the factory
/// @dev Can be changed by the current owner via setOwner
/// @return The address of the factory owner
function owner() external view returns (address);
/// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
/// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
/// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
/// @return The tick spacing
function feeAmountTickSpacing(uint24 fee) external view returns (int24);
/// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
/// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The pool address
function getPool(
address tokenA,
address tokenB,
uint24 fee
) external view returns (address pool);
/// @notice Creates a pool for the given two tokens and fee
/// @param tokenA One of the two tokens in the desired pool
/// @param tokenB The other of the two tokens in the desired pool
/// @param fee The desired fee for the pool
/// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
/// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
/// are invalid.
/// @return pool The address of the newly created pool
function createPool(
address tokenA,
address tokenB,
uint24 fee
) external returns (address pool);
/// @notice Updates the owner of the factory
/// @dev Must be called by the current owner
/// @param _owner The new owner of the factory
function setOwner(address _owner) external;
/// @notice Enables a fee amount with the given tickSpacing
/// @dev Fee amounts may never be removed once enabled
/// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
/// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = -denominator & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.5.0 <0.8.0;
library BytesLib {
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, 'toAddress_overflow');
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import './BytesLib.sol';
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
library TransferHelper {
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
}
/// @notice Approves the stipulated contract to spend the given allowance in the given token
/// @dev Errors with 'SA' if transfer fails
/// @param token The contract address of the token to be approved
/// @param to The target of the approval
/// @param value The amount of the given token the target will be allowed to spend
function safeApprove(
address token,
address to,
uint256 value
) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'STE');
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import './libraries/PathPrice.sol';
import './interfaces/IHotPotV3Fund.sol';
import './interfaces/IHotPot.sol';
import './interfaces/IHotPotV3FundController.sol';
import './base/Multicall.sol';
contract HotPotV3FundController is IHotPotV3FundController, Multicall {
using Path for bytes;
address public override immutable uniV3Factory;
address public override immutable uniV3Router;
address public override immutable hotpot;
address public override governance;
address public override immutable WETH9;
uint32 maxPIS = (100 << 16) + 9974;// MaxPriceImpact: 1%, MaxSwapSlippage: 0.5% = (1 - (sqrtSlippage/1e4)^2) * 100%
mapping (address => bool) public override verifiedToken;
mapping (address => bytes) public override harvestPath;
modifier onlyManager(address fund){
require(msg.sender == IHotPotV3Fund(fund).manager(), "OMC");
_;
}
modifier onlyGovernance{
require(msg.sender == governance, "OGC");
_;
}
modifier checkDeadline(uint deadline) {
require(block.timestamp <= deadline, 'CDL');
_;
}
constructor(
address _hotpot,
address _governance,
address _uniV3Router,
address _uniV3Factory,
address _weth9
) {
hotpot = _hotpot;
governance = _governance;
uniV3Router = _uniV3Router;
uniV3Factory = _uniV3Factory;
WETH9 = _weth9;
}
/// @inheritdoc IControllerState
function maxPriceImpact() external override view returns(uint32 priceImpact){
return maxPIS >> 16;
}
/// @inheritdoc IControllerState
function maxSqrtSlippage() external override view returns(uint32 sqrtSlippage){
return maxPIS & 0xffff;
}
/// @inheritdoc IGovernanceActions
function setHarvestPath(address token, bytes calldata path) external override onlyGovernance {
bytes memory _path = path;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = _path.decodeFirstPool();
// pool is exist
address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee);
require(pool != address(0), "PIE");
// at least 2 observations
(,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0();
require(observationCardinality >= 2, "OC");
if (_path.hasMultiplePools()) {
_path = _path.skipToken();
} else {
//最后一个交易对:输入WETH9, 输出hotpot
require(tokenIn == WETH9 && tokenOut == hotpot, "IOT");
break;
}
}
harvestPath[token] = path;
emit SetHarvestPath(token, path);
}
/// @inheritdoc IGovernanceActions
function setMaxPriceImpact(uint32 priceImpact) external override onlyGovernance {
require(priceImpact <= 1e4 ,"SPI");
maxPIS = (priceImpact << 16) | (maxPIS & 0xffff);
emit SetMaxPriceImpact(priceImpact);
}
/// @inheritdoc IGovernanceActions
function setMaxSqrtSlippage(uint32 sqrtSlippage) external override onlyGovernance {
require(sqrtSlippage <= 1e4 ,"SSS");
maxPIS = maxPIS & 0xffff0000 | sqrtSlippage;
emit SetMaxSqrtSlippage(sqrtSlippage);
}
/// @inheritdoc IHotPotV3FundController
function harvest(address token, uint amount) external override returns(uint burned) {
bytes memory path = harvestPath[token];
PathPrice.verifySlippage(path, uniV3Factory, maxPIS & 0xffff);
uint value = amount <= IERC20(token).balanceOf(address(this)) ? amount : IERC20(token).balanceOf(address(this));
TransferHelper.safeApprove(token, uniV3Router, value);
ISwapRouter.ExactInputParams memory args = ISwapRouter.ExactInputParams({
path: path,
recipient: address(this),
deadline: block.timestamp,
amountIn: value,
amountOutMinimum: 0
});
burned = ISwapRouter(uniV3Router).exactInput(args);
IHotPot(hotpot).burn(burned);
emit Harvest(token, amount, burned);
}
/// @inheritdoc IGovernanceActions
function setGovernance(address account) external override onlyGovernance {
require(account != address(0));
governance = account;
emit SetGovernance(account);
}
/// @inheritdoc IGovernanceActions
function setVerifiedToken(address token, bool isVerified) external override onlyGovernance {
verifiedToken[token] = isVerified;
emit ChangeVerifiedToken(token, isVerified);
}
/// @inheritdoc IManagerActions
function setDescriptor(address fund, bytes calldata _descriptor) external override onlyManager(fund) {
return IHotPotV3Fund(fund).setDescriptor(_descriptor);
}
/// @inheritdoc IManagerActions
function setDepositDeadline(address fund, uint deadline) external override onlyManager(fund) {
return IHotPotV3Fund(fund).setDepositDeadline(deadline);
}
/// @inheritdoc IManagerActions
function setPath(
address fund,
address distToken,
bytes memory path
) external override onlyManager(fund){
require(verifiedToken[distToken]);
address fundToken = IHotPotV3Fund(fund).token();
bytes memory _path = path;
bytes memory _reverse;
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
_reverse = abi.encodePacked(tokenOut, fee, tokenIn);
bool isBuy;
// 第一个tokenIn是基金token,那么就是buy路径
if(tokenIn == fundToken){
isBuy = true;
}
// 如果是sellPath, 第一个需要是目标代币
else{
require(tokenIn == distToken);
}
while (true) {
require(verifiedToken[tokenIn], "VIT");
require(verifiedToken[tokenOut], "VOT");
// pool is exist
address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee);
require(pool != address(0), "PIE");
// at least 2 observations
(,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0();
require(observationCardinality >= 2, "OC");
if (path.hasMultiplePools()) {
path = path.skipToken();
(tokenIn, tokenOut, fee) = path.decodeFirstPool();
_reverse = abi.encodePacked(tokenOut, fee, _reverse);
} else {
/// @dev 如果是buy, 最后一个token要是目标代币;
/// @dev 如果是sell, 最后一个token要是基金token.
if(isBuy)
require(tokenOut == distToken, "OID");
else
require(tokenOut == fundToken, "OIF");
break;
}
}
if(!isBuy) (_path, _reverse) = (_reverse, _path);
IHotPotV3Fund(fund).setPath(distToken, _path, _reverse);
}
/// @inheritdoc IManagerActions
function init(
address fund,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).init(token0, token1, fee, tickLower, tickUpper, amount, maxPIS);
}
/// @inheritdoc IManagerActions
function add(
address fund,
uint poolIndex,
uint positionIndex,
uint amount,
bool collect,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).add(poolIndex, positionIndex, amount, collect, maxPIS);
}
/// @inheritdoc IManagerActions
function sub(
address fund,
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint amount){
return IHotPotV3Fund(fund).sub(poolIndex, positionIndex, proportionX128, maxPIS);
}
/// @inheritdoc IManagerActions
function move(
address fund,
uint poolIndex,
uint subIndex,
uint addIndex,
uint proportionX128,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint128 liquidity){
return IHotPotV3Fund(fund).move(poolIndex, subIndex, addIndex, proportionX128, maxPIS);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;
import '../interfaces/IMulticall.sol';
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title HPT (Hotpot Funds) 代币接口定义.
interface IHotPot is IERC20{
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function burn(uint value) external returns (bool) ;
function burnFrom(address from, uint value) external returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './IHotPotV3FundERC20.sol';
import './fund/IHotPotV3FundEvents.sol';
import './fund/IHotPotV3FundState.sol';
import './fund/IHotPotV3FundUserActions.sol';
import './fund/IHotPotV3FundManagerActions.sol';
/// @title Hotpot V3 基金接口
/// @notice 接口定义分散在多个接口文件
interface IHotPotV3Fund is
IHotPotV3FundERC20,
IHotPotV3FundEvents,
IHotPotV3FundState,
IHotPotV3FundUserActions,
IHotPotV3FundManagerActions
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './controller/IManagerActions.sol';
import './controller/IGovernanceActions.sol';
import './controller/IControllerState.sol';
import './controller/IControllerEvents.sol';
/// @title Hotpot V3 控制合约接口定义.
/// @notice 基金经理和治理均需通过控制合约进行操作.
interface IHotPotV3FundController is IManagerActions, IGovernanceActions, IControllerState, IControllerEvents {
/// @notice 基金分成全部用于销毁HPT
/// @dev 任何人都可以调用本函数
/// @param token 用于销毁时购买HPT的代币类型
/// @param amount 代币数量
/// @return burned 销毁数量
function harvest(address token, uint amount) external returns(uint burned);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Hotpot V3 基金份额代币接口定义
interface IHotPotV3FundERC20 is IERC20{
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title HotPotV3Controller 事件接口定义
interface IControllerEvents {
/// @notice 当设置受信任token时触发
event ChangeVerifiedToken(address indexed token, bool isVerified);
/// @notice 当调用Harvest时触发
event Harvest(address indexed token, uint amount, uint burned);
/// @notice 当调用setHarvestPath时触发
event SetHarvestPath(address indexed token, bytes path);
/// @notice 当调用setGovernance时触发
event SetGovernance(address indexed account);
/// @notice 当调用setMaxSqrtSlippage时触发
event SetMaxSqrtSlippage(uint sqrtSlippage);
/// @notice 当调用setMaxPriceImpact时触发
event SetMaxPriceImpact(uint priceImpact);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title HotPotV3Controller 状态变量及只读函数
interface IControllerState {
/// @notice Returns the address of the Uniswap V3 router
function uniV3Router() external view returns (address);
/// @notice Returns the address of the Uniswap V3 facotry
function uniV3Factory() external view returns (address);
/// @notice 本项目治理代币HPT的地址
function hotpot() external view returns (address);
/// @notice 治理账户地址
function governance() external view returns (address);
/// @notice Returns the address of WETH9
function WETH9() external view returns (address);
/// @notice 代币是否受信任
/// @dev The call will revert if the the token argument is address 0.
/// @param token 要查询的代币地址
function verifiedToken(address token) external view returns (bool);
/// @notice harvest时交易路径
/// @param token 要兑换的代币
function harvestPath(address token) external view returns (bytes memory);
/// @notice 获取swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100%
/// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5%
function maxSqrtSlippage() external view returns (uint32);
/// @notice 获取swap时最大价格影响,取值范围为 0-1e4
function maxPriceImpact() external view returns (uint32);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title 治理操作接口定义
interface IGovernanceActions {
/// @notice Change governance
/// @dev This function can only be called by governance
/// @param account 新的governance地址
function setGovernance(address account) external;
/// @notice Set the token to be verified for all fund, vice versa
/// @dev This function can only be called by governance
/// @param token 目标代币
/// @param isVerified 是否受信任
function setVerifiedToken(address token, bool isVerified) external;
/// @notice Set the swap path for harvest
/// @dev This function can only be called by governance
/// @param token 目标代币
/// @param path 路径
function setHarvestPath(address token, bytes calldata path) external;
/// @notice 设置swap时最大滑点,取值范围为 0-1e4, 计算公式为:MaxSwapSlippage = (1 - (sqrtSlippage/1e4)^2) * 100%
/// 如设置最大滑点 0.5%, 则 sqrtSlippage 应设置为9974,此时 MaxSwapSlippage = (1-(9974/1e4)^2)*100% = 0.5%
/// @dev This function can only be called by governance
/// @param sqrtSlippage 0-1e4
function setMaxSqrtSlippage(uint32 sqrtSlippage) external;
/// @notice Set the max price impact for swap
/// @dev This function can only be called by governance
/// @param priceImpact 0-1e4
function setMaxPriceImpact(uint32 priceImpact) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import '../fund/IHotPotV3FundManagerActions.sol';
/// @title 控制器合约基金经理操作接口定义
interface IManagerActions {
/// @notice 设置基金描述信息
/// @dev This function can only be called by manager
/// @param _descriptor 描述信息
function setDescriptor(address fund, bytes calldata _descriptor) external;
/// @notice 设置基金存入截止时间
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param deadline 最晚存入截止时间
function setDepositDeadline(address fund, uint deadline) external;
/// @notice 设置代币交易路径
/// @dev This function can only be called by manager
/// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任
/// @param fund 基金地址
/// @param distToken 目标代币地址
/// @param path 符合uniswap v3格式的交易路径
function setPath(
address fund,
address distToken,
bytes memory path
) external;
/// @notice 初始化头寸, 允许投资额为0.
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param token0 token0 地址
/// @param token1 token1 地址
/// @param fee 手续费率
/// @param tickLower 价格刻度下届
/// @param tickUpper 价格刻度上届
/// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资
/// @param deadline 最晚交易时间
/// @return liquidity 添加的lp数量
function init(
address fund,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint deadline
) external returns(uint128 liquidity);
/// @notice 投资指定头寸,可选复投手续费
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param amount 投资金额
/// @param collect 是否收集已产生的手续费并复投
/// @param deadline 最晚交易时间
/// @return liquidity 添加的lp数量
function add(
address fund,
uint poolIndex,
uint positionIndex,
uint amount,
bool collect,
uint deadline
) external returns(uint128 liquidity);
/// @notice 撤资指定头寸
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费
/// @param deadline 最晚交易时间
/// @return amount 撤资获得的基金本币数量
function sub(
address fund,
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint deadline
) external returns(uint amount);
/// @notice 调整头寸投资
/// @dev This function can only be called by manager
/// @param fund 基金地址
/// @param poolIndex 池子索引号
/// @param subIndex 要移除的头寸索引号
/// @param addIndex 要添加的头寸索引号
/// @param proportionX128 调整比例,左移128位
/// @param deadline 最晚交易时间
/// @return liquidity 调整后添加的lp数量
function move(
address fund,
uint poolIndex,
uint subIndex,
uint addIndex,
uint proportionX128,
uint deadline
) external returns(uint128 liquidity);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Hotpot V3 事件接口定义
interface IHotPotV3FundEvents {
/// @notice 当存入基金token时,会触发该事件
event Deposit(address indexed owner, uint amount, uint share);
/// @notice 当取走基金token时,会触发该事件
event Withdraw(address indexed owner, uint amount, uint share);
/// @notice 当调用setDescriptor时触发
event SetDescriptor(bytes descriptor);
/// @notice 当调用setDepositDeadline时触发
event SetDeadline(uint deadline);
/// @notice 当调用setPath时触发
event SetPath(address distToken, bytes path);
/// @notice 当调用init时,会触发该事件
event Init(uint poolIndex, uint positionIndex, uint amount);
/// @notice 当调用add时,会触发该事件
event Add(uint poolIndex, uint positionIndex, uint amount, bool collect);
/// @notice 当调用sub时,会触发该事件
event Sub(uint poolIndex, uint positionIndex, uint proportionX128);
/// @notice 当调用move时,会触发该事件
event Move(uint poolIndex, uint subIndex, uint addIndex, uint proportionX128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @notice 基金经理操作接口定义
interface IHotPotV3FundManagerActions {
/// @notice 设置基金描述信息
/// @dev This function can only be called by controller
/// @param _descriptor 描述信息
function setDescriptor(bytes calldata _descriptor) external;
/// @notice 设置基金存入截止时间
/// @dev This function can only be called by controller
/// @param deadline 最晚存入截止时间
function setDepositDeadline(uint deadline) external;
/// @notice 设置代币交易路径
/// @dev This function can only be called by controller
/// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任
/// @param distToken 目标代币地址
/// @param buy 购买路径(本币->distToken)
/// @param sell 销售路径(distToken->本币)
function setPath(
address distToken,
bytes calldata buy,
bytes calldata sell
) external;
/// @notice 初始化头寸, 允许投资额为0.
/// @dev This function can only be called by controller
/// @param token0 token0 地址
/// @param token1 token1 地址
/// @param fee 手续费率
/// @param tickLower 价格刻度下届
/// @param tickUpper 价格刻度上届
/// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资
/// @param maxPIS 最大价格影响和价格滑点
/// @return liquidity 添加的lp数量
function init(
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint amount,
uint32 maxPIS
) external returns(uint128 liquidity);
/// @notice 投资指定头寸,可选复投手续费
/// @dev This function can only be called by controller
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param amount 投资金额
/// @param collect 是否收集已产生的手续费并复投
/// @param maxPIS 最大价格影响和价格滑点
/// @return liquidity 添加的lp数量
function add(
uint poolIndex,
uint positionIndex,
uint amount,
bool collect,
uint32 maxPIS
) external returns(uint128 liquidity);
/// @notice 撤资指定头寸
/// @dev This function can only be called by controller
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费
/// @param maxPIS 最大价格影响和价格滑点
/// @return amount 撤资获得的基金本币数量
function sub(
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint32 maxPIS
) external returns(uint amount);
/// @notice 调整头寸投资
/// @dev This function can only be called by controller
/// @param poolIndex 池子索引号
/// @param subIndex 要移除的头寸索引号
/// @param addIndex 要添加的头寸索引号
/// @param proportionX128 调整比例,左移128位
/// @param maxPIS 最大价格影响和价格滑点
/// @return liquidity 调整后添加的lp数量
function move(
uint poolIndex,
uint subIndex,
uint addIndex,
uint proportionX128, //以前是按LP数量移除,现在改成按总比例移除,这样前端就不用管实际LP是多少了
uint32 maxPIS
) external returns(uint128 liquidity);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Hotpot V3 状态变量及只读函数
interface IHotPotV3FundState {
/// @notice 控制器合约地址
function controller() external view returns (address);
/// @notice 基金经理地址
function manager() external view returns (address);
/// @notice 基金本币地址
function token() external view returns (address);
/// @notice 32 bytes 基金经理 + 任意长度的简要描述
function descriptor() external view returns (bytes memory);
/// @notice 基金锁定期
function lockPeriod() external view returns (uint);
/// @notice 基金经理收费基线
function baseLine() external view returns (uint);
/// @notice 基金经理收费比例
function managerFee() external view returns (uint);
/// @notice 基金存入截止时间
function depositDeadline() external view returns (uint);
/// @notice 获取最新存入时间
/// @param account 目标地址
/// @return 最新存入时间
function lastDepositTime(address account) external view returns (uint);
/// @notice 总投入数量
function totalInvestment() external view returns (uint);
/// @notice owner的投入数量
/// @param owner 用户地址
/// @return 投入本币的数量
function investmentOf(address owner) external view returns (uint);
/// @notice 指定头寸的资产数量
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return 以本币计价的头寸资产数量
function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint);
/// @notice 指定pool的资产数量
/// @param poolIndex 池子索引号
/// @return 以本币计价的池子资产数量
function assetsOfPool(uint poolIndex) external view returns(uint);
/// @notice 总资产数量
/// @return 以本币计价的总资产数量
function totalAssets() external view returns (uint);
/// @notice 基金本币->目标代币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币购买路径
function buyPath(address _token) external view returns (bytes memory);
/// @notice 目标代币->基金本币 的购买路径
/// @param _token 目标代币地址
/// @return 符合uniswap v3格式的目标代币销售路径
function sellPath(address _token) external view returns (bytes memory);
/// @notice 获取池子地址
/// @param index 池子索引号
/// @return 池子地址
function pools(uint index) external view returns(address);
/// @notice 头寸信息
/// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸
/// @param poolIndex 池子索引号
/// @param positionIndex 头寸索引号
/// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届
function positions(uint poolIndex, uint positionIndex)
external
view
returns(
bool isEmpty,
int24 tickLower,
int24 tickUpper
);
/// @notice pool数组长度
function poolsLength() external view returns(uint);
/// @notice 指定池子的头寸数组长度
/// @param poolIndex 池子索引号
/// @return 头寸数组长度
function positionsLength(uint poolIndex) external view returns(uint);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Hotpot V3 用户操作接口定义
/// @notice 存入(deposit)函数适用于ERC20基金; 如果是ETH基金(内部会转换为WETH9),应直接向基金合约转账;
interface IHotPotV3FundUserActions {
/// @notice 用户存入基金本币
/// @param amount 存入数量
/// @return share 用户获得的基金份额
function deposit(uint amount) external returns(uint share);
/// @notice 用户取出指定份额的本币
/// @param share 取出的基金份额数量
/// @param amountMin 最小提取值
/// @param deadline 最晚交易时间
/// @return amount 返回本币数量
function withdraw(uint share, uint amountMin, uint deadline) external returns(uint amount);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint64
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint64 {
uint256 internal constant Q64 = 0x10000000000000000;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.7.5;
pragma abicoder v2;
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
import "@uniswap/v3-core/contracts/libraries/FixedPoint128.sol";
import "./FixedPoint64.sol";
import '@uniswap/v3-core/contracts/libraries/TickMath.sol';
import "@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol";
import "@uniswap/v3-periphery/contracts/libraries/Path.sol";
library PathPrice {
using Path for bytes;
/// @notice 获取目标代币当前价格的平方根
/// @param path 兑换路径
/// @return sqrtPriceX96 价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格
function getSqrtPriceX96(
bytes memory path,
address uniV3Factory
) internal view returns (uint sqrtPriceX96){
require(path.length > 0, "IPL");
sqrtPriceX96 = FixedPoint96.Q96;
uint _nextSqrtPriceX96;
uint32[] memory secondAges = new uint32[](2);
secondAges[0] = 0;
secondAges[1] = 1;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee)));
(_nextSqrtPriceX96,,,,,,) = pool.slot0();
sqrtPriceX96 = tokenIn > tokenOut
? FullMath.mulDiv(sqrtPriceX96, FixedPoint96.Q96, _nextSqrtPriceX96)
: FullMath.mulDiv(sqrtPriceX96, _nextSqrtPriceX96, FixedPoint96.Q96);
// decide whether to continue or terminate
if (path.hasMultiplePools())
path = path.skipToken();
else
break;
}
}
/// @notice 获取目标代币预言机价格的平方根
/// @param path 兑换路径
/// @return sqrtPriceX96Last 预言机价格的平方根(X 2^96),给定兑换路径的 tokenOut / tokenIn 的价格
function getSqrtPriceX96Last(
bytes memory path,
address uniV3Factory
) internal view returns (uint sqrtPriceX96Last){
require(path.length > 0, "IPL");
sqrtPriceX96Last = FixedPoint96.Q96;
uint _nextSqrtPriceX96;
uint32[] memory secondAges = new uint32[](2);
secondAges[0] = 0;
secondAges[1] = 1;
while (true) {
(address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool();
IUniswapV3Pool pool = IUniswapV3Pool(PoolAddress.computeAddress(uniV3Factory, PoolAddress.getPoolKey(tokenIn, tokenOut, fee)));
// sqrtPriceX96Last
(int56[] memory tickCumulatives,) = pool.observe(secondAges);
_nextSqrtPriceX96 = TickMath.getSqrtRatioAtTick(int24(tickCumulatives[0] - tickCumulatives[1]));
sqrtPriceX96Last = tokenIn > tokenOut
? FullMath.mulDiv(sqrtPriceX96Last, FixedPoint96.Q96, _nextSqrtPriceX96)
: FullMath.mulDiv(sqrtPriceX96Last, _nextSqrtPriceX96, FixedPoint96.Q96);
// decide whether to continue or terminate
if (path.hasMultiplePools())
path = path.skipToken();
else
break;
}
}
/// @notice 验证交易滑点是否满足条件
/// @param path 兑换路径
/// @param uniV3Factory uniswap v3 factory
/// @param maxSqrtSlippage 最大滑点,最大值: 1e4
/// @return 当前价
function verifySlippage(
bytes memory path,
address uniV3Factory,
uint32 maxSqrtSlippage
) internal view returns(uint) {
uint last = getSqrtPriceX96Last(path, uniV3Factory);
uint current = getSqrtPriceX96(path, uniV3Factory);
if(last > current) require(current > FullMath.mulDiv(maxSqrtSlippage, last, 1e4), "VS");
return current;
}
}
|
@inheritdoc IManagerActions
|
function sub(
address fund,
uint poolIndex,
uint positionIndex,
uint proportionX128,
uint deadline
) external override checkDeadline(deadline) onlyManager(fund) returns(uint amount){
return IHotPotV3Fund(fund).sub(poolIndex, positionIndex, proportionX128, maxPIS);
}
| 416,962
|
./full_match/1/0x40B910Acd369794092917fCb730651105F05a90A/sources/foo.sol
|
Redeem Approve Token on best exchange
|
function harvest(GnosisSafe safe) external override onlyHarvesters(safe) {
uint256 amountBefore = rewardsToken.balanceOf(address(safe));
safe.call(address(rewards), abi.encodeWithSelector(rewards.getReward.selector), "failed to withdraw");
uint256 amountAfter = rewardsToken.balanceOf(address(safe));
uint256 balance = amountAfter - amountBefore;
require(balance > 0, "balance was 0");
SafeHelper.approve(safe, ERC20(path[0]), address(SUSHI), balance);
uint256 amount = ExchangeHelper.amountOutFor(SUSHI, path, balance);
if (amount == 0) {
return;
}
safe,
SUSHI,
balance,
(amount * (1000 - 20)) / 1000,
path,
address(safe),
block.timestamp + 180
);
emit Harvested(safe, path[path.length - 1], amountsOut[amountsOut.length - 1]);
}
| 17,098,893
|
./full_match/11155111/0xc7355ec2377b560CA132Ce16c1D7930E4d56e486/sources/_balancer-labs/v2-interfaces/contracts/solidity-utils/helpers/BalancerErrors.sol
|
First, we need to compute the ASCII representation of the error code. We assume that it is in the 0-999 range, so we only need to convert three digits. To convert the digits to ASCII, we add 0x30, the value for the '0' character. With the individual characters, we can now construct the full string. We first append the '' character (0x23) to the prefix. In the case of 'BAL', it results in 0x42414c23 ('TEN') Then, we shift this by 24 (to provide space for the 3 bytes of the error code), and add the characters to it, each shifted by a multiple of 8. The revert reason is then shifted left by 200 bits (256 minus the length of the string, 7 characters 8 bits per character = 56) to locate it in the most significant part of the 256 slot (the beginning of a byte array). We can now encode the reason in memory, which can be safely overwritten as we're about to revert. The encoded message will have the following layout: [ revert reason identifier ] [ string location offset ] [ string length ] [ string contents ] The Solidity revert reason identifier is 0x08c739a0, the function selector of the Error(string) function. We also write zeroes to the next 28 bytes of memory, but those are about to be overwritten. Next is the offset to the location of the string, which will be placed immediately after (20 bytes away). The string length is fixed: 7 characters. Finally, the string itself is stored. Even if the string is only 7 bytes long, we need to return a full 32 byte slot containing it. The length of the encoded message is therefore 4 + 32 + 32 + 32 = 100.
|
function _require(
bool condition,
uint256 errorCode,
bytes3 prefix
}
}
assembly {
let units := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let tenths := add(mod(errorCode, 10), 0x30)
errorCode := div(errorCode, 10)
let hundreds := add(mod(errorCode, 10), 0x30)
let formattedPrefix := shl(24, add(0x23, shl(8, prefixUint)))
let revertReason := shl(200, add(formattedPrefix, add(add(units, shl(8, tenths)), shl(16, hundreds))))
mstore(0x0, 0x08c379a000000000000000000000000000000000000000000000000000000000)
mstore(0x04, 0x0000000000000000000000000000000000000000000000000000000000000020)
mstore(0x24, 7)
mstore(0x44, revertReason)
revert(0, 100)
}
| 3,816,406
|
pragma solidity ^0.4.19;
// File: contracts/IPFSEvents.sol
contract IPFSEvents {
event HashAdded(string hash, uint ttl);
event HashRemoved(string hash);
event MetadataObjectAdded(string hash);
event MetadataObjectRemoved(string hash);
}
// File: contracts/Multimember.sol
contract Multimember {
// TYPES
// struct for the status of a pending operation.
struct PendingState {
uint yetNeeded;
uint membersDone;
uint index;
}
// EVENTS
// this contract only has seven types of events: it can accept a confirmation, in which case
// we record member and operation (hash) alongside it.
event Confirmation(address member, bytes32 operation);
event Revoke(address member, bytes32 operation);
// some others are in the case of an member changing.
event MemberChanged(address oldMember, address newMember);
event MemberAdded(address newMember);
event MemberRemoved(address oldMember);
// the last one is emitted if the required signatures change
event RequirementChanged(uint newRequirement);
// MODIFIERS
// simple single-sig function modifier.
modifier onlymember {
if (isMember(msg.sender))
_;
}
// multi-sig function modifier: the operation must have an intrinsic hash in order
// that later attempts can be realised as the same underlying operation and
// thus count as confirmations.
modifier onlymanymembers(bytes32 _operation) {
if (confirmAndCheck(_operation))
_;
}
// METHODS
// constructor is given number of sigs required to do protected "onlymanymembers" transactions
// as well as the selection of addresses capable of confirming them.
function Multimember(address[] _members, uint _required) public {
m_numMembers = _members.length + 1;
m_members[1] = uint(msg.sender);
m_memberIndex[uint(msg.sender)] = 1;
for (uint i = 0; i < _members.length; ++i) {
m_members[2 + i] = uint(_members[i]);
m_memberIndex[uint(_members[i])] = 2 + i;
}
m_required = _required;
}
// Revokes a prior confirmation of the given operation
function revoke(bytes32 _operation) external {
uint memberIndex = m_memberIndex[uint(msg.sender)];
// make sure they're an member
if (memberIndex == 0)
return;
uint memberIndexBit = 2**memberIndex;
var pending = m_pending[_operation];
if (pending.membersDone & memberIndexBit > 0) {
pending.yetNeeded++;
pending.membersDone -= memberIndexBit;
Revoke(msg.sender, _operation);
}
}
// Replaces an member `_from` with another `_to`.
function changeMember(address _from, address _to) onlymanymembers(keccak256(_from,_to)) external {
if (isMember(_to))
return;
uint memberIndex = m_memberIndex[uint(_from)];
if (memberIndex == 0)
return;
clearPending();
m_members[memberIndex] = uint(_to);
m_memberIndex[uint(_from)] = 0;
m_memberIndex[uint(_to)] = memberIndex;
MemberChanged(_from, _to);
}
function addMember(address _member) onlymanymembers(keccak256(_member)) public {
if (isMember(_member))
return;
clearPending();
if (m_numMembers >= MAXMEMBERS)
reorganizeMembers();
if (m_numMembers >= MAXMEMBERS)
return;
m_numMembers++;
m_members[m_numMembers] = uint(_member);
m_memberIndex[uint(_member)] = m_numMembers;
MemberAdded(_member);
}
function removeMember(address _member) onlymanymembers(keccak256(_member)) public {
uint memberIndex = m_memberIndex[uint(_member)];
if (memberIndex == 0)
return;
if (m_required > m_numMembers - 1)
return;
m_members[memberIndex] = 0;
m_memberIndex[uint(_member)] = 0;
clearPending();
reorganizeMembers(); //make sure m_numMembers is equal to the number of members and always points to the optimal free slot
MemberRemoved(_member);
}
function changeRequirement(uint _newRequired) onlymanymembers(keccak256(_newRequired)) external {
if (_newRequired > m_numMembers)
return;
m_required = _newRequired;
clearPending();
RequirementChanged(_newRequired);
}
function isMember(address _addr) public constant returns (bool) {
return m_memberIndex[uint(_addr)] > 0;
}
function hasConfirmed(bytes32 _operation, address _member) external constant returns (bool) {
var pending = m_pending[_operation];
uint memberIndex = m_memberIndex[uint(_member)];
// make sure they're an member
if (memberIndex == 0)
return false;
// determine the bit to set for this member.
uint memberIndexBit = 2**memberIndex;
return !(pending.membersDone & memberIndexBit == 0);
}
// INTERNAL METHODS
function confirmAndCheck(bytes32 _operation) internal returns (bool) {
// determine what index the present sender is:
uint memberIndex = m_memberIndex[uint(msg.sender)];
// make sure they're an member
if (memberIndex == 0)
return;
var pending = m_pending[_operation];
// if we're not yet working on this operation, switch over and reset the confirmation status.
if (pending.yetNeeded == 0) {
// reset count of confirmations needed.
pending.yetNeeded = m_required;
// reset which members have confirmed (none) - set our bitmap to 0.
pending.membersDone = 0;
pending.index = m_pendingIndex.length++;
m_pendingIndex[pending.index] = _operation;
}
// determine the bit to set for this member.
uint memberIndexBit = 2**memberIndex;
// make sure we (the message sender) haven't confirmed this operation previously.
if (pending.membersDone & memberIndexBit == 0) {
Confirmation(msg.sender, _operation);
// ok - check if count is enough to go ahead.
if (pending.yetNeeded <= 1) {
// enough confirmations: reset and run interior.
delete m_pendingIndex[m_pending[_operation].index];
delete m_pending[_operation];
return true;
} else {
// not enough: record that this member in particular confirmed.
pending.yetNeeded--;
pending.membersDone |= memberIndexBit;
}
}
}
function reorganizeMembers() private returns (bool) {
uint free = 1;
while (free < m_numMembers) {
while (free < m_numMembers && m_members[free] != 0) {
free++;
}
while (m_numMembers > 1 && m_members[m_numMembers] == 0) {
m_numMembers--;
}
if (free < m_numMembers && m_members[m_numMembers] != 0 && m_members[free] == 0) {
m_members[free] = m_members[m_numMembers];
m_memberIndex[m_members[free]] = free;
m_members[m_numMembers] = 0;
}
}
}
function clearPending() internal {
uint length = m_pendingIndex.length;
for (uint i = 0; i < length; ++i) {
if (m_pendingIndex[i] != 0) {
delete m_pending[m_pendingIndex[i]];
}
}
delete m_pendingIndex;
}
// FIELDS
// the number of members that must confirm the same operation before it is run.
uint public m_required;
// pointer used to find a free slot in m_members
uint public m_numMembers;
// list of members
uint[256] m_members;
uint constant MAXMEMBERS = 250;
// index on the list of members to allow reverse lookup
mapping(uint => uint) m_memberIndex;
// the ongoing operations.
mapping(bytes32 => PendingState) m_pending;
bytes32[] m_pendingIndex;
}
// File: contracts/IPFSProxy.sol
contract IPFSProxy is IPFSEvents, Multimember {
uint public persistLimit;
event PersistLimitChanged(uint limit);
event ContractAdded(address pubKey,uint startBlock);
event ContractRemoved(address pubKey);
/**
* @dev Constructor - adds the owner of the contract to the list of valid members
*/
function IPFSProxy(address[] _members,uint _required, uint _persistlimit) Multimember (_members, _required) public {
setTotalPersistLimit(_persistlimit);
for (uint i = 0; i < _members.length; ++i) {
MemberAdded(_members[i]);
}
addContract(this,block.number);
}
/**
* @dev Add hash to persistent storage
* @param _ipfsHash The ipfs hash to propagate.
* @param _ttl amount of time is seconds to persist this. 0 = infinite
*/
function addHash(string _ipfsHash, uint _ttl) public onlymember {
HashAdded(_ipfsHash,_ttl);
}
/**
* @dev Remove hash from persistent storage
* @param _ipfsHash The ipfs hash to propagate.
*/
function removeHash(string _ipfsHash) public onlymember {
HashRemoved(_ipfsHash);
}
/**
* Add a contract to watch list. Each proxy will then
* watch it for HashAdded and HashRemoved events
* and cache these events
* @param _contractAddress The contract address.
* @param _startBlock The startblock where to look for events.
*/
function addContract(address _contractAddress,uint _startBlock) public onlymember {
ContractAdded(_contractAddress,_startBlock);
}
/**
* @dev Remove contract from watch list
*/
function removeContract(address _contractAddress) public onlymember {
require(_contractAddress != address(this));
ContractRemoved(_contractAddress);
}
/**
* Add a metadata of an object. Each proxy will then
* read the ipfs hash file with the metadata about the object and parse it
*/
function addMetadataObject(string _metadataHash) public onlymember {
HashAdded(_metadataHash,0);
MetadataObjectAdded(_metadataHash);
}
/**
* removed a metadata of an object.
*/
function removeMetadataObject(string _metadataHash) public onlymember {
HashRemoved(_metadataHash);
MetadataObjectRemoved(_metadataHash);
}
/**
* @dev set total allowed upload
*
**/
function setTotalPersistLimit (uint _limit) public onlymanymembers(keccak256(_limit)) {
persistLimit = _limit;
PersistLimitChanged(_limit);
}
}
|
Replaces an member `_from` with another `_to`.
|
function changeMember(address _from, address _to) onlymanymembers(keccak256(_from,_to)) external {
if (isMember(_to))
return;
uint memberIndex = m_memberIndex[uint(_from)];
if (memberIndex == 0)
return;
clearPending();
m_members[memberIndex] = uint(_to);
m_memberIndex[uint(_from)] = 0;
m_memberIndex[uint(_to)] = memberIndex;
MemberChanged(_from, _to);
}
| 1,353,156
|
./full_match/1/0x06242Df49008EBcb523B5d0E0aDBB1350AEB28e2/sources/contracts/SeoriGenerative.sol
|
maxSupply changed to constant
|
function setMaxSupply(uint256 _maxSupply) public onlyOwner {
maxSupply = _maxSupply;
}
| 8,349,428
|
./full_match/1/0x1807e79594A19de9a887f0A1448F4AB4c347B763/sources/src/module/governance-pool/Nouns.sol
|
Helper that determines if a bid is eligible for a refund Canceled or vetoed proposals are always refundable. canceled vetoed pending, active, or updatable states should never be refundable since voting is either in progress or has not started 0 == Pending, 1 == Active, 10 == Updatable
|
function _refundable(uint256 _pId, bool _voteCast) internal view returns (bool) {
uint256 state = NounsGovernanceV2(_cfg.externalDAO).state(_pId);
if (state == 2) {
return true;
}
if (state == 8) {
return true;
}
if (state == 0 || state == 1 || state == 10) {
return false;
}
}
| 17,042,446
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.