file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// Verified using https://dapp.tools
// hevm: flattened sources of src/DexC2CGateway.sol
pragma solidity ^0.4.24;
////// lib/ds-auth/src/auth.sol
// 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.23; */
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized");
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
////// lib/ds-math/src/math.sol
/// 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; */
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint 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(uint x, uint n) internal pure returns (uint 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);
}
}
}
}
////// lib/ds-token/lib/ds-stop/lib/ds-note/src/note.sol
/// note.sol -- the `note' modifier, for logging calls as events
// 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.23; */
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint256 wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
uint256 wad;
assembly {
foo := calldataload(4)
bar := calldataload(36)
wad := callvalue
}
emit LogNote(msg.sig, msg.sender, foo, bar, wad, msg.data);
_;
}
}
////// lib/ds-token/lib/ds-stop/src/stop.sol
/// stop.sol -- mixin for enable/disable functionality
// Copyright (C) 2017 DappHub, LLC
// 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.23; */
/* import "ds-auth/auth.sol"; */
/* import "ds-note/note.sol"; */
contract DSStop is DSNote, DSAuth {
bool public stopped;
modifier stoppable {
require(!stopped, "ds-stop-is-stopped");
_;
}
function stop() public auth note {
stopped = true;
}
function start() public auth note {
stopped = false;
}
}
////// lib/ds-token/lib/erc20/src/erc20.sol
/// erc20.sol -- API for the ERC20 token standard
// See <https://github.com/ethereum/EIPs/issues/20>.
// This file likely does not meet the threshold of originality
// required for copyright to apply. As a result, this is free and
// unencumbered software belonging to the public domain.
/* pragma solidity >0.4.20; */
contract ERC20Events {
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
}
contract ERC20 is ERC20Events {
function totalSupply() public view returns (uint);
function balanceOf(address guy) public view returns (uint);
function allowance(address src, address guy) public view returns (uint);
function approve(address guy, uint wad) public returns (bool);
function transfer(address dst, uint wad) public returns (bool);
function transferFrom(
address src, address dst, uint wad
) public returns (bool);
}
////// lib/ds-token/src/base.sol
/// base.sol -- basic ERC20 implementation
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// 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.23; */
/* import "erc20/erc20.sol"; */
/* import "ds-math/math.sol"; */
contract DSTokenBase is ERC20, DSMath {
uint256 _supply;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _approvals;
constructor(uint supply) public {
_balances[msg.sender] = supply;
_supply = supply;
}
function totalSupply() public view returns (uint) {
return _supply;
}
function balanceOf(address src) public view returns (uint) {
return _balances[src];
}
function allowance(address src, address guy) public view returns (uint) {
return _approvals[src][guy];
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
if (src != msg.sender) {
require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
require(_balances[src] >= wad, "ds-token-insufficient-balance");
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function approve(address guy, uint wad) public returns (bool) {
_approvals[msg.sender][guy] = wad;
emit Approval(msg.sender, guy, wad);
return true;
}
}
////// lib/ds-token/src/token.sol
/// token.sol -- ERC20 implementation with minting and burning
// Copyright (C) 2015, 2016, 2017 DappHub, LLC
// 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.23; */
/* import "ds-stop/stop.sol"; */
/* import "./base.sol"; */
contract DSToken is DSTokenBase(0), DSStop {
bytes32 public symbol;
uint256 public decimals = 18; // standard token precision. override to customize
constructor(bytes32 symbol_) public {
symbol = symbol_;
}
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
function approve(address guy) public stoppable returns (bool) {
return super.approve(guy, uint(-1));
}
function approve(address guy, uint wad) public stoppable returns (bool) {
return super.approve(guy, wad);
}
function transferFrom(address src, address dst, uint wad)
public
stoppable
returns (bool)
{
if (src != msg.sender && _approvals[src][msg.sender] != uint(-1)) {
require(_approvals[src][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[src][msg.sender] = sub(_approvals[src][msg.sender], wad);
}
require(_balances[src] >= wad, "ds-token-insufficient-balance");
_balances[src] = sub(_balances[src], wad);
_balances[dst] = add(_balances[dst], wad);
emit Transfer(src, dst, wad);
return true;
}
function push(address dst, uint wad) public {
transferFrom(msg.sender, dst, wad);
}
function pull(address src, uint wad) public {
transferFrom(src, msg.sender, wad);
}
function move(address src, address dst, uint wad) public {
transferFrom(src, dst, wad);
}
function mint(uint wad) public {
mint(msg.sender, wad);
}
function burn(uint wad) public {
burn(msg.sender, wad);
}
function mint(address guy, uint wad) public auth stoppable {
_balances[guy] = add(_balances[guy], wad);
_supply = add(_supply, wad);
emit Mint(guy, wad);
}
function burn(address guy, uint wad) public auth stoppable {
if (guy != msg.sender && _approvals[guy][msg.sender] != uint(-1)) {
require(_approvals[guy][msg.sender] >= wad, "ds-token-insufficient-approval");
_approvals[guy][msg.sender] = sub(_approvals[guy][msg.sender], wad);
}
require(_balances[guy] >= wad, "ds-token-insufficient-balance");
_balances[guy] = sub(_balances[guy], wad);
_supply = sub(_supply, wad);
emit Burn(guy, wad);
}
// Optional token name
bytes32 public name = "";
function setName(bytes32 name_) public auth {
name = name_;
}
}
////// lib/ds-value/lib/ds-thing/src/thing.sol
// thing.sol - `auth` with handy mixins. your things should be DSThings
// Copyright (C) 2017 DappHub, LLC
// 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.23; */
/* import 'ds-auth/auth.sol'; */
/* import 'ds-note/note.sol'; */
/* import 'ds-math/math.sol'; */
contract DSThing is DSAuth, DSNote, DSMath {
function S(string memory s) internal pure returns (bytes4) {
return bytes4(keccak256(abi.encodePacked(s)));
}
}
////// lib/ds-value/src/value.sol
/// value.sol - a value is a simple thing, it can be get and set
// Copyright (C) 2017 DappHub, LLC
// 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.23; */
/* import 'ds-thing/thing.sol'; */
contract DSValue is DSThing {
bool has;
bytes32 val;
function peek() public view returns (bytes32, bool) {
return (val,has);
}
function read() public view returns (bytes32) {
bytes32 wut; bool haz;
(wut, haz) = peek();
assert(haz);
return wut;
}
function poke(bytes32 wut) public note auth {
val = wut;
has = true;
}
function void() public note auth { // unset the value
has = false;
}
}
////// src/EscrowDataInterface.sol
/* pragma solidity ^0.4.24; */
/* import "ds-token/token.sol"; */
interface EscrowDataInterface
{
///@notice Create and fund a new escrow.
function createEscrow(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint32 _paymentWindowInSeconds
) external returns(bool);
function getEscrow(
bytes32 _tradeHash
) external returns(bool, uint32, uint128);
function removeEscrow(
bytes32 _tradeHash
) external returns(bool);
function updateSellerCanCancelAfter(
bytes32 _tradeHash,
uint32 _paymentWindowInSeconds
) external returns(bool);
function increaseTotalGasFeesSpentByRelayer(
bytes32 _tradeHash,
uint128 _increaseGasFees
) external returns(bool);
}
////// src/DexC2C.sol
/* pragma solidity ^0.4.24; */
/* import "ds-token/token.sol"; */
/* import "ds-auth/auth.sol"; */
/* import "ds-value/value.sol"; */
// import "ds-math/math.sol";
/* import "./EscrowDataInterface.sol"; */
contract DexC2C is DSAuth
{
DSToken constant internal ETH_TOKEN_ADDRESS = DSToken(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
bool public enableMake = true;
EscrowDataInterface escrowData;
// address escrowData;
address public gateway;
address public arbitrator;
address public relayer;
address public signer;
uint32 public requestCancellationMinimumTime;
uint8 constant ACTION_TYPE_BUYER_PAID = 0x01;
uint8 constant ACTION_TYPE_SELLER_CANCEL = 0x02;
uint8 constant ACTION_TYPE_RELEASE = 0x03;
uint8 constant ACTION_TYPE_RESOLVE = 0x04;
mapping(address => bool) public listTokens;
mapping(address => uint256) feesAvailableForWithdraw;
// mapping(bytes32 => bool) withdrawAddresses;
mapping(address => DSValue) public tokenPriceFeed;
// event SetGateway(address _gateway);
// event SetEscrowData(address _escrowData);
// event SetToken(address caller, DSToken token, bool enable);
// event ResetOwner(address curr, address old);
// event ResetRelayer(address curr, address old);
// event ResetSigner(address curr, address old);
// event ResetArbitrator(address curr, address ocl);
// event ResetEnabled(bool curr, bool old);
// event WithdrawAddressApproved(DSToken token, address addr, bool approve);
// event LogWithdraw(DSToken token, address receiver, uint amnt);
event CreatedEscrow(address indexed _buyer, address indexed _seller, bytes32 indexed _tradeHash, DSToken _token);
event CancelledBySeller(address indexed _buyer, address indexed _seller, bytes32 indexed _tradeHash, DSToken _token);
event BuyerPaid(address indexed _buyer, address indexed _seller, bytes32 indexed _tradeHash, DSToken _token);
event Release(address indexed _buyer, address indexed _seller, bytes32 indexed _tradeHash, DSToken _token);
event DisputeResolved(address indexed _buyer, address indexed _seller, bytes32 indexed _tradeHash, DSToken _token);
struct EscrowParams{
bytes32 tradeId;
DSToken tradeToken;
address buyer;
address seller;
uint256 value;
uint16 fee;
uint32 paymentWindowInSeconds;
uint32 expiry;
uint8 v;
bytes32 r;
bytes32 s;
address caller;
}
struct Escrow{
bytes32 tradeHash;
bool exists;
uint32 sellerCanCancelAfter;
uint128 totalGasFeesSpentByRelayer;
}
modifier onlyGateway(){
require(msg.sender == gateway, "Must be gateway contract");
_;
}
constructor(EscrowDataInterface _escrowData, address _signer) DSAuth() public{
// require(_escrowData != address(0x00), "EscrowData address must exists");
arbitrator = msg.sender;
relayer = msg.sender;
signer = _signer;
escrowData = _escrowData;
listTokens[ETH_TOKEN_ADDRESS] = true;
requestCancellationMinimumTime = 2 hours;
}
function setPriceFeed(DSToken _token, DSValue _priceFeed) public auth{
// require(_priceFeed != address(0x00), "price feed must not be null");
tokenPriceFeed[_token] = _priceFeed;
}
function setRelayer(address _relayer) public auth {
// require(_relayer != address(0x00), "Relayer is null");
// emit ResetRelayer(_relayer, relayer);
relayer = _relayer;
}
function setSigner(address _signer) public auth {
// require(_signer != address(0x00), "Signer is null");
// emit ResetSigner(_signer, signer);
signer = _signer;
}
function setArbitrator(address _arbitrator) public auth{
// require(_arbitrator != address(0x00), "Arbitrator is null");
// emit ResetArbitrator(arbitrator, _arbitrator);
arbitrator = _arbitrator;
}
function setGateway(address _gateway) public auth returns(bool){
// require(_gateway != address(0x00), "Gateway address must valid");
gateway = _gateway;
// emit SetGateway(_gateway);
}
function setEscrowData(EscrowDataInterface _escrowData) public auth returns(bool){
// require(_escrowData != address(0x00), "EscrowData address must valid");
escrowData = _escrowData;
// emit SetEscrowData(_escrowData);
}
function setToken(DSToken token, bool enable) public auth returns(bool){
// require(gateway != address(0x00), "Set gateway first");
// require(token != address(0x00), "Token address can not be 0x00");
listTokens[token] = enable;
// emit SetToken(msg.sender, token, enable);
}
function setRequestCancellationMinimumTime(
uint32 _newRequestCancellationMinimumTime
) external auth {
requestCancellationMinimumTime = _newRequestCancellationMinimumTime;
}
function enabled() public view returns(bool) {
return enableMake;
}
function setEnabled(bool _enableMake) public auth{
require(_enableMake != enableMake, "Enabled same value");
// emit ResetEnabled(enableMake, _enableMake);
enableMake = _enableMake;
}
function getTokenAmount(DSToken _token, uint ethWad) public view returns(uint){
require(tokenPriceFeed[address(_token)] != address(0x00), "the token has not price feed(to eth).");
DSValue feed = tokenPriceFeed[address(_token)];
return wmul(ethWad, uint(feed.read()));
}
function checkCanResolveDispute(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint8 _v,
bytes32 _r,
bytes32 _s,
uint8 _buyerPercent,
address _caller
) private view {
require(_caller == arbitrator, "Must be arbitrator");
bytes32 tradeHash = keccak256(abi.encodePacked(_tradeId, _token, _buyer, _seller, _value, _fee));
bytes32 invitationHash = keccak256(abi.encodePacked(tradeHash, ACTION_TYPE_RESOLVE, _buyerPercent));
address _signature = recoverAddress(invitationHash, _v, _r, _s);
require(_signature == _buyer || _signature == _seller, "Must be buyer or seller");
}
function resolveDispute(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint8 _v,
bytes32 _r,
bytes32 _s,
uint8 _buyerPercent,
address _caller
) external onlyGateway {
checkCanResolveDispute(_tradeId, _token, _buyer, _seller, _value, _fee, _v, _r, _s,_buyerPercent, _caller);
Escrow memory escrow = getEscrow(_tradeId, _token, _buyer, _seller, _value, _fee);
require(escrow.exists, "Escrow does not exists");
require(_buyerPercent <= 100, "BuyerPercent must be 100 or lower");
doResolveDispute(
escrow.tradeHash,
_token,
_buyer,
_seller,
_value,
_buyerPercent,
escrow.totalGasFeesSpentByRelayer
);
}
uint16 constant GAS_doResolveDispute = 36100;
function doResolveDispute(
bytes32 _tradeHash,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint8 _buyerPercent,
uint128 _totalGasFeesSpentByRelayer
) private {
uint256 _totalFees = _totalGasFeesSpentByRelayer;
if(_token == ETH_TOKEN_ADDRESS){
_totalFees += (GAS_doResolveDispute * uint128(tx.gasprice));
} else {
///如果交易非ETH需要按照汇率换算成等值的token
_totalFees += getTokenAmount(_token, GAS_doResolveDispute * uint(tx.gasprice));
}
require(_value - _totalFees <= _value, "Overflow error");
feesAvailableForWithdraw[_token] += _totalFees;
escrowData.removeEscrow(_tradeHash);
emit DisputeResolved(_buyer, _seller, _tradeHash, _token);
if(_token == ETH_TOKEN_ADDRESS){
if (_buyerPercent > 0){
_buyer.transfer((_value - _totalFees) * _buyerPercent / 100);
}
if (_buyerPercent < 100){
_seller.transfer((_value - _totalFees) * (100 - _buyerPercent) / 100);
}
}else{
if (_buyerPercent > 0){
require(_token.transfer(_buyer, (_value - _totalFees) * _buyerPercent / 100));
}
if (_buyerPercent < 100){
require(_token.transfer(_seller, (_value - _totalFees) * (100 - _buyerPercent) / 100));
}
}
}
uint16 constant GAS_relayBaseCost = 35500;
function relay(
bytes32 _tradeId,
DSToken _tradeToken,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint128 _maxGasPrice,
uint8 _v,
bytes32 _r,
bytes32 _s,
uint8 _actionType,
address _caller
) public onlyGateway returns (bool) {
address _relayedSender = getRelayedSender(_tradeId, _actionType, _maxGasPrice, _v, _r, _s);
uint128 _additionalGas = uint128(_caller == relayer ? GAS_relayBaseCost : 0);
if(_relayedSender == _buyer){
if(_actionType == ACTION_TYPE_BUYER_PAID){
return doBuyerPaid(_tradeId, _tradeToken, _buyer, _seller, _value, _fee, _caller, _additionalGas);
}
}else if(_relayedSender == _seller) {
if(_actionType == ACTION_TYPE_SELLER_CANCEL){
return doSellerCancel(_tradeId, _tradeToken, _buyer, _seller, _value, _fee, _caller, _additionalGas);
}else if(_actionType == ACTION_TYPE_RELEASE){
return doRelease(_tradeId, _tradeToken, _buyer, _seller, _value, _fee, _caller, _additionalGas);
}
}else{
require(_relayedSender == _seller, "Unrecognised party");
return false;
}
}
function createEscrow(
bytes32 _tradeId,
DSToken _tradeToken,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint32 _paymentWindowInSeconds,
uint32 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s,
address _caller
) external payable onlyGateway returns (bool){
EscrowParams memory params;
params.tradeId = _tradeId;
params.tradeToken = _tradeToken;
params.buyer = _buyer;
params.seller = _seller;
params.value = _value;
params.fee = _fee;
params.paymentWindowInSeconds = _paymentWindowInSeconds;
params.expiry = _expiry;
params.v = _v;
params.r = _r;
params.s = _s;
params.caller = _caller;
return doCreateEscrow(params);
}
function doCreateEscrow(
EscrowParams params
) internal returns (bool) {
require(enableMake, "DESC2C is not enable");
require(listTokens[params.tradeToken], "Token is not allowed");
// require(params.caller == params.seller, "Must be seller");
bytes32 _tradeHash = keccak256(
abi.encodePacked(params.tradeId, params.tradeToken, params.buyer, params.seller, params.value, params.fee));
bytes32 _invitationHash = keccak256(abi.encodePacked(_tradeHash, params.paymentWindowInSeconds, params.expiry));
require(recoverAddress(_invitationHash, params.v, params.r, params.s) == signer, "Must be signer");
require(block.timestamp < params.expiry, "Signature has expired");
emit CreatedEscrow(params.buyer, params.seller, _tradeHash, params.tradeToken);
return escrowData.createEscrow(params.tradeId, params.tradeToken, params.buyer, params.seller, params.value,
params.fee, params.paymentWindowInSeconds);
}
function buyerPaid(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
address _caller
) external onlyGateway returns(bool) {
require(_caller == _buyer, "Must by buyer");
return doBuyerPaid(_tradeId, _token, _buyer, _seller, _value, _fee, _caller, 0);
}
function release(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
address _caller
) external onlyGateway returns(bool){
require(_caller == _seller, "Must by seller");
doRelease(_tradeId, _token, _buyer, _seller, _value, _fee, _caller, 0);
}
uint16 constant GAS_doRelease = 46588;
function doRelease(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
address _caller,
uint128 _additionalGas
) internal returns(bool){
Escrow memory escrow = getEscrow(_tradeId, _token, _buyer, _seller, _value, _fee);
require(escrow.exists, "Escrow does not exists");
uint128 _gasFees = escrow.totalGasFeesSpentByRelayer;
if(_caller == relayer){
if(_token == ETH_TOKEN_ADDRESS){
_gasFees += (GAS_doRelease + _additionalGas) * uint128(tx.gasprice);
}else{
uint256 relayGas = (GAS_doRelease + _additionalGas) * tx.gasprice;
_gasFees += uint128(getTokenAmount(_token, relayGas));
}
}else{
require(_caller == _seller, "Must by seller");
}
escrowData.removeEscrow(escrow.tradeHash);
transferMinusFees(_token, _buyer, _value, _gasFees, _fee);
emit Release(_buyer, _seller, escrow.tradeHash, _token);
return true;
}
uint16 constant GAS_doBuyerPaid = 35944;
function doBuyerPaid(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
address _caller,
uint128 _additionalGas
) internal returns(bool){
Escrow memory escrow = getEscrow(_tradeId, _token, _buyer, _seller, _value, _fee);
require(escrow.exists, "Escrow not exists");
if(_caller == relayer){
if(_token == ETH_TOKEN_ADDRESS){
require(escrowData.increaseTotalGasFeesSpentByRelayer(escrow.tradeHash, (GAS_doBuyerPaid + _additionalGas) * uint128(tx.gasprice)));
}else{
uint256 relayGas = (GAS_doBuyerPaid + _additionalGas) * tx.gasprice;
require(escrowData.increaseTotalGasFeesSpentByRelayer(escrow.tradeHash, uint128(getTokenAmount(_token, relayGas))));
}
}else{
require(_caller == _buyer, "Must be buyer");
}
require(escrowData.updateSellerCanCancelAfter(escrow.tradeHash, requestCancellationMinimumTime));
emit BuyerPaid(_buyer, _seller, escrow.tradeHash, _token);
return true;
}
function sellerCancel(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint32 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s,
address _caller
) external onlyGateway returns (bool){
require(_caller == _seller, "Must be seller");
bytes32 tradeHash = keccak256(abi.encodePacked(_tradeId, _token, _buyer, _seller, _value, _fee));
bytes32 invitationHash = keccak256(abi.encodePacked(tradeHash, ACTION_TYPE_SELLER_CANCEL, _expiry));
require(recoverAddress(invitationHash, _v, _r, _s) == signer, "Must be signer");
return doSellerCancel(_tradeId, _token, _buyer, _seller, _value, _fee, _caller, 0);
}
uint16 constant GAS_doSellerCancel = 46255;
function doSellerCancel(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
address _caller,
uint128 _additionalGas
) private returns (bool) {
Escrow memory escrow = getEscrow(_tradeId, _token, _buyer, _seller, _value, _fee);
require(escrow.exists, "Escrow does not exists");
if(block.timestamp < escrow.sellerCanCancelAfter){
return false;
}
uint128 _gasFees = escrow.totalGasFeesSpentByRelayer;
if(_caller == relayer){
if(_token == ETH_TOKEN_ADDRESS){
_gasFees += (GAS_doSellerCancel + _additionalGas) * uint128(tx.gasprice);
}else{
uint256 relayGas = (GAS_doSellerCancel + _additionalGas) * tx.gasprice;
_gasFees += uint128(getTokenAmount(_token, relayGas));
}
}else{
require(_caller == _seller, "Must be buyer");
}
escrowData.removeEscrow(escrow.tradeHash);
emit CancelledBySeller(_buyer, _seller, escrow.tradeHash, _token);
transferMinusFees(_token, _seller, _value, _gasFees, 0);
return true;
}
function transferMinusFees(
DSToken _token,
address _to,
uint256 _value,
uint128 _totalGasFeesSpentByRelayer,
uint16 _fee
) private {
uint256 _totalFees = (_value * _fee / 10000);
_totalFees += _totalGasFeesSpentByRelayer;
if(_value - _totalFees > _value) {
return;
}
feesAvailableForWithdraw[_token] += _totalFees;
if(_token == ETH_TOKEN_ADDRESS){
_to.transfer(_value - _totalFees);
}else{
require(_token.transfer(_to, _value - _totalFees));
}
}
function getFeesAvailableForWithdraw(
DSToken _token
) public view auth returns(uint256){
// bytes32 key = keccak256(abi.encodePacked(_token, msg.sender));
// require(withdrawAddresses[key], "unauthorization address!");
return feesAvailableForWithdraw[_token];
}
// function approvedWithdrawAddress(DSToken _token, address _addr, bool _approve) public auth returns(bool){
// // require(_addr != address(0x00), "Approved address is null");
// bytes32 key = keccak256(abi.encodePacked(_token, _addr));
// require(withdrawAddresses[key] != _approve, "Address has approved");
// withdrawAddresses[key] = _approve;
// // emit WithdrawAddressApproved(_token, _addr, _approve);
// return true;
// }
function withdraw(DSToken _token, uint _amnt, address _receiver) external auth returns(bool){
// require(withdrawAddresses[keccak256(abi.encodePacked(_token, _receiver))], "Address not in white list");
require(feesAvailableForWithdraw[_token] > 0, "Fees is 0 or token not exists");
require(_amnt <= feesAvailableForWithdraw[_token], "Amount is higher than amount available");
if(_token == ETH_TOKEN_ADDRESS){
_receiver.transfer(_amnt);
}else{
require(_token.transfer(_receiver, _amnt), "Withdraw failed");
}
// emit LogWithdraw(_token, _receiver, _amnt);
return true;
}
function getEscrow(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee
) private returns(Escrow){
bytes32 _tradeHash = keccak256(abi.encodePacked(_tradeId, _token, _buyer, _seller, _value, _fee));
bool exists;
uint32 sellerCanCancelAfter;
uint128 totalFeesSpentByRelayer;
(exists, sellerCanCancelAfter, totalFeesSpentByRelayer) = escrowData.getEscrow(_tradeHash);
return Escrow(_tradeHash, exists, sellerCanCancelAfter, totalFeesSpentByRelayer);
}
function () public payable{
}
function recoverAddress(
bytes32 _h,
uint8 _v,
bytes32 _r,
bytes32 _s
) internal pure returns (address){
bytes memory _prefix = "\x19Ethereum Signed Message:\n32";
bytes32 _prefixedHash = keccak256(abi.encodePacked(_prefix, _h));
return ecrecover(_prefixedHash, _v, _r, _s);
}
function getRelayedSender(
bytes32 _tradeId,
uint8 _actionType,
uint128 _maxGasPrice,
uint8 _v,
bytes32 _r,
bytes32 _s
) internal view returns(address){
bytes32 _hash = keccak256(abi.encodePacked(_tradeId, _actionType, _maxGasPrice));
if(tx.gasprice > _maxGasPrice){
return;
}
return recoverAddress(_hash, _v, _r, _s);
}
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
uint constant WAD = 10 ** 18;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
}
////// src/DexC2CGateway.sol
/* pragma solidity ^0.4.24; */
/* import "./DexC2C.sol"; */
/* import "ds-token/token.sol"; */
/* import "ds-auth/auth.sol"; */
contract DexC2CGateway is DSAuth{
DSToken constant internal ETH_TOKEN_ADDRESS = DSToken(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
DexC2C dexc2c;
event ResetDexC2C(address curr, address old);
struct BatchRelayParams{
bytes32[] _tradeId;
DSToken[] _token;
address[] _buyer;
address[] _seller;
uint256[] _value;
uint16[] _fee;
uint128[] _maxGasPrice;
uint8[] _v;
bytes32[] _r;
bytes32[] _s;
uint8[] _actionType;
}
constructor() DSAuth() public{
}
function setDexC2C(DexC2C _dexc2c) public auth{
require(_dexc2c != address(0x00), "DexC2C is null");
dexc2c = _dexc2c;
emit ResetDexC2C(_dexc2c, dexc2c);
}
function resolveDispute(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint8 _v,
bytes32 _r,
bytes32 _s,
uint8 _buyerPercent
) public{
dexc2c.resolveDispute(_tradeId, _token, _buyer, _seller, _value, _fee, _v, _r, _s, _buyerPercent, msg.sender);
}
function relay(
bytes32 _tradeId,
DSToken _token,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint128 _maxGasPrice,
uint8 _v,
bytes32 _r,
bytes32 _s,
uint8 _actionType
) public returns(bool){
return dexc2c.relay(_tradeId, _token, _buyer, _seller, _value, _fee, _maxGasPrice, _v, _r, _s, _actionType, msg.sender);
}
function createEscrow(
bytes32 _tradeId,
DSToken _tradeToken,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint32 _paymentWindowInSeconds,
uint32 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s
) public payable returns(bool) {
if(_tradeToken == ETH_TOKEN_ADDRESS){
require(msg.value == _value && msg.value > 0, "Incorrect token sent");
}else{
require(_tradeToken.transferFrom(_seller, dexc2c, _value), "Can not transfer token from seller");
}
return doCreateEscrow(_tradeId, _tradeToken, _buyer, _seller, _value, _fee, _paymentWindowInSeconds, _expiry, _v, _r, _s, msg.sender);
}
function sellerCancel(
bytes32 _tradeId,
DSToken _tradeToken,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint32 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s
) public returns(bool){
return dexc2c.sellerCancel(_tradeId, _tradeToken, _buyer, _seller, _value, _fee, _expiry, _v, _r, _s, msg.sender);
}
function buyerPaid(
bytes32 _tradeId,
DSToken _tradeToken,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee
)public returns(bool){
return dexc2c.buyerPaid(_tradeId, _tradeToken, _buyer, _seller, _value, _fee, msg.sender);
}
function release(
bytes32 _tradeId,
DSToken _tradeToken,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee
)public returns(bool){
return dexc2c.release(_tradeId, _tradeToken, _buyer, _seller, _value, _fee, msg.sender);
}
function doCreateEscrow(
bytes32 _tradeId,
DSToken _tradeToken,
address _buyer,
address _seller,
uint256 _value,
uint16 _fee,
uint32 _paymentWindowInSeconds,
uint32 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s,
address _caller
) internal returns(bool){
return dexc2c.createEscrow.value(msg.value)(
_tradeId,
_tradeToken,
_buyer,
_seller,
_value,
_fee,
_paymentWindowInSeconds,
_expiry,
_v,
_r,
_s,
_caller
);
}
function recoverAddress(
bytes32 _h,
uint8 _v,
bytes32 _r,
bytes32 _s
) internal pure returns (address){
// bytes memory _prefix = "\x19Ethereum Signed Message:\n32";
// bytes32 _prefixedHash = keccak256(abi.encodePacked(_prefix, _h));
// return ecrecover(_prefixedHash, _v, _r, _s);
return ecrecover(_h, _v, _r, _s);
}
function getRelayedSender(
bytes32 _tradeId,
uint8 _actionType,
uint128 _maxGasPrice,
uint8 _v,
bytes32 _r,
bytes32 _s
) internal view returns(address){
bytes32 _hash = keccak256(abi.encodePacked(_tradeId, _actionType, _maxGasPrice));
if(tx.gasprice > _maxGasPrice){
return;
}
return recoverAddress(_hash, _v, _r, _s);
}
}
|
require(withdrawAddresses[keccak256(abi.encodePacked(_token, _receiver))], "Address not in white list");
|
function withdraw(DSToken _token, uint _amnt, address _receiver) external auth returns(bool){
require(feesAvailableForWithdraw[_token] > 0, "Fees is 0 or token not exists");
require(_amnt <= feesAvailableForWithdraw[_token], "Amount is higher than amount available");
if(_token == ETH_TOKEN_ADDRESS){
_receiver.transfer(_amnt);
require(_token.transfer(_receiver, _amnt), "Withdraw failed");
}
}
| 1,004,804 |
./full_match/77/0x37A3f02721939C7357779A7E1Bd91f1be61203b5/sources/contracts/LP.sol
|
Core: Change amount of reserved by conditions funds. initReserve reinforcement of the condition. profitReserve amount of reserves that was not demand according to the condition results/ pool win calc oracle rewards calc DAO rewards add profit to segmentTree remove loss from segmentTree excluding canceled conditions (when profitReserve = 0)
|
function addReserve(
uint128 initReserve,
uint128 profitReserve,
uint48 leaf
) external override onlyCore {
if (profitReserve >= initReserve) {
uint128 profit = profitReserve - initReserve;
uint128 oracleRewards = (profit * oracleFee) / multiplier;
uint128 daoRewards = (profit * daoFee) / multiplier;
totalDaoRewards += daoRewards;
addLimit(profit - (oracleRewards + daoRewards), leaf);
if (profitReserve > 0) {
remove(initReserve - profitReserve);
}
}
}
| 5,046,588 |
pragma solidity ^0.4.24;
/* SLUGROAD
Simple Fomo Game with fair scaling.
Slugroad has 3 different tracks: different networks, with different settings.
This is the Ethereum track.
A car drives to hyperspeed.
Speed starts at a min of 100mph and rises to a max 1000mph over 7 days.
Buy Slugs with ETH.
Slugs persist between loops!
Get ETH divs from other Slug buys.
Use your earned ETH to Time Warp, buying Slugs for a cheaper price.
Throw Slugs on the windshield to stop the car (+6 minute timer) and become the Driver.
As the driver, you earn miles according to your speed.
Trade 6000 miles for 1% of the pot.
Once the car reaches hyperspeed, the Driver starts draining the pot.
0.01% is drained every second, up to a maximum of 36% in one hour.
The Driver can jump out of the window at any moment to secure his gains.
Once the Driver jumps out, the car drives freely.
Timer resets to 1 hour.
The wheel goes to the starter, but he gets no reward if the car crosses the finish line.
If someone else throws Slugs before the Driver jumps out, he takes the wheel.
Timer resets to 6 minutes, and the Driver gets nothing!
If the Driver keeps the wheel for one hour in hyperspeed, he gets the full pot.
Then we move to loop 2 immediately, on a 7 days timer.
Slug price: (0.000025 + (loopchest/10000)) / loop
The price of slugs initially rises then lowers through a loop, as the pot is drained.
With each new loop, the price of slugs decrease significantly (cancel out early advantage)
Players can Skip Ahead with the ether they won.
Slug price changes to (0.000025 + (loopchest/10000)) / (loop + 1)
Traveling through time will always be more fruitful than buying.
Pot split:
- 60% divs
- 20% slugBank (reserve pot)
- 10% loopChest (round pot)
- 10% snailthrone
*/
contract Slugroad {
using SafeMath for uint;
/* Events */
event WithdrewBalance (address indexed player, uint eth);
event BoughtSlug (address indexed player, uint eth, uint slug);
event SkippedAhead (address indexed player, uint eth, uint slug);
event TradedMile (address indexed player, uint eth, uint mile);
event BecameDriver (address indexed player, uint eth);
event TookWheel (address indexed player, uint eth);
event ThrewSlug (address indexed player);
event JumpedOut (address indexed player, uint eth);
event TimeWarped (address indexed player, uint indexed loop, uint eth);
event NewLoop (address indexed player, uint indexed loop);
event PaidThrone (address indexed player, uint eth);
event BoostedPot (address indexed player, uint eth);
/* Constants */
uint256 constant public RACE_TIMER_START = 604800; //7 days
uint256 constant public HYPERSPEED_LENGTH = 3600; //1 hour
uint256 constant public THROW_SLUG_REQ = 200; //slugs to become driver
uint256 constant public DRIVER_TIMER_BOOST = 360; //6 minutes
uint256 constant public SLUG_COST_FLOOR = 0.000025 ether; //4 zeroes
uint256 constant public DIV_SLUG_COST = 10000; //loop pot divider
uint256 constant public TOKEN_MAX_BUY = 1 ether; //max allowed eth in one buy transaction
uint256 constant public MIN_SPEED = 100;
uint256 constant public MAX_SPEED = 1000;
uint256 constant public ACCEL_FACTOR = 672; //inverse of acceleration per second
uint256 constant public MILE_REQ = 6000; //required miles for 1% of the pot
address constant public SNAILTHRONE = 0x261d650a521103428C6827a11fc0CBCe96D74DBc;
/* Variables */
// Race starter
address public starter;
bool public gameStarted;
// loop, timer, driver
uint256 public loop;
uint256 public timer;
address public driver;
// Are we in hyperspeed?
bool public hyperSpeed = false;
// Last driver claim
uint256 public lastHijack;
// Pots
uint256 public loopChest;
uint256 public slugBank;
uint256 public thronePot;
// Divs for one slug, max amount of slugs
uint256 public divPerSlug;
uint256 public maxSlug;
/* Mappings */
mapping (address => uint256) public slugNest;
mapping (address => uint256) public playerBalance;
mapping (address => uint256) public claimedDiv;
mapping (address => uint256) public mile;
/* Functions */
//-- GAME START --
// Constructor
// Sets msg.sender as starter, to start the game properly
constructor() public {
starter = msg.sender;
gameStarted = false;
}
// StartRace
// Initialize timer
// Set starter as driver (starter can't win or trade miles)
// Buy tokens for value of message
function StartRace() public payable {
require(gameStarted == false);
require(msg.sender == starter);
timer = now.add(RACE_TIMER_START).add(HYPERSPEED_LENGTH);
loop = 1;
gameStarted = true;
lastHijack = now;
driver = starter;
BuySlug();
}
//-- PRIVATE --
// PotSplit
// Called on buy and hatch
// 60% divs, 20% slugBank, 10% loopChest, 10% thronePot
function PotSplit(uint256 _msgValue) private {
divPerSlug = divPerSlug.add(_msgValue.mul(3).div(5).div(maxSlug));
slugBank = slugBank.add(_msgValue.div(5));
loopChest = loopChest.add(_msgValue.div(10));
thronePot = thronePot.add(_msgValue.div(10));
}
// ClaimDiv
// Sends player dividends to his playerBalance
// Adjusts claimable dividends
function ClaimDiv() private {
uint256 _playerDiv = ComputeDiv(msg.sender);
if(_playerDiv > 0){
//Add new divs to claimed divs
claimedDiv[msg.sender] = claimedDiv[msg.sender].add(_playerDiv);
//Send divs to playerBalance
playerBalance[msg.sender] = playerBalance[msg.sender].add(_playerDiv);
}
}
// BecomeDriver
// Gives driver role, and miles to previous driver
function BecomeDriver() private {
//give miles to previous driver
uint256 _mile = ComputeMileDriven();
mile[driver] = mile[driver].add(_mile);
//if we're in hyperspeed, the new driver ends up 6 minutes before hyperspeed
if(now.add(HYPERSPEED_LENGTH) >= timer){
timer = now.add(DRIVER_TIMER_BOOST).add(HYPERSPEED_LENGTH);
emit TookWheel(msg.sender, loopChest);
//else, simply add 6 minutes to timer
} else {
timer = timer.add(DRIVER_TIMER_BOOST);
emit BecameDriver(msg.sender, loopChest);
}
lastHijack = now;
driver = msg.sender;
}
//-- ACTIONS --
// TimeWarp
// Call manually when race is over
// Distributes loopchest and miles to winner, moves to next loop
function TimeWarp() public {
require(gameStarted == true, "game hasn't started yet");
require(now >= timer, "race isn't finished yet");
//give miles to driver
uint256 _mile = ComputeMileDriven();
mile[driver] = mile[driver].add(_mile);
//Reset timer and start new loop
timer = now.add(RACE_TIMER_START).add(HYPERSPEED_LENGTH);
loop = loop.add(1);
//Adjust loop and slug pots
uint256 _nextPot = slugBank.div(2);
slugBank = slugBank.sub(_nextPot);
//Make sure the car isn't driving freely
if(driver != starter){
//Calculate reward
uint256 _reward = loopChest;
//Change loopchest
loopChest = _nextPot;
//Give reward
playerBalance[driver] = playerBalance[driver].add(_reward);
emit TimeWarped(driver, loop, _reward);
//Else, start a new loop with different event
} else {
//Change loopchest
loopChest = loopChest.add(_nextPot);
emit NewLoop(msg.sender, loop);
}
lastHijack = now;
//msg.sender becomes Driver
driver = msg.sender;
}
// BuySlug
// Get token price, adjust maxSlug and divs, give slugs
function BuySlug() public payable {
require(gameStarted == true, "game hasn't started yet");
require(tx.origin == msg.sender, "contracts not allowed");
require(msg.value <= TOKEN_MAX_BUY, "maximum buy = 1 ETH");
require(now <= timer, "race is over!");
//Calculate price and resulting slugs
uint256 _slugBought = ComputeBuy(msg.value, true);
//Adjust player claimed divs
claimedDiv[msg.sender] = claimedDiv[msg.sender].add(_slugBought.mul(divPerSlug));
//Change maxSlug before new div calculation
maxSlug = maxSlug.add(_slugBought);
//Divide incoming ETH
PotSplit(msg.value);
//Add player slugs
slugNest[msg.sender] = slugNest[msg.sender].add(_slugBought);
emit BoughtSlug(msg.sender, msg.value, _slugBought);
//Become driver if player bought at least 200 slugs
if(_slugBought >= 200){
BecomeDriver();
}
}
// SkipAhead
// Functions like BuySlug, using player balance
// Less cost per Slug (+1 loop)
function SkipAhead() public {
require(gameStarted == true, "game hasn't started yet");
ClaimDiv();
require(playerBalance[msg.sender] > 0, "no ether to timetravel");
require(now <= timer, "race is over!");
//Calculate price and resulting slugs
uint256 _etherSpent = playerBalance[msg.sender];
uint256 _slugHatched = ComputeBuy(_etherSpent, false);
//Adjust player claimed divs (reinvest + new slugs) and balance
claimedDiv[msg.sender] = claimedDiv[msg.sender].add(_slugHatched.mul(divPerSlug));
playerBalance[msg.sender] = 0;
//Change maxSlug before new div calculation
maxSlug = maxSlug.add(_slugHatched);
//Divide reinvested ETH
PotSplit(_etherSpent);
//Add player slugs
slugNest[msg.sender] = slugNest[msg.sender].add(_slugHatched);
emit SkippedAhead(msg.sender, _etherSpent, _slugHatched);
//Become driver if player hatched at least 200 slugs
if(_slugHatched >= 200){
BecomeDriver();
}
}
// WithdrawBalance
// Sends player ingame ETH balance to his wallet
function WithdrawBalance() public {
ClaimDiv();
require(playerBalance[msg.sender] > 0, "no ether to withdraw");
uint256 _amount = playerBalance[msg.sender];
playerBalance[msg.sender] = 0;
msg.sender.transfer(_amount);
emit WithdrewBalance(msg.sender, _amount);
}
// ThrowSlug
// Throws slugs on the windshield to claim Driver
function ThrowSlug() public {
require(gameStarted == true, "game hasn't started yet");
require(slugNest[msg.sender] >= THROW_SLUG_REQ, "not enough slugs in nest");
require(now <= timer, "race is over!");
//Call ClaimDiv so ETH isn't blackholed
ClaimDiv();
//Remove slugs
maxSlug = maxSlug.sub(THROW_SLUG_REQ);
slugNest[msg.sender] = slugNest[msg.sender].sub(THROW_SLUG_REQ);
//Adjust msg.sender claimed dividends
claimedDiv[msg.sender] = claimedDiv[msg.sender].sub(THROW_SLUG_REQ.mul(divPerSlug));
emit ThrewSlug(msg.sender);
//Run become driver function
BecomeDriver();
}
// JumpOut
// Driver jumps out of the car to secure his ETH gains
// Give him his miles as well
function JumpOut() public {
require(gameStarted == true, "game hasn't started yet");
require(msg.sender == driver, "can't jump out if you're not in the car!");
require(msg.sender != starter, "starter isn't allowed to be driver");
//give miles to driver
uint256 _mile = ComputeMileDriven();
mile[driver] = mile[driver].add(_mile);
//calculate reward
uint256 _reward = ComputeHyperReward();
//remove reward from pot
loopChest = loopChest.sub(_reward);
//put timer back to 1 hours (+1 hour of hyperspeed)
timer = now.add(HYPERSPEED_LENGTH.mul(2));
//give player his reward
playerBalance[msg.sender] = playerBalance[msg.sender].add(_reward);
//set driver as the starter
driver = starter;
//set lastHijack to reset miles count to 0 (easier on frontend)
lastHijack = now;
emit JumpedOut(msg.sender, _reward);
}
// TradeMile
// Exchanges player miles for part of the pot
function TradeMile() public {
require(mile[msg.sender] >= MILE_REQ, "not enough miles for a reward");
require(msg.sender != starter, "starter isn't allowed to trade miles");
require(msg.sender != driver, "can't trade miles while driver");
//divide player miles by req
uint256 _mile = mile[msg.sender].div(MILE_REQ);
//can't get more than 20% of the pot at once
if(_mile > 20){
_mile = 20;
}
//calculate reward
uint256 _reward = ComputeMileReward(_mile);
//remove reward from pot
loopChest = loopChest.sub(_reward);
//lower player miles by amount spent
mile[msg.sender] = mile[msg.sender].sub(_mile.mul(MILE_REQ));
//give player his reward
playerBalance[msg.sender] = playerBalance[msg.sender].add(_reward);
emit TradedMile(msg.sender, _reward, _mile);
}
// PayThrone
// Sends thronePot to SnailThrone
function PayThrone() public {
uint256 _payThrone = thronePot;
thronePot = 0;
if (!SNAILTHRONE.call.value(_payThrone)()){
revert();
}
emit PaidThrone(msg.sender, _payThrone);
}
// fallback function
// Feeds the slugBank
function() public payable {
slugBank = slugBank.add(msg.value);
emit BoostedPot(msg.sender, msg.value);
}
//-- VIEW --
// ComputeHyperReward
// Returns ETH reward for driving in hyperspeed
// Reward = HYPERSPEED_LENGTH - (timer - now) * 0.01% * loopchest
// 0.01% = /10000
// This will throw before we're in hyperspeed, so account for that in frontend
function ComputeHyperReward() public view returns(uint256) {
uint256 _remainder = timer.sub(now);
return HYPERSPEED_LENGTH.sub(_remainder).mul(loopChest).div(10000);
}
// ComputeSlugCost
// Returns ETH required to buy one slug
// 1 slug = (S_C_FLOOR + (loopchest / DIV_SLUG_COST)) / loop
// On hatch, add 1 to loop
function ComputeSlugCost(bool _isBuy) public view returns(uint256) {
if(_isBuy == true){
return (SLUG_COST_FLOOR.add(loopChest.div(DIV_SLUG_COST))).div(loop);
} else {
return (SLUG_COST_FLOOR.add(loopChest.div(DIV_SLUG_COST))).div(loop.add(1));
}
}
// ComputeBuy
// Returns slugs bought for a given amount of ETH
// True = buy, false = hatch
function ComputeBuy(uint256 _ether, bool _isBuy) public view returns(uint256) {
uint256 _slugCost;
if(_isBuy == true){
_slugCost = ComputeSlugCost(true);
} else {
_slugCost = ComputeSlugCost(false);
}
return _ether.div(_slugCost);
}
// ComputeDiv
// Returns unclaimed divs for a player
function ComputeDiv(address _player) public view returns(uint256) {
//Calculate share of player
uint256 _playerShare = divPerSlug.mul(slugNest[_player]);
//Subtract already claimed divs
_playerShare = _playerShare.sub(claimedDiv[_player]);
return _playerShare;
}
// ComputeSpeed
// Returns current speed
// speed = maxspeed - ((timer - _time - 1 hour) / accelFactor)
function ComputeSpeed(uint256 _time) public view returns(uint256) {
//check we're not in hyperspeed
if(timer > _time.add(HYPERSPEED_LENGTH)){
//check we're not more than 7 days away from end
if(timer.sub(_time) < RACE_TIMER_START){
return MAX_SPEED.sub((timer.sub(_time).sub(HYPERSPEED_LENGTH)).div(ACCEL_FACTOR));
} else {
return MIN_SPEED; //more than 7 days away
}
} else {
return MAX_SPEED; //hyperspeed
}
}
// ComputeMileDriven
// Returns miles driven during this driver session
function ComputeMileDriven() public view returns(uint256) {
uint256 _speedThen = ComputeSpeed(lastHijack);
uint256 _speedNow = ComputeSpeed(now);
uint256 _timeDriven = now.sub(lastHijack);
uint256 _averageSpeed = (_speedNow.add(_speedThen)).div(2);
return _timeDriven.mul(_averageSpeed).div(HYPERSPEED_LENGTH);
}
// ComputeMileReward
// Returns ether reward for a given multiplier of the req
function ComputeMileReward(uint256 _reqMul) public view returns(uint256) {
return _reqMul.mul(loopChest).div(100);
}
// GetNest
// Returns player slugs
function GetNest(address _player) public view returns(uint256) {
return slugNest[_player];
}
// GetMile
// Returns player mile
function GetMile(address _player) public view returns(uint256) {
return mile[_player];
}
// GetBalance
// Returns player balance
function GetBalance(address _player) public view returns(uint256) {
return playerBalance[_player];
}
}
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;
}
}
|
give miles to drivercalculate rewardremove reward from potput timer back to 1 hours (+1 hour of hyperspeed)give player his rewardset driver as the starterset lastHijack to reset miles count to 0 (easier on frontend)
|
function JumpOut() public {
require(gameStarted == true, "game hasn't started yet");
require(msg.sender == driver, "can't jump out if you're not in the car!");
require(msg.sender != starter, "starter isn't allowed to be driver");
uint256 _mile = ComputeMileDriven();
mile[driver] = mile[driver].add(_mile);
uint256 _reward = ComputeHyperReward();
loopChest = loopChest.sub(_reward);
timer = now.add(HYPERSPEED_LENGTH.mul(2));
playerBalance[msg.sender] = playerBalance[msg.sender].add(_reward);
driver = starter;
lastHijack = now;
emit JumpedOut(msg.sender, _reward);
}
| 6,346,524 |
pragma solidity ^0.4.23;
import "./interface/ITRC20.sol";
import "../common/PausableDSAuth.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
/// @title TRC223ReceivingContract - Standard contract implementation for compatibility with TRC223 tokens.
contract TRC223ReceivingContract {
/// @dev Function that is called when a user or another contract wants to transfer funds.
/// @param _from Transaction initiator, analogue of msg.sender
/// @param _value Number of tokens to transfer.
/// @param _data Data containig a function signature and/or parameters
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns (bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public returns (bool);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes _data) public;
}
contract TRC223 {
function transferAndFallback(address to, uint amount, bytes data) public returns (bool ok);
function transferFromAndFallback(address from, address to, uint256 amount, bytes data) public returns (bool ok);
event TRC223Transfer(address indexed from, address indexed to, uint amount, bytes data);
}
contract ISmartToken {
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
/**
* @title Standard TRC20 token (compatible with ITRC20 token)
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
*/
contract GOLD is PausableDSAuth, TRC223, ITRC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
address public newOwner;
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
address public controller;
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
constructor () public {
_symbol = "GOLD";
_decimals = 18;
_name = "Evolution Land Gold";
controller = msg.sender;
}
/**
* @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;
}
/**
* @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];
}
function setName(string name_) public auth {
_name = name_;
}
/**
* @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 transfersAllowed whenNotPaused returns (bool) {
// Alerts the token controller of the transfer
if (isContract(controller)) {
if (!TokenController(controller).onTransfer(msg.sender, to, value))
revert();
}
_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 whenNotPaused returns (bool) {
require(spender != address(0));
// Alerts the token controller of the approve function call
if (isContract(controller)) {
if (!TokenController(controller).onApprove(msg.sender, spender, value))
revert();
}
_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 transfersAllowed whenNotPaused
returns (bool)
{
// Alerts the token controller of the transfer
if (isContract(controller)) {
if (!TokenController(controller).onTransfer(from, to, value))
revert();
}
_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 whenNotPaused
returns (bool)
{
require(spender != address(0));
uint256 newValue = _allowed[msg.sender][spender].add(addedValue);
// Alerts the token controller of the approve function call
if (isContract(controller)) {
if (!TokenController(controller).onApprove(msg.sender, spender, newValue))
revert();
}
_allowed[msg.sender][spender] = newValue;
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 whenNotPaused
returns (bool)
{
require(spender != address(0));
uint256 newValue = _allowed[msg.sender][spender].sub(subtractedValue);
// Alerts the token controller of the approve function call
if (isContract(controller)) {
if (!TokenController(controller).onApprove(msg.sender, spender, newValue))
revert();
}
_allowed[msg.sender][spender] = newValue;
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(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);
emit Mint(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);
emit Burn(account, 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 {
// 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);
}
/**
* @dev Function to mint tokens
* @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 auth whenNotPaused returns (bool) {
_mint(to, value);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burn(address from, uint256 value) public auth whenNotPaused {
_burn(from, value);
}
/*
* TRC 223
* Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload.
*/
function transferFromAndFallback(address _from, address _to, uint256 _amount, bytes _data)
public transfersAllowed
returns (bool success)
{
require(transferFrom(_from, _to, _amount));
if (isContract(_to)) {
TRC223ReceivingContract receiver = TRC223ReceivingContract(_to);
receiver.tokenFallback(_from, _amount, _data);
}
emit TRC223Transfer(_from, _to, _amount, _data);
return true;
}
/*
* TRC 223
* Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload.
* https://github.com/ethereum/EIPs/issues/223
* function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
*/
/// @notice Send `_value` tokens to `_to` from `msg.sender` and trigger
/// tokenFallback if sender is a contract.
/// @dev Function that is called when a user or another contract wants to transfer funds.
/// @param _to Address of token receiver.
/// @param _amount Number of tokens to transfer.
/// @param _data Data to be sent to tokenFallback
/// @return Returns success of function call.
function transferAndFallback(
address _to,
uint256 _amount,
bytes _data)
public transfersAllowed
returns (bool success)
{
require(transfer(_to, _amount));
if (isContract(_to)) {
TRC223ReceivingContract receiver = TRC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _amount, _data);
}
emit TRC223Transfer(msg.sender, _to, _amount, _data);
return true;
}
//////////
// IOwned Methods
//////////
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public auth {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
owner = newOwner;
newOwner = address(0);
}
//////////
// SmartToken Methods
//////////
/**
@dev disables/enables transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTransfers(bool _disable) public auth {
transfersEnabled = !_disable;
}
function issue(address _to, uint256 _amount) public auth whenNotPaused {
mint(_to, _amount);
}
function destroy(address _from, uint256 _amount) public auth whenNotPaused {
_burn(_from, _amount);
}
//////////
// Controller Methods
//////////
/// @notice Changes the controller of the contract
/// @param _newController The new controller of the contract
function changeController(address _newController) public auth {
controller = _newController;
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes _extraData
) public returns (bool success) {
if (!approve(_spender, _amount)) revert();
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
this,
_extraData
);
return true;
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) view internal returns(bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the owner to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address _token) public auth {
if (_token == 0x0) {
address(msg.sender).transfer(address(this).balance);
return;
}
ITRC20 token = ITRC20(_token);
uint balance = token.balanceOf(this);
token.transfer(address(msg.sender), balance);
emit ClaimedTokens(_token, address(msg.sender), balance);
}
function withdrawTokens(ITRC20 _token, address _to, uint256 _amount) public auth
{
assert(_token.transfer(_to, _amount));
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount);
event Mint(address indexed guy, uint wad);
event Burn(address indexed guy, uint wad);
}
|
TRC 223 Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload./
|
function transferFromAndFallback(address _from, address _to, uint256 _amount, bytes _data)
public transfersAllowed
returns (bool success)
{
require(transferFrom(_from, _to, _amount));
if (isContract(_to)) {
TRC223ReceivingContract receiver = TRC223ReceivingContract(_to);
receiver.tokenFallback(_from, _amount, _data);
}
emit TRC223Transfer(_from, _to, _amount, _data);
return true;
}
| 1,763,999 |
// to test issue with nodes breaking with large clients over WS
// fixed in web3 with fragmentationThreshold: 8192
pragma solidity ^0.4.17;
contract BigFreakingContract {
event Transfer(address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
mapping( address => uint ) _balances;
mapping( address => mapping( address => uint ) ) _approvals;
uint public _supply;
constructor( uint initial_balance ) public {
_balances[msg.sender] = initial_balance;
_supply = initial_balance;
}
function totalSupply() public constant returns (uint supply) {
return _supply;
}
function balanceOf( address who ) public constant returns (uint value) {
return _balances[who];
}
function transfer( address to, uint value) public returns (bool ok) {
if( _balances[msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
_balances[msg.sender] -= value;
_balances[to] += value;
emit Transfer( msg.sender, to, value );
return true;
}
function transferFrom( address from, address to, uint value) public returns (bool ok) {
// if you don't have enough balance, throw
if( _balances[from] < value ) {
revert();
}
// if you don't have approval, throw
if( _approvals[from][msg.sender] < value ) {
revert();
}
if( !safeToAdd(_balances[to], value) ) {
revert();
}
// transfer and return true
_approvals[from][msg.sender] -= value;
_balances[from] -= value;
_balances[to] += value;
emit Transfer( from, to, value );
return true;
}
function approve(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function allowance(address owner, address spender) public constant returns (uint _allowance) {
return _approvals[owner][spender];
}
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return (a + b >= a);
}
function isAvailable() public pure returns (bool) {
return false;
}
function approve_1(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_2(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_3(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_4(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_5(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_6(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_7(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_8(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_9(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_10(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_11(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_12(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_13(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_14(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_15(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_16(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_17(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_18(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_19(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_20(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_21(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_22(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_23(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_24(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_25(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_26(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_27(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_28(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_29(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_30(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_31(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_32(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_33(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_34(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_35(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_36(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_37(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_38(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_39(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_40(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_41(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_42(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_43(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_44(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_45(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_46(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_47(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_48(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_49(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_50(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_51(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_52(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_53(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_54(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_55(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_56(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_57(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_58(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_59(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_60(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_61(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_62(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_63(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_64(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_65(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_66(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_67(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_68(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_69(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_70(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_71(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_72(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_73(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_74(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_75(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_76(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_77(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_78(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_79(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_80(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_81(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_82(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_83(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_84(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_85(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_86(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_87(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_88(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_89(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_90(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_91(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_92(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_93(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_94(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_95(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_96(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_97(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_98(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_99(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_100(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_101(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_102(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_103(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_104(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_105(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_106(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_107(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_108(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_109(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_110(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_111(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_112(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_113(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_114(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_115(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_116(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_117(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_118(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_119(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_120(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_121(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_122(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_123(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_124(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_125(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_126(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_127(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_128(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_129(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_130(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_131(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_132(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_133(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_134(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_135(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_136(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_137(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_138(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_139(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_140(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_141(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_142(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_143(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_144(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_145(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_146(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_147(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_148(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_149(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_150(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_151(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_152(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_153(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_154(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_155(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_156(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_157(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_158(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_159(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_160(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_161(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_162(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_163(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_164(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_165(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_166(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_167(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_168(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_169(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_170(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_171(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_172(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_173(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_174(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_175(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_176(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_177(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_178(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_179(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_180(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_181(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_182(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_183(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_184(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_185(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_186(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_187(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_188(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_189(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_190(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_191(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_192(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_193(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_194(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_195(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_196(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_197(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_198(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_199(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_200(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_201(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_202(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_203(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_204(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_205(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_206(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_207(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_208(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_209(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_210(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_211(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_212(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_213(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_214(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_215(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_216(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_217(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_218(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_219(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_220(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_221(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_222(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_223(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_224(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_225(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_226(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_227(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_228(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_229(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_230(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_231(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_232(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_233(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_234(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_235(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_236(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_237(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_238(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_239(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_240(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_241(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_242(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_243(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_244(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_245(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_246(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_247(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_248(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_249(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_250(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_251(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_252(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_253(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_254(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_255(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_256(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_257(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_258(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_259(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_260(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_261(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_262(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_263(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_264(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_265(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_266(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_267(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_268(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_269(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_270(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_271(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_272(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_273(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_274(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_275(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_276(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_277(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_278(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_279(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_280(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_281(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_282(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_283(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_284(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_285(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_286(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_287(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_288(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_289(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_290(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_291(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_292(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_293(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_294(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_295(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_296(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_297(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_298(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_299(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_300(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_301(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_302(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_303(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_304(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_305(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_306(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_307(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_308(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_309(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_310(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_311(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_312(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_313(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_314(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_315(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_316(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_317(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_318(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_319(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_320(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_321(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_322(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_323(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_324(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_325(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_326(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_327(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_328(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_329(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_330(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_331(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_332(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_333(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_334(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_335(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_336(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_337(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_338(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_339(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_340(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_341(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_342(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_343(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_344(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_345(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_346(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_347(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_348(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_349(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_350(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_351(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_352(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_353(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_354(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_355(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_356(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_357(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_358(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_359(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_360(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_361(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_362(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_363(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_364(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_365(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_366(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_367(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_368(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_369(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_370(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_371(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_372(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_373(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_374(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_375(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_376(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_377(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_378(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_379(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_380(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_381(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_382(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_383(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_384(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_385(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_386(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_387(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_388(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_389(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_390(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_391(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_392(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_393(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_394(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_395(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_396(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_397(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_398(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_399(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_400(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_401(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_402(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_403(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_404(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_405(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_406(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_407(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_408(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_409(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_410(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_411(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_412(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_413(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_414(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_415(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_416(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_417(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_418(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_419(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_420(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_421(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_422(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_423(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_424(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_425(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_426(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_427(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_428(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_429(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_430(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_431(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_432(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_433(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_434(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_435(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_436(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_437(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_438(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_439(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_440(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_441(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_442(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_443(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_444(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_445(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_446(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_447(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_448(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_449(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_450(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_451(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_452(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_453(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_454(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_455(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_456(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_457(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_458(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_459(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_460(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_461(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_462(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_463(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_464(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_465(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_466(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_467(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_468(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_469(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_470(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_471(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_472(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_473(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_474(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_475(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_476(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_477(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_478(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_479(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_480(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_481(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_482(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_483(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_484(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_485(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_486(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_487(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_488(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_489(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_490(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_491(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_492(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_493(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_494(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_495(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_496(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_497(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_498(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_499(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_500(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_501(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_502(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_503(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_504(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_505(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_506(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_507(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_508(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_509(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_510(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_511(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_512(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_513(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_514(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_515(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_516(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_517(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_518(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_519(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_520(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_521(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_522(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_523(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_524(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_525(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_526(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_527(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_528(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_529(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_530(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_531(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_532(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_533(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_534(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_535(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_536(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_537(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_538(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_539(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_540(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_541(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_542(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_543(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_544(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_545(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_546(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_547(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_548(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_549(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_550(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_551(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_552(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_553(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_554(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_555(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_556(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_557(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_558(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_559(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_560(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_561(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_562(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_563(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_564(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_565(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_566(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_567(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_568(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_569(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_570(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_571(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_572(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_573(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_574(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_575(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_576(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_577(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_578(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_579(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_580(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_581(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_582(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_583(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_584(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_585(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_586(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_587(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_588(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_589(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_590(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_591(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_592(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_593(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_594(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_595(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_596(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_597(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_598(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_599(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_600(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_601(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_602(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_603(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_604(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_605(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_606(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_607(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_608(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_609(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_610(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_611(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_612(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_613(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_614(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_615(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_616(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_617(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_618(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_619(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_620(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_621(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_622(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_623(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_624(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_625(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_626(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_627(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_628(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_629(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_630(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_631(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_632(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_633(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_634(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_635(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_636(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_637(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_638(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_639(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_640(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_641(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_642(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_643(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_644(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_645(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_646(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_647(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_648(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_649(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_650(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_651(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_652(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_653(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_654(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_655(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_656(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_657(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_658(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_659(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_660(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_661(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_662(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_663(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_664(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_665(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_666(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_667(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_668(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_669(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_670(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_671(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_672(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_673(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_674(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_675(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_676(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_677(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_678(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_679(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_680(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_681(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_682(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_683(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_684(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_685(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_686(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_687(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_688(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_689(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_690(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_691(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_692(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_693(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_694(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_695(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_696(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_697(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_698(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_699(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_700(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_701(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_702(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_703(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_704(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_705(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_706(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_707(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_708(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_709(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_710(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_711(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_712(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_713(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_714(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_715(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_716(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_717(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_718(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_719(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_720(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_721(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_722(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_723(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_724(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_725(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_726(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_727(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_728(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_729(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_730(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_731(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_732(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_733(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_734(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_735(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_736(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_737(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_738(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_739(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_740(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_741(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_742(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_743(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_744(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_745(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_746(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_747(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_748(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_749(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_750(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_751(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_752(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_753(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_754(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_755(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_756(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_757(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_758(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_759(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_760(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_761(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_762(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_763(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_764(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_765(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_766(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_767(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_768(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_769(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_770(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_771(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_772(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_773(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_774(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_775(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_776(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_777(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_778(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_779(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_780(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_781(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_782(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_783(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_784(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_785(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_786(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_787(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_788(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_789(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_790(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_791(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_792(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_793(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_794(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_795(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_796(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_797(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_798(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_799(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_800(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_801(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_802(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_803(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_804(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_805(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_806(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_807(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_808(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_809(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_810(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_811(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_812(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_813(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_814(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_815(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_816(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_817(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_818(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_819(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_820(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_821(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_822(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_823(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_824(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_825(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_826(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_827(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_828(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_829(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_830(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_831(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_832(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_833(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_834(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_835(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_836(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_837(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_838(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_839(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_840(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_841(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_842(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_843(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_844(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_845(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_846(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_847(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_848(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_849(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_850(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_851(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_852(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_853(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_854(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_855(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_856(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_857(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_858(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_859(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_860(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_861(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_862(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_863(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_864(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_865(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_866(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_867(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_868(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_869(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_870(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_871(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_872(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_873(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_874(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_875(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_876(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_877(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_878(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_879(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_880(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_881(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_882(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_883(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_884(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_885(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_886(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_887(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_888(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_889(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_890(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_891(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_892(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_893(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_894(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_895(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_896(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_897(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_898(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_899(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_900(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
function approve_901(address spender, uint value) public returns (bool ok) {
// TODO: should increase instead
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
}
|
TODO: should increase instead
|
function approve_193(address spender, uint value) public returns (bool ok) {
_approvals[msg.sender][spender] = value;
emit Approval( msg.sender, spender, value );
return true;
}
| 6,453,906 |
./partial_match/1/0x70f648c442eFa7007E7e4323e14e7Bdc800Bd0cf/sources/MainnetUsdpToUsdpAssimilator.sol
|
Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number and y is unsigned 256-bit integer number. Revert on overflow. x signed 64.64-bit fixed point number y uint256 value return signed 64.64-bit fixed point number/ We rely on overflow behavior here
|
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
}
}
| 9,381,652 |
/**
*Submitted for verification at Etherscan.io on 2020-10-04
*/
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.6.12;
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
require(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
require(b > 0);
uint c = a / b;
require(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(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(uint a, uint b) internal pure returns (uint) {
return a >= b ? a : b;
}
function min256(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
}
interface ISupplyController {
function mint(address token, address owner, uint amount) external;
}
interface IADXToken {
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOf(address spender) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function supplyController() external view returns (ISupplyController);
}
contract ADXLoyaltyPoolToken {
using SafeMath for uint;
// ERC20 stuff
// Constants
string public constant name = "AdEx Loyalty";
uint8 public constant decimals = 18;
string public symbol = "ADX-LOYALTY";
// Mutable variables
uint public totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// EIP 2612
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
// ERC20 events
event Approval(address indexed owner, address indexed spender, uint amount);
event Transfer(address indexed from, address indexed to, uint amount);
function balanceOf(address owner) public view returns (uint balance) { //inject PUBLIC FUNC TO EXTERNAL
return balances[owner];
}
function transfer(address to, uint amount) public returns (bool success) { //inject PUBLIC FUNC TO EXTERNAL
require(to != address(this), 'BAD_ADDRESS');
balances[msg.sender] = balances[msg.sender].sub(amount);
balances[to] = balances[to].add(amount);
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(address from, address to, uint amount) public returns (bool success) { //inject PUBLIC FUNC TO EXTERNAL
balances[from] = balances[from].sub(amount);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount);
balances[to] = balances[to].add(amount);
emit Transfer(from, to, amount);
return true;
}
function approve(address spender, uint amount) public returns (bool success) { //inject PUBLIC FUNC TO EXTERNAL
allowed[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function allowance(address owner, address spender) public view returns (uint remaining) { //inject PUBLIC FUNC TO EXTERNAL
return allowed[owner][spender];
}
// EIP 2612
function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) public { //inject PUBLIC FUNC TO EXTERNAL
require(deadline >= block.timestamp, 'DEADLINE_EXPIRED');
bytes32 digest = keccak256(abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline))
));
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, 'INVALID_SIGNATURE');
allowed[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// Inner
function innerMint(address owner, uint amount) internal {
totalSupply = totalSupply.add(amount);
balances[owner] = balances[owner].add(amount);
// Because of https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
emit Transfer(address(0), owner, amount);
}
function innerBurn(address owner, uint amount) internal {
totalSupply = totalSupply.sub(amount);
balances[owner] = balances[owner].sub(amount);
emit Transfer(owner, address(0), amount);
}
// Pool functionality
event LogSetGovernance(address indexed addr, bool hasGovt, uint time);
event LogSetIncentive(uint incentive, uint time);
IADXToken public ADXToken;
uint public incentivePerTokenPerAnnum;
uint public lastMintTime;
uint public maxTotalADX;
mapping (address => bool) public governance;
constructor(IADXToken token, uint incentive, uint cap) public {
ADXToken = token;
incentivePerTokenPerAnnum = incentive;
maxTotalADX = cap;
governance[msg.sender] = true;
lastMintTime = block.timestamp;
// EIP 2612
uint chainId;
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
emit LogSetGovernance(msg.sender, true, block.timestamp);
emit LogSetIncentive(incentive, block.timestamp);
}
// Governance functions
function setGovernance(address addr, bool hasGovt) public { //inject PUBLIC FUNC TO EXTERNAL
require(governance[msg.sender], 'NOT_GOVERNANCE');
governance[addr] = hasGovt;
emit LogSetGovernance(addr, hasGovt, block.timestamp);
}
// This doesn't trigger a mint because otherwise we risk of being unable to setIncentive to 0
// if minting is impossible
// It's the better tradeoff to make - and the issue of front-running mintIncnetive with setIncentive(0) can
// be solved by timelocking the governance
function setIncentive(uint newIncentive) public { //inject PUBLIC FUNC TO EXTERNAL
require(governance[msg.sender], 'NOT_GOVERNANCE');
incentivePerTokenPerAnnum = newIncentive;
lastMintTime = block.timestamp;
emit LogSetIncentive(newIncentive, block.timestamp);
}
function setSymbol(string calldata newSymbol) external {
require(governance[msg.sender], 'NOT_GOVERNANCE');
symbol = newSymbol;
}
function setMaxTotalADX(uint newMaxTotalADX) public { //inject PUBLIC FUNC TO EXTERNAL
require(governance[msg.sender], 'NOT_GOVERNANCE');
maxTotalADX = newMaxTotalADX;
}
// Pool stuff
// There are a few notable items in how minting works
// 1) if ADX is sent to the LoyaltyPool in-between mints, it will calculate the incentive as if this amount
// has been there the whole time since the last mint
// 2) Compounding is happening when mint is called, so essentially when entities enter/leave/trigger it manually
function toMint() public view returns (uint) { //inject PUBLIC FUNC TO EXTERNAL
if (block.timestamp <= lastMintTime) return 0;
uint totalADX = ADXToken.balanceOf(address(this));
return (block.timestamp - lastMintTime)
.mul(totalADX)
.mul(incentivePerTokenPerAnnum)
.div(365 days * 10e17);
}
function shareValue() public view returns (uint) { //inject PUBLIC FUNC TO EXTERNAL
if (totalSupply == 0) return 0;
return ADXToken.balanceOf(address(this))
.add(this.toMint())
.mul(10e17)
.div(totalSupply);
}
function mintIncentive() public {
if (incentivePerTokenPerAnnum == 0) return;
uint amountToMint = this.toMint();
if (amountToMint == 0) return;
lastMintTime = block.timestamp;
ADXToken.supplyController().mint(address(ADXToken), address(this), amountToMint);
}
function enter(uint256 amount) public { //inject PUBLIC FUNC TO EXTERNAL
// Please note that minting has to be in the beginning so that we take it into account
// when using ADXToken.balanceOf()
// Minting makes an external call but it's to a trusted contract (ADXToken)
mintIncentive();
uint totalADX = ADXToken.balanceOf(address(this));
require(totalADX.add(amount) <= maxTotalADX, 'REACHED_MAX_TOTAL_ADX');
// The totalADX == 0 check here should be redudnant; the only way to get totalSupply to a nonzero val is by adding ADX
if (totalSupply == 0 || totalADX == 0) {
innerMint(msg.sender, amount);
} else {
uint256 newShares = amount.mul(totalSupply).div(totalADX);
innerMint(msg.sender, newShares);
}
require(ADXToken.transferFrom(msg.sender, address(this), amount));
}
function leaveInner(uint256 shares) internal {
uint256 totalADX = ADXToken.balanceOf(address(this));
uint256 adxAmount = shares.mul(totalADX).div(totalSupply);
innerBurn(msg.sender, shares);
require(ADXToken.transfer(msg.sender, adxAmount));
}
function leave(uint256 shares) public { //inject PUBLIC FUNC TO EXTERNAL
mintIncentive();
leaveInner(shares);
}
// Guarantees ADX can be taken out even if minting is failing
function emergencyLeave(uint256 shares) public { //inject PUBLIC FUNC TO EXTERNAL
leaveInner(shares);
}
}
|
inject PUBLIC FUNC TO EXTERNAL
|
function shareValue() public view returns (uint) {
| 2,519,502 |
./full_match/1/0x8b8bf083fD1837486c141681E10Ea61D0f3cD692/sources/src/StaticATokenLM.sol
|
@inheritdoc IStaticATokenLM
|
function aToken() external view returns (IERC20) {
return _aToken;
}
| 5,016,533 |
// @Author: Yuexin Xiang
// @Email: [email protected]
//Remix Compiler 0.4.25
pragma solidity >=0.4.22 <0.7.0;
contract Verification{
//Start to verify the signed string
function Verify_String(bytes memory signed_string) public returns (address){
//This is a signed string data
//e.g. bytes memory signed_string =hex"..."
bytes32 data_h;
//Divide the data into three parts
bytes32 r = BytesToBytes32(Slice(signed_string,0,32));
bytes32 s = BytesToBytes32(Slice(signed_string,32,32));
byte v = Slice(signed_string,64,1)[0];
return Ecrecover_Verify(data_h, r, s, v);
}
function Slice(bytes memory Data,uint Start,uint Len) public returns(bytes) {
bytes memory Byt = new bytes(Len);
for(uint i = 0; i < Len; i++){
Byt[i] = Data[i + Start];
}
return Byt;
}
//Using ecrecover to recover the public key
function Ecrecover_Verify(bytes32 data_h, bytes32 r,bytes32 s, byte v1) public returns(address Addr) {
uint8 v = uint8(v1) + 27;
//This is data hash
// e.g. data_a = "..."
Addr = ecrecover(data_a, v, r, s);
}
//Transfer bytes to bytes32
function BytesToBytes32(bytes memory Source) public returns(bytes32 ResultVerify) {
assembly{
ResultVerify :=mload(add(Source,32))
}
}
}
contract FAPS {
Verification vss;
address public address_PKB;
address public address_R;
uint256 public deposit_A;//The amount of deposit that Alice should pay
uint256 public deposit_B;//The amount of deposit that Bob should pay
uint256 public block_num;//The number of the blocks of the data Bob wants to buy
uint256 public block_price;//The price of each block of the data set by Alice
uint256 public block_value;//The amount of the tokens Bob needs to pay
uint256 public Time_Start;//The time when the transaction starts
uint256 public Time_Limit;//The time limit of the transaction
bytes public cheque_signed;//The cheque Bob sends to the smarc contract
bytes public cheque_B;//The cheque_signed Alice verifies by PK_B and SK_A
string public PK_A;//The public key of Alice
string public PK_B;//The public key of Bob
address public address_A;//The address of Alice
address public address_B;//The address of Bob
bool step_SetDepositA = false;
bool step_SetDepositB = false;
bool step_SetPrice = false;
bool step_SendDepositA = false;
bool step_SendPublicKeyA = false;
bool step_SetTime = false;
bool step_SetNumber = false;
bool step_SendDepositB = false;
bool step_SendValue = false;
bool step_SendPublicKeyB = false;
bool step_SendSignedCheque = false;
bool step_CheckCheque = false;
bool step_Result = false;
bool step_Withdraw = false;
//The creater of the smart contract
constructor () public payable {
address_A = msg.sender;
}
//Display the time
function Display_Time() public view returns (uint256) {
return now;
}
//Alice sets the deposit of Alice
function Set_DepositA (uint256 DepositAlice) public {
if (msg.sender == address_A) {
step_SetDepositA = true;
deposit_A = DepositAlice;
}
else {
step_SetDepositA = false;
revert("Only Alice can set the deposit of Alice.");
}
}
//Alice sets the deposit of Bob
function Set_DepositB (uint256 DepositBob) public {
if (step_SetDepositA == true) {
if (msg.sender == address_A) {
step_SetDepositB = true;
deposit_B = DepositBob;
}
else {
step_SetDepositB = false;
revert("Only Alice can set the deposit of Bob.");
}
}
else {
step_SetDepositB = false;
revert("Please set the deposit of Alice first.");
}
}
//Alice sets the price of each block of the data
function Set_Price (uint256 BlockPrice) public {
if (step_SetDepositB == true) {
if (msg.sender == address_A) {
step_SetPrice = true;
block_price = BlockPrice;
}
else {
step_SetPrice = false;
revert("Wrong Price of Each Block.");
}
}
else {
step_SetPrice = false;
revert("Please set the deposit of Bob first.");
}
}
//Alice sends the deposit to the smart contract
function Send_DepositA () public payable returns(bool) {
if (step_SetPrice == true) {
if (msg.sender == address_A) {
if (msg.value == deposit_A) {
step_SendDepositA = true;
return address(this).send(msg.value);
}
else {
step_SendDepositA = false;
revert("The amount of deposit Alice pays is wrong.");
}
}
else {
step_SendDepositA = false;
revert("Only Alice can send the deposit of Alice.");
}
}
else {
step_SendDepositA = false;
revert("Please set the price of each block first.");
}
}
//Alice sends her public key to the smart contract
function Send_PublicKeyA (string PublicKeyA) public {
if (step_SendDepositA == true) {
if (msg.sender == address_A) {
step_SendPublicKeyA = true;
PK_A = PublicKeyA;
}
else {
step_SendPublicKeyA = false;
revert("Only Alice can send her public key.");
}
}
else {
step_SendPublicKeyA = false;
revert("Please send the deposit of Alice first.");
}
}
//Alice sets the time limit of the transaction
function Set_Time (uint TimeLimit) public {
if (step_SendPublicKeyA == true) {
if (msg.sender == address_A) {
step_SetTime = true;
Time_Limit = TimeLimit;
Time_Start = now;
}
else {
step_SetTime = false;
revert("Only Alice can set the limit of time.");
}
}
else {
step_SetTime = false;
revert("Please send the public key of Alice first.");
}
}
//Bob sends the number of blokcs he wants to buy to the smart contract
function Set_Number (uint BlockNumber) public {
address_B = msg.sender;
if (step_SetTime == true) {
if (address_B != address_A) {
step_SetNumber = true;
block_num = BlockNumber;
block_value = block_price * block_num;
}
else {
step_SetNumber = false;
revert("The seller and the buyer can not be same.");
}
}
else {
step_SetNumber = false;
revert("Please send the public key of Alice first.");
}
}
//Bob sends the deposit to the smart contract
function Send_DepositB () public payable returns(bool) {
if (step_SetNumber == true) {
if (msg.sender == address_B) {
if (msg.value == deposit_B) {
step_SendDepositB = true;
return address(this).send(msg.value);
}
else {
step_SendDepositB = false;
revert("The amount of deposit Bob pays is wrong.");
}
}
else {
step_SendDepositB = false;
revert("Only Bob can send the deposit of Bob.");
}
}
else {
step_SendDepositB = false;
revert("Please set the number of blocks first.");
}
}
//Bob sends the value of blocks to the smart contract
function Send_Value () public payable returns(bool) {
if (step_SendDepositB == true) {
if (msg.sender == address_B) {
if (msg.value == block_value) {
step_SendValue = true;
return address(this).send(msg.value);
}
else {
step_SendValue = false;
revert("The value of blocks Bob pays is wrong.");
}
}
else {
step_SendValue = false;
revert("Only Bob can pay for the blocks.");
}
}
else {
step_SendValue = false;
revert("Please send the deposit of Bob first.");
}
}
//Bob sends his public key to the smart contract
function Send_PublicKeyB (string PublicKeyB) public {
if (step_SendValue == true) {
if (msg.sender == address_B) {
step_SendPublicKeyB = true;
PK_B = PublicKeyB;
}
else {
step_SendPublicKeyB = false;
revert("Only Bob can send the publick key of Bob.");
}
}
else {
step_SendPublicKeyB = false;
revert("Please send the value of blokcs first.");
}
}
//Bob sends the signed cheque to the smart contract
function Send_SignedCheque (bytes SignedCheque) public {
if (step_SendPublicKeyB == true) {
if (msg.sender == address_B) {
step_SendSignedCheque = true;
cheque_signed = SignedCheque;
}
else {
step_SendSignedCheque = false;
revert("Only Bob can send signed cheque.");
}
}
else {
step_SendSignedCheque = false;
revert("Please send the value of blokcs first.");
}
}
//Alice check signed cheque and send it to the smart contract
function Send_Cheque (bytes Cheque) public {
if (step_SendSignedCheque == true) {
if (msg.sender == address_A) {
cheque_B = Cheque;
address_R = vss.Verify_String(Cheque);
if (address_R == address_PKB) {
step_CheckCheque = true;
}
else {
step_CheckCheque = false;
revert("The signature of signed cheque is wrong.");
}
}
else {
step_CheckCheque = false;
revert("Only Alice can send the cheque for verification.");
}
}
else {
step_CheckCheque = false;
revert("Please send the signed cheque first.");
}
}
//The result of the trasaction
function Button_Result () public {
if (step_CheckCheque == true) {
if (msg.sender == address_A || msg.sender == address_B) {
step_Result = true;
address_A.transfer(deposit_A);
address_B.transfer(deposit_B);
}
else {
step_Result = false;
revert("Only Alice or Bob can comfirm.");
}
}
else {
step_Result = false;
revert("Please check the cheque first.");
}
}
//To stop the transaction for waiting too long
function Button_End () public {
//Only Alice sends the deposit
if ((msg.sender == address_A || msg.sender == address_B) &&
now > Time_Start + Time_Limit &&
step_SendDepositA == true) {
address_A.transfer(deposit_A);
}
//Alice and Bob both send the deposit
else if ((msg.sender == address_A || msg.sender == address_B) &&
now > Time_Start + Time_Limit &&
step_SendDepositB == true) {
address_A.transfer(deposit_A);
address_B.transfer(deposit_B);
}
//Bob sends the value of bloacks
else if ((msg.sender == address_A || msg.sender == address_B) &&
now > Time_Start + Time_Limit &&
step_SendValue == true) {
address_A.transfer(deposit_A);
address_B.transfer(deposit_B);
address_B.transfer(block_value);
}
else {
revert("The transaction is running.");
}
}
//Alice withdraws the money
function Withdraw_Money () public {
if (step_Result == true) {
if (msg.sender == address_A) {
step_Withdraw = true;
address_A.transfer(block_value);
}
else {
step_Withdraw = false;
revert("Only Alice can use it.");
}
}
else {
step_Withdraw = false;
revert("The transaction has not completed yet.");
}
}
}
|
Bob sends the number of blokcs he wants to buy to the smart contract
|
function Set_Number (uint BlockNumber) public {
address_B = msg.sender;
if (step_SetTime == true) {
if (address_B != address_A) {
step_SetNumber = true;
block_num = BlockNumber;
block_value = block_price * block_num;
}
else {
step_SetNumber = false;
revert("The seller and the buyer can not be same.");
}
}
else {
step_SetNumber = false;
revert("Please send the public key of Alice first.");
}
}
| 6,361,566 |
./full_match/80001/0x21289999e7EAf1ED197e42aE1E4c3b09c9ccfE8a/sources/lib/plugin-pattern/src/presets/utils/StringSet.sol
|
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, string memory value) internal returns (bool) {
return _remove(set, value);
}
| 852,343 |
./full_match/1/0xfB2Bfc368a7edfD51aa2cbEC513ad50edEa74E84/sources/contracts/cctp/SynapseCCTP.sol
|
Predicts the address of the destination caller that will be used to call the Circle Message Transmitter. On the destination chain, Synapse CCTP will deploy a MinimalForwarder for each request, using requestID as salt for the create2 deployment.
|
function _destinationCaller(address synapseCCTP, bytes32 requestID) internal pure returns (bytes32) {
return synapseCCTP.predictAddress(requestID).addressToBytes32();
}
| 5,006,485 |
./partial_match/4/0x6480e156865Bbb84Ba94d53dC09f667bdC2B371a/sources/Contract.sol
|
Получение количества голосваний./
|
function getBallotsLengh() public view returns(uint) {
return ballots.length;
}
| 8,508,810 |
./full_match/43113/0xE745F526aD4244B4432D8F5Da402f5778668693C/sources/contracts/router.sol
|
SWAP (supporting fee-on-transfer tokens) requires the initial amount to have already been sent to the first pair
|
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = PangolinLibrary.sortTokens(input, output);
IPair pair = IPair(PangolinLibrary.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = PangolinLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? PangolinLibrary.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
| 7,205,208 |
./full_match/1/0xE7C2016f5344858f6A1874424d077aDD3ea81fa5/sources/contracts/test/GovernQueueFactoryMock.sol
|
TODO: emit events and catch it in the govern-base-factory-unit.test.ts
|
function configure(ERC3000Data.Config memory /*_config*/) public pure returns(bool) {
return true;
}
| 4,906,916 |
pragma solidity 0.5.1;
/**
* @dev Base contract for teams
*/
contract Team {
using SafeMath for uint256;
//DEEX fund address
address payable public DEEXFund = 0xA2A3aD8319D24f4620Fbe06D2bC57c045ECF0932;
JackPot public JPContract;
DEEX public DEEXContract;
/**
* @dev Payable function. 10% will send to DEEX fund and 90% will send to JackPot contract.
* Also setting info about player.
*/
function () external payable { //inject DOS BY COMPLEX FALLBACK
require(JPContract.getState() && msg.value >= 0.05 ether);
JPContract.setInfo(msg.sender, msg.value.mul(90).div(100));
DEEXFund.call.gas(2301).value(msg.value.mul(10).div(100))("");
address(JPContract).call.gas(2301).value(msg.value.mul(90).div(100))("");
}
}
/*
* @dev Dragons contract. To play game with Dragons send ETH to this contract
*/
contract Dragons is Team {
/*
* @dev Approving JackPot contract for spending token from Dragons contract.
* Also setting Dragons address in JackPot contract
*/
constructor(address payable _jackPotAddress, address payable _DEEXAddress) public {
JPContract = JackPot(_jackPotAddress);
JPContract.setDragonsAddress(address(this));
DEEXContract = DEEX(_DEEXAddress);
DEEXContract.approve(_jackPotAddress, 9999999999999999999000000000000000000);
}
}
/*
* @dev Hamsters contract. To play game with Hamsters send ETH to this contract
*/
contract Hamsters is Team {
/*
* @dev Approving JackPot contract for spending token from Hamsters contract.
* Also setting Hamsters address in JackPot contract
*/
constructor(address payable _jackPotAddress, address payable _DEEXAddress) public {
JPContract = JackPot(_jackPotAddress);
JPContract.setHamstersAddress(address(this));
DEEXContract = DEEX(_DEEXAddress);
DEEXContract.approve(_jackPotAddress, 9999999999999999999000000000000000000);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error. Latest version on 05.01.2019
*/
library SafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @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 Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == INT256_MIN)); // This is the only case of overflow not detected by the check below
int256 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 Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0); // Solidity only automatically asserts when dividing by 0
require(!(b == -1 && a == INT256_MIN)); // This is the only case of overflow
int256 c = a / b;
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 Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two 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 Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/*
* @title JackPot
* @dev Jackpot contract which contained all ETH from Dragons and Hamsters teams.
* When time in blockchain will be grater then current deadline or last deadline need call getWinner function
* then participants able get prizes.
*
* Last participant(last hero) win 10% from all bank
*
* - To get prize send 0 ETH to this contract
*/
contract JackPot {
using SafeMath for uint256;
mapping (address => uint256) public depositDragons;
mapping (address => uint256) public depositHamsters;
uint256 public currentDeadline;
uint256 public lastDeadline = 1551978000; //last deadline for game
uint256 public countOfDragons;
uint256 public countOfHamsters;
uint256 public totalSupplyOfHamsters;
uint256 public totalSupplyOfDragons;
uint256 public totalDEEXSupplyOfHamsters;
uint256 public totalDEEXSupplyOfDragons;
uint256 public probabilityOfHamsters;
uint256 public probabilityOfDragons;
address public lastHero;
address public lastHeroHistory;
uint256 public jackPot;
uint256 public winner;
bool public finished = false;
Dragons public DragonsContract;
Hamsters public HamstersContract;
DEEX public DEEXContract;
/*
* @dev Constructor create first deadline
*/
constructor() public {
currentDeadline = block.timestamp + 60 * 60 * 24 * 30 ; //days for first deadline
}
/**
* @dev Setter the DEEX Token contract address. Address can be set at once.
* @param _DEEXAddress Address of the DEEX Token contract
*/
function setDEEXAddress(address payable _DEEXAddress) public {
require(address(DEEXContract) == address(0x0));
DEEXContract = DEEX(_DEEXAddress);
}
/**
* @dev Setter the Dragons contract address. Address can be set at once.
* @param _dragonsAddress Address of the Dragons contract
*/
function setDragonsAddress(address payable _dragonsAddress) external {
require(address(DragonsContract) == address(0x0));
DragonsContract = Dragons(_dragonsAddress);
}
/**
* @dev Setter the Hamsters contract address. Address can be set at once.
* @param _hamstersAddress Address of the Hamsters contract
*/
function setHamstersAddress(address payable _hamstersAddress) external {
require(address(HamstersContract) == address(0x0));
HamstersContract = Hamsters(_hamstersAddress);
}
/**
* @dev Getting time from blockchain
*/
function getNow() view public returns(uint){
return block.timestamp;
}
/**
* @dev Getting state of game. True - game continue, False - game stopped
*/
function getState() view public returns(bool) {
if (block.timestamp > currentDeadline) {
return false;
}
return true;
}
/**
* @dev Setting info about participant from Dragons or Hamsters contract
* @param _lastHero Address of participant
* @param _deposit Amount of deposit
*/
function setInfo(address _lastHero, uint256 _deposit) public {
require(address(DragonsContract) == msg.sender || address(HamstersContract) == msg.sender);
if (address(DragonsContract) == msg.sender) {
require(depositHamsters[_lastHero] == 0, "You are already in hamsters team");
if (depositDragons[_lastHero] == 0)
countOfDragons++;
totalSupplyOfDragons = totalSupplyOfDragons.add(_deposit.mul(90).div(100));
depositDragons[_lastHero] = depositDragons[_lastHero].add(_deposit.mul(90).div(100));
}
if (address(HamstersContract) == msg.sender) {
require(depositDragons[_lastHero] == 0, "You are already in dragons team");
if (depositHamsters[_lastHero] == 0)
countOfHamsters++;
totalSupplyOfHamsters = totalSupplyOfHamsters.add(_deposit.mul(90).div(100));
depositHamsters[_lastHero] = depositHamsters[_lastHero].add(_deposit.mul(90).div(100));
}
lastHero = _lastHero;
if (currentDeadline.add(120) <= lastDeadline) {
currentDeadline = currentDeadline.add(120);
} else {
currentDeadline = lastDeadline;
}
jackPot = (address(this).balance.add(_deposit)).mul(10).div(100);
calculateProbability();
}
/**
* @dev Calculation probability for team's win
*/
function calculateProbability() public {
require(winner == 0 && getState());
totalDEEXSupplyOfHamsters = DEEXContract.balanceOf(address(HamstersContract));
totalDEEXSupplyOfDragons = DEEXContract.balanceOf(address(DragonsContract));
uint256 percent = (totalSupplyOfHamsters.add(totalSupplyOfDragons)).div(100);
if (totalDEEXSupplyOfHamsters < 1) {
totalDEEXSupplyOfHamsters = 0;
}
if (totalDEEXSupplyOfDragons < 1) {
totalDEEXSupplyOfDragons = 0;
}
if (totalDEEXSupplyOfHamsters <= totalDEEXSupplyOfDragons) {
uint256 difference = (totalDEEXSupplyOfDragons.sub(totalDEEXSupplyOfHamsters)).mul(100);
probabilityOfDragons = totalSupplyOfDragons.mul(100).div(percent).add(difference);
if (probabilityOfDragons > 8000) {
probabilityOfDragons = 8000;
}
if (probabilityOfDragons < 2000) {
probabilityOfDragons = 2000;
}
probabilityOfHamsters = 10000 - probabilityOfDragons;
} else {
uint256 difference = (totalDEEXSupplyOfHamsters.sub(totalDEEXSupplyOfDragons)).mul(100);
probabilityOfHamsters = totalSupplyOfHamsters.mul(100).div(percent).add(difference);
if (probabilityOfHamsters > 8000) {
probabilityOfHamsters = 8000;
}
if (probabilityOfHamsters < 2000) {
probabilityOfHamsters = 2000;
}
probabilityOfDragons = 10000 - probabilityOfHamsters;
}
totalDEEXSupplyOfHamsters = DEEXContract.balanceOf(address(HamstersContract));
totalDEEXSupplyOfDragons = DEEXContract.balanceOf(address(DragonsContract));
}
/**
* @dev Getting winner team
*/
function getWinners() public {
require(winner == 0 && !getState());
uint256 seed1 = address(this).balance;
uint256 seed2 = totalSupplyOfHamsters;
uint256 seed3 = totalSupplyOfDragons;
uint256 seed4 = totalDEEXSupplyOfHamsters;
uint256 seed5 = totalDEEXSupplyOfHamsters;
uint256 seed6 = block.difficulty;
uint256 seed7 = block.timestamp;
bytes32 randomHash = keccak256(abi.encodePacked(seed1, seed2, seed3, seed4, seed5, seed6, seed7));
uint randomNumber = uint(randomHash);
if (randomNumber == 0){
randomNumber = 1;
}
uint winningNumber = randomNumber % 10000;
if (1 <= winningNumber && winningNumber <= probabilityOfDragons){
winner = 1;
}
if (probabilityOfDragons < winningNumber && winningNumber <= 10000){
winner = 2;
}
}
/**
* @dev Payable function for take prize
*/
function () external payable { //inject DOS BY COMPLEX FALLBACK
if (msg.value == 0 && !getState() && winner > 0){
require(depositDragons[msg.sender] > 0 || depositHamsters[msg.sender] > 0);
uint payout = 0;
uint payoutDEEX = 0;
if (winner == 1 && depositDragons[msg.sender] > 0) {
payout = calculateETHPrize(msg.sender);
}
if (winner == 2 && depositHamsters[msg.sender] > 0) {
payout = calculateETHPrize(msg.sender);
}
if (payout > 0) {
depositDragons[msg.sender] = 0;
depositHamsters[msg.sender] = 0;
msg.sender.call.gas(2301).value(payout)("");
}
if ((winner == 1 && depositDragons[msg.sender] == 0) || (winner == 2 && depositHamsters[msg.sender] == 0)) {
payoutDEEX = calculateDEEXPrize(msg.sender);
if (DEEXContract.balanceOf(address(HamstersContract)) > 0)
DEEXContract.transferFrom(
address(HamstersContract),
address(this),
DEEXContract.balanceOf(address(HamstersContract))
);
if (DEEXContract.balanceOf(address(DragonsContract)) > 0)
DEEXContract.transferFrom(
address(DragonsContract),
address(this),
DEEXContract.balanceOf(address(DragonsContract))
);
if (payoutDEEX > 0){
DEEXContract.transfer(msg.sender, payoutDEEX);
}
}
if (msg.sender == lastHero) {
lastHeroHistory = lastHero;
lastHero = address(0x0);
msg.sender.call.gas(2301).value(jackPot)("");
}
}
}
/**
* @dev Getting ETH prize of participant
* @param participant Address of participant
*/
function calculateETHPrize(address participant) public view returns(uint) {
uint payout = 0;
uint256 totalSupply = totalSupplyOfDragons.add(totalSupplyOfHamsters);
if (totalSupply > 0) {
if (depositDragons[participant] > 0) {
payout = totalSupply.mul(depositDragons[participant]).div(totalSupplyOfDragons);
}
if (depositHamsters[participant] > 0) {
payout = totalSupply.mul(depositHamsters[participant]).div(totalSupplyOfHamsters);
}
}
return payout;
}
/**
* @dev Getting DEEX Token prize of participant
* @param participant Address of participant
*/
function calculateDEEXPrize(address participant) public view returns(uint) {
uint payout = 0;
if (totalDEEXSupplyOfDragons.add(totalDEEXSupplyOfHamsters) > 0){
uint totalSupply = (totalDEEXSupplyOfDragons.add(totalDEEXSupplyOfHamsters)).mul(80).div(100);
if (depositDragons[participant] > 0) {
payout = totalSupply.mul(depositDragons[participant]).div(totalSupplyOfDragons);
}
if (depositHamsters[participant] > 0) {
payout = totalSupply.mul(depositHamsters[participant]).div(totalSupplyOfHamsters);
}
return payout;
}
return payout;
}
}
/*
* deex.exchange pre-ICO tokens smart contract
* implements [ERC-20 Token Standard](https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md)
*
* Style
* 1) before start coding, run Python and type 'import this' in Python console.
* 2) we avoid using inheritance (contract B is A) as it makes code less clear for observer
* ("Flat is better than nested", "Readability counts")
* 3) we avoid using -= ; =- ; +=; =+
* see: https://github.com/ether-camp/virtual-accelerator/issues/8
* https://www.ethnews.com/ethercamps-hkg-token-has-a-bug-and-needs-to-be-reissued
* 4) always explicitly mark variables and functions visibility ("Explicit is better than implicit")
* 5) every function except constructor should trigger at leas one event.
* 6) smart contracts have to be audited and reviewed, comment your code.
*
* Code is published on https://github.com/thedeex/thedeex.github.io
*/
/* "Interfaces" */
// this is expected from another contracts
// if it wants to spend tokens of behalf of the token owner in our contract
// this can be used in many situations, for example to convert pre-ICO tokens to ICO tokens
// see 'approveAndCall' function
contract allowanceRecipient {
function receiveApproval(address _from, uint256 _value, address _inContract, bytes memory _extraData) public returns (bool success);
}
// see:
// https://github.com/ethereum/EIPs/issues/677
contract tokenRecipient {
function tokenFallback(address _from, uint256 _value, bytes memory _extraData) public returns (bool success);
}
contract DEEX {
// ver. 2.0
/* ---------- Variables */
/* --- ERC-20 variables */
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#name
// function name() constant returns (string name)
string public name = "deex";
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#symbol
// function symbol() constant returns (string symbol)
string public symbol = "deex";
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#decimals
// function decimals() constant returns (uint8 decimals)
uint8 public decimals = 0;
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#totalsupply
// function totalSupply() constant returns (uint256 totalSupply)
// we start with zero and will create tokens as SC receives ETH
uint256 public totalSupply;
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#balanceof
// function balanceOf(address _owner) constant returns (uint256 balance)
mapping (address => uint256) public balanceOf;
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#allowance
// function allowance(address _owner, address _spender) constant returns (uint256 remaining)
mapping (address => mapping (address => uint256)) public allowance;
/* ----- For tokens sale */
uint256 public salesCounter = 0;
uint256 public maxSalesAllowed;
bool private transfersBetweenSalesAllowed;
// initial value should be changed by the owner
uint256 public tokenPriceInWei = 0;
uint256 public saleStartUnixTime = 0; // block.timestamp
uint256 public saleEndUnixTime = 0; // block.timestamp
/* --- administrative */
address public owner;
// account that can set prices
address public priceSetter;
// 0 - not set
uint256 private priceMaxWei = 0;
// 0 - not set
uint256 private priceMinWei = 0;
// accounts holding tokens for for the team, for advisers and for the bounty campaign
mapping (address => bool) public isPreferredTokensAccount;
bool public contractInitialized = false;
/* ---------- Constructor */
// do not forget about:
// https://medium.com/@codetractio/a-look-into-paritys-multisig-wallet-bug-affecting-100-million-in-ether-and-tokens-356f5ba6e90a
constructor () public {
owner = msg.sender;
// for testNet can be more than 2
// --------------------------------2------------------------------------------------------change in production!
maxSalesAllowed = 2;
//
transfersBetweenSalesAllowed = true;
}
function initContract(address team, address advisers, address bounty) public onlyBy(owner) returns (bool){
require(contractInitialized == false);
contractInitialized = true;
priceSetter = msg.sender;
totalSupply = 100000000;
// tokens for sale go SC own account
balanceOf[address(this)] = 75000000;
// for the team
balanceOf[team] = balanceOf[team] + 15000000;
isPreferredTokensAccount[team] = true;
// for advisers
balanceOf[advisers] = balanceOf[advisers] + 7000000;
isPreferredTokensAccount[advisers] = true;
// for the bounty campaign
balanceOf[bounty] = balanceOf[bounty] + 3000000;
isPreferredTokensAccount[bounty] = true;
}
/* ---------- Events */
/* --- ERC-20 events */
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#events
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer-1
event Transfer(address indexed from, address indexed to, uint256 value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#approval
event Approval(address indexed _owner, address indexed spender, uint256 value);
/* --- Administrative events: */
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
/* ---- Tokens creation and sale events */
event PriceChanged(uint256 indexed newTokenPriceInWei);
event SaleStarted(uint256 startUnixTime, uint256 endUnixTime, uint256 indexed saleNumber);
event NewTokensSold(uint256 numberOfTokens, address indexed purchasedBy, uint256 indexed priceInWei);
event Withdrawal(address indexed to, uint sumInWei);
/* --- Interaction with other contracts events */
event DataSentToAnotherContract(address indexed _from, address indexed _toContract, bytes _extraData);
/* ---------- Functions */
/* --- Modifiers */
modifier onlyBy(address _account){
require(msg.sender == _account);
_;
}
/* --- ERC-20 Functions */
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#methods
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transfer
function transfer(address _to, uint256 _value) public returns (bool){
return transferFrom(msg.sender, _to, _value);
}
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool){
// transfers are possible only after sale is finished
// except for manager and preferred accounts
bool saleFinished = saleIsFinished();
require(saleFinished || msg.sender == owner || isPreferredTokensAccount[msg.sender]);
// transfers can be forbidden until final ICO is finished
// except for manager and preferred accounts
require(transfersBetweenSalesAllowed || salesCounter == maxSalesAllowed || msg.sender == owner || isPreferredTokensAccount[msg.sender]);
// Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event (ERC-20)
require(_value >= 0);
// The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism
require(msg.sender == _from || _value <= allowance[_from][msg.sender]);
// check if _from account have required amount
require(_value <= balanceOf[_from]);
// Subtract from the sender
balanceOf[_from] = balanceOf[_from] - _value;
//
// Add the same to the recipient
balanceOf[_to] = balanceOf[_to] + _value;
// If allowance used, change allowances correspondingly
if (_from != msg.sender) {
allowance[_from][msg.sender] = allowance[_from][msg.sender] - _value;
}
// event
emit Transfer(_from, _to, _value);
return true;
}
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md#approve
// there is and attack, see:
// https://github.com/CORIONplatform/solidity/issues/6,
// https://drive.google.com/file/d/0ByMtMw2hul0EN3NCaVFHSFdxRzA/view
// but this function is required by ERC-20
function approve(address _spender, uint256 _value) public returns (bool success){
require(_value >= 0);
allowance[msg.sender][_spender] = _value;
// event
emit Approval(msg.sender, _spender, _value);
return true;
}
/* ---------- Interaction with other contracts */
/* User can allow another smart contract to spend some shares in his behalf
* (this function should be called by user itself)
* @param _spender another contract's address
* @param _value number of tokens
* @param _extraData Data that can be sent from user to another contract to be processed
* bytes - dynamically-sized byte array,
* see http://solidity.readthedocs.io/en/v0.4.15/types.html#dynamically-sized-byte-array
* see possible attack information in comments to function 'approve'
* > this may be used to convert pre-ICO tokens to ICO tokens
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) {
approve(_spender, _value);
// 'spender' is another contract that implements code as prescribed in 'allowanceRecipient' above
allowanceRecipient spender = allowanceRecipient(_spender);
// our contract calls 'receiveApproval' function of another contract ('allowanceRecipient') to send information about
// allowance and data sent by user
// 'this' is this (our) contract address
if (spender.receiveApproval(msg.sender, _value, address(this), _extraData)) {
emit DataSentToAnotherContract(msg.sender, _spender, _extraData);
return true;
}
else return false;
}
function approveAllAndCall(address _spender, bytes memory _extraData) public returns (bool success) {
return approveAndCall(_spender, balanceOf[msg.sender], _extraData);
}
/* https://github.com/ethereum/EIPs/issues/677
* transfer tokens with additional info to another smart contract, and calls its correspondent function
* @param address _to - another smart contract address
* @param uint256 _value - number of tokens
* @param bytes _extraData - data to send to another contract
* > this may be used to convert pre-ICO tokens to ICO tokens
*/
function transferAndCall(address _to, uint256 _value, bytes memory _extraData) public returns (bool success){
transferFrom(msg.sender, _to, _value);
tokenRecipient receiver = tokenRecipient(_to);
if (receiver.tokenFallback(msg.sender, _value, _extraData)) {
emit DataSentToAnotherContract(msg.sender, _to, _extraData);
return true;
}
else return false;
}
// for example for conveting ALL tokens of user account to another tokens
function transferAllAndCall(address _to, bytes memory _extraData) public returns (bool success){
return transferAndCall(_to, balanceOf[msg.sender], _extraData);
}
/* --- Administrative functions */
function changeOwner(address _newOwner) public onlyBy(owner) returns (bool success){
//
require(_newOwner != address(0));
address oldOwner = owner;
owner = _newOwner;
emit OwnerChanged(oldOwner, _newOwner);
return true;
}
/* ---------- Create and sell tokens */
/* set time for start and time for end pre-ICO
* time is integer representing block timestamp
* in UNIX Time,
* see: https://www.epochconverter.com
* @param uint256 startTime - time to start
* @param uint256 endTime - time to end
* should be taken into account that
* "block.timestamp" can be influenced by miners to a certain degree.
* That means that a miner can "choose" the block.timestamp, to a certain degree,
* to change the outcome of a transaction in the mined block.
* see:
* http://solidity.readthedocs.io/en/v0.4.15/frequently-asked-questions.html#are-timestamps-now-block-timestamp-reliable
*/
function startSale(uint256 _startUnixTime, uint256 _endUnixTime) public onlyBy(owner) returns (bool success){
require(balanceOf[address(this)] > 0);
require(salesCounter < maxSalesAllowed);
// time for sale can be set only if:
// this is first sale (saleStartUnixTime == 0 && saleEndUnixTime == 0) , or:
// previous sale finished ( saleIsFinished() )
require(
(saleStartUnixTime == 0 && saleEndUnixTime == 0) || saleIsFinished()
);
// time can be set only for future
require(_startUnixTime > now && _endUnixTime > now);
// end time should be later than start time
require(_endUnixTime - _startUnixTime > 0);
saleStartUnixTime = _startUnixTime;
saleEndUnixTime = _endUnixTime;
salesCounter = salesCounter + 1;
emit SaleStarted(_startUnixTime, _endUnixTime, salesCounter);
return true;
}
function saleIsRunning() public view returns (bool){
if (balanceOf[address(this)] == 0) {
return false;
}
if (saleStartUnixTime == 0 && saleEndUnixTime == 0) {
return false;
}
if (now > saleStartUnixTime && now < saleEndUnixTime) {
return true;
}
return false;
}
function saleIsFinished() public view returns (bool){
if (balanceOf[address(this)] == 0) {
return true;
}
else if (
(saleStartUnixTime > 0 && saleEndUnixTime > 0)
&& now > saleEndUnixTime) {
return true;
}
// <<<
return true;
}
function changePriceSetter(address _priceSetter) public onlyBy(owner) returns (bool success) {
priceSetter = _priceSetter;
return true;
}
function setMinMaxPriceInWei(uint256 _priceMinWei, uint256 _priceMaxWei) public onlyBy(owner) returns (bool success){
require(_priceMinWei >= 0 && _priceMaxWei >= 0);
priceMinWei = _priceMinWei;
priceMaxWei = _priceMaxWei;
return true;
}
function setTokenPriceInWei(uint256 _priceInWei) public onlyBy(priceSetter) returns (bool success){
require(_priceInWei >= 0);
// if 0 - not set
if (priceMinWei != 0 && _priceInWei < priceMinWei) {
tokenPriceInWei = priceMinWei;
}
else if (priceMaxWei != 0 && _priceInWei > priceMaxWei) {
tokenPriceInWei = priceMaxWei;
}
else {
tokenPriceInWei = _priceInWei;
}
emit PriceChanged(tokenPriceInWei);
return true;
}
// allows sending ether and receiving tokens just using contract address
// warning:
// 'If the fallback function requires more than 2300 gas, the contract cannot receive Ether'
// see:
// https://ethereum.stackexchange.com/questions/21643/fallback-function-best-practices-when-registering-information
function() external payable {
buyTokens();
}
//
function buyTokens() public payable returns (bool success){
if (saleIsRunning() && tokenPriceInWei > 0) {
uint256 numberOfTokens = msg.value / tokenPriceInWei;
if (numberOfTokens <= balanceOf[address(this)]) {
balanceOf[msg.sender] = balanceOf[msg.sender] + numberOfTokens;
balanceOf[address(this)] = balanceOf[address(this)] - numberOfTokens;
emit NewTokensSold(numberOfTokens, msg.sender, tokenPriceInWei);
return true;
}
else {
// (payable)
revert();
}
}
else {
// (payable)
revert();
}
}
/* After sale contract owner
* (can be another contract or account)
* can withdraw all collected Ether
*/
function withdrawAllToOwner() public onlyBy(owner) returns (bool) {
// only after sale is finished:
require(saleIsFinished());
uint256 sumInWei = address(this).balance;
if (
// makes withdrawal and returns true or false
!msg.sender.send(address(this).balance)
) {
return false;
}
else {
// event
emit Withdrawal(msg.sender, sumInWei);
return true;
}
}
/* ---------- Referral System */
// list of registered referrers
// represented by keccak256(address) (returns bytes32)
// ! referrers can not be removed !
mapping (bytes32 => bool) private isReferrer;
uint256 private referralBonus = 0;
uint256 private referrerBonus = 0;
// tokens owned by referrers:
mapping (bytes32 => uint256) public referrerBalanceOf;
mapping (bytes32 => uint) public referrerLinkedSales;
function addReferrer(bytes32 _referrer) public onlyBy(owner) returns (bool success){
isReferrer[_referrer] = true;
return true;
}
function removeReferrer(bytes32 _referrer) public onlyBy(owner) returns (bool success){
isReferrer[_referrer] = false;
return true;
}
// bonuses are set in as integers (20%, 30%), initial 0%
function setReferralBonuses(uint256 _referralBonus, uint256 _referrerBonus) public onlyBy(owner) returns (bool success){
require(_referralBonus > 0 && _referrerBonus > 0);
referralBonus = _referralBonus;
referrerBonus = _referrerBonus;
return true;
}
function buyTokensWithReferrerAddress(address _referrer) public payable returns (bool success){
bytes32 referrer = keccak256(abi.encodePacked(_referrer));
if (saleIsRunning() && tokenPriceInWei > 0) {
if (isReferrer[referrer]) {
uint256 numberOfTokens = msg.value / tokenPriceInWei;
if (numberOfTokens <= balanceOf[address(this)]) {
referrerLinkedSales[referrer] = referrerLinkedSales[referrer] + numberOfTokens;
uint256 referralBonusTokens = (numberOfTokens * (100 + referralBonus) / 100) - numberOfTokens;
uint256 referrerBonusTokens = (numberOfTokens * (100 + referrerBonus) / 100) - numberOfTokens;
balanceOf[address(this)] = balanceOf[address(this)] - numberOfTokens - referralBonusTokens - referrerBonusTokens;
balanceOf[msg.sender] = balanceOf[msg.sender] + (numberOfTokens + referralBonusTokens);
referrerBalanceOf[referrer] = referrerBalanceOf[referrer] + referrerBonusTokens;
emit NewTokensSold(numberOfTokens + referralBonusTokens, msg.sender, tokenPriceInWei);
return true;
}
else {
// (payable)
revert();
}
}
else {
// (payable)
buyTokens();
}
}
else {
// (payable)
revert();
}
}
event ReferrerBonusTokensTaken(address referrer, uint256 bonusTokensValue);
function getReferrerBonusTokens() public returns (bool success){
require(saleIsFinished());
uint256 bonusTokens = referrerBalanceOf[keccak256(abi.encodePacked(msg.sender))];
balanceOf[msg.sender] = balanceOf[msg.sender] + bonusTokens;
emit ReferrerBonusTokensTaken(msg.sender, bonusTokens);
return true;
}
}
|
Setting info about participant from Dragons or Hamsters contract _lastHero Address of participant _deposit Amount of deposit/
|
function setInfo(address _lastHero, uint256 _deposit) public {
require(address(DragonsContract) == msg.sender || address(HamstersContract) == msg.sender);
if (address(DragonsContract) == msg.sender) {
require(depositHamsters[_lastHero] == 0, "You are already in hamsters team");
if (depositDragons[_lastHero] == 0)
countOfDragons++;
totalSupplyOfDragons = totalSupplyOfDragons.add(_deposit.mul(90).div(100));
depositDragons[_lastHero] = depositDragons[_lastHero].add(_deposit.mul(90).div(100));
}
if (address(HamstersContract) == msg.sender) {
require(depositDragons[_lastHero] == 0, "You are already in dragons team");
if (depositHamsters[_lastHero] == 0)
countOfHamsters++;
totalSupplyOfHamsters = totalSupplyOfHamsters.add(_deposit.mul(90).div(100));
depositHamsters[_lastHero] = depositHamsters[_lastHero].add(_deposit.mul(90).div(100));
}
lastHero = _lastHero;
if (currentDeadline.add(120) <= lastDeadline) {
currentDeadline = currentDeadline.add(120);
currentDeadline = lastDeadline;
}
jackPot = (address(this).balance.add(_deposit)).mul(10).div(100);
calculateProbability();
}
| 12,758,620 |
./full_match/8453/0x0c9034b92351cF8f067379a1fFA4fa35f5AF9dCC/sources/lib/optimism/packages/contracts-bedrock/src/libraries/Encoding.sol
|
Encodes a cross domain message based on the V1 (current) encoding. _nonce Message nonce. _sender Address of the sender of the message. _target Address of the target of the message. _value ETH value to send to the target. _gasLimit Gas limit to use for the message. _data Data to send with the message. return Encoded cross domain message.
|
function encodeCrossDomainMessageV1(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes memory _data
) internal pure returns (bytes memory) {
return
abi.encodeWithSignature(
"relayMessage(uint256,address,address,uint256,uint256,bytes)",
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
}
| 11,538,340 |
pragma solidity ^0.4.4;
contract ContractAbiMgr {
struct AbiInfo {
string contractname; //contract name
string version; //version
string abi; //abi
address addr; //contract address
uint256 blocknumber; //block number
uint256 timestamp; //timestamp
}
event AddAbi(string name,string contractname,string version,string abi,address addr,uint256 blocknumber,uint256 timestamp);
event UpdateAbi(string name,string contractname,string version,string abi,address addr,uint256 blocknumber,uint256 timestamp);
//name => AbiInfo
mapping(string=>AbiInfo) private map_abi_infos;
string[] private names;
//add one abi info, when this contract abi info is already exist , it will end with failed.
function addAbi(string name,string contractname,string version,string abi,address addr) public {
//check if this contract abi info is already exist.
uint256 old_timestamp = getTimeStamp(name);
if (old_timestamp != 0) {
//this abi info already exist;
return;
}
names.push(name);
map_abi_infos[name] = AbiInfo(contractname,version,abi,addr,block.number,block.timestamp);
AddAbi(name,contractname,version,abi,addr,block.number,block.timestamp);
}
//update one abi info, when this contract abi info is not exist , it will end with failed.
function updateAbi(string name,string contractname,string version,string abi,address addr) public {
//check if this contract abi info is not exist.
uint256 old_timestamp = getTimeStamp(name);
if (old_timestamp == 0) {
//this abi info is not exist;
return;
}
map_abi_infos[name] = AbiInfo(contractname,version,abi,addr,block.number,block.timestamp);
UpdateAbi(name,contractname,version,abi,addr,block.number,block.timestamp);
}
//get member address
function getAddr(string name) constant public returns(address){
return map_abi_infos[name].addr;
}
//get member abi
function getAbi(string name) constant public returns(string){
return map_abi_infos[name].abi;
}
//get member contract name
function getContractName(string name) constant public returns(string){
return map_abi_infos[name].contractname;
}
//get member version
function getVersion(string name) constant public returns(string){
return map_abi_infos[name].version;
}
//get member blocknumber
function getBlockNumber(string name) constant public returns(uint256){
return map_abi_infos[name].blocknumber;
}
//get member timestamp
function getTimeStamp(string name) constant public returns(uint256){
return map_abi_infos[name].timestamp;
}
//get length of names
function getAbiCount() constant public returns(uint256){
return names.length;
}
//get all members by name
function getAll(string name) constant public returns(string,address,string,string,uint256,uint256){
return (map_abi_infos[name].abi,
map_abi_infos[name].addr,
map_abi_infos[name].contractname,
map_abi_infos[name].version,
map_abi_infos[name].blocknumber,
map_abi_infos[name].timestamp
);
}
//get all members by index
function getAllByIndex(uint256 index) constant public returns(string,address,string,string,uint256,uint256){
if(index < names.length){
return (map_abi_infos[names[index]].abi,
map_abi_infos[names[index]].addr,
map_abi_infos[names[index]].contractname,
map_abi_infos[names[index]].version,
map_abi_infos[names[index]].blocknumber,
map_abi_infos[names[index]].timestamp
);
}
return ("",0x00,"","",0,0);
}
}
|
get member blocknumber
|
function getBlockNumber(string name) constant public returns(uint256){
return map_abi_infos[name].blocknumber;
}
| 910,637 |
./full_match/1/0xe229084e0892f26a2Eec44349C36463F4b93E5c6/sources/contracts/TransactionManager.sol
|
Sets the timestamp for an owner to be proposed, and sets the newly proposed owner as step 1 in a 2-step process/
|
function proposeNewOwner(address newlyProposed) public virtual onlyOwner {
_setProposed(newlyProposed);
}
| 8,344,442 |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./FantomMintErrorCodes.sol";
import "./FantomCollateralStorage.sol";
import "./FantomDebtStorage.sol";
import "./FantomMintRewardManager.sol";
// FantomMintCore implements a balance pool of collateral and debt tokens
// for the related Fantom DeFi contract. The collateral part allows notified rewards
// distribution to eligible collateral accounts.
contract FantomMintCore is
Ownable,
ReentrancyGuard,
FantomMintErrorCodes,
FantomCollateralStorage,
FantomDebtStorage,
FantomMintRewardManager
{
// define used libs
using SafeMath for uint256;
using Address for address;
using SafeERC20 for ERC20;
// -------------------------------------------------------------
// Price and value calculation related constants
// -------------------------------------------------------------
// collateralLowestDebtRatio4dec represents the lowest ratio between
// collateral value and debt value allowed for the user.
// User can not withdraw his collateral if the active ratio would
// drop below this value.
// The value is returned in 4 decimals, e.g. value 30000 = 3.0
uint256 public constant collateralLowestDebtRatio4dec = 30000;
// collateralRatioDecimalsCorrection represents the value to be used
// to adjust result decimals after applying ratio to a value calculation.
uint256 public constant collateralRatioDecimalsCorrection = 10000;
// -------------------------------------------------------------
// Emitted events definition
// -------------------------------------------------------------
// Deposited is emitted on token received to deposit
// increasing user's collateral value.
event Deposited(address indexed token, address indexed user, uint256 amount);
// Withdrawn is emitted on confirmed token withdraw
// from the deposit decreasing user's collateral value.
event Withdrawn(address indexed token, address indexed user, uint256 amount);
// -------------------------------------------------------------
// Token value related functions
// -------------------------------------------------------------
// getPrice (abstract) returns the price of given ERC20 token using on-chain oracle
// expression of an exchange rate between the token and base denomination.
function getPrice(address _token) public view returns (uint256);
// getPriceDigitsCorrection (abstract) returns the correction to the calculated
// ERC20 token value to correct exchange rate digits correction.
function getPriceDigitsCorrection() public pure returns (uint256);
// tokenValue calculates the value of the given amount of the token specified.
// The value is returned in given referential tokens (fUSD).
// Implements tokenValue() abstract function of the underlying storage contracts.
function tokenValue(address _token, uint256 _amount) public view returns (uint256) {
// calculate the value using price Oracle access
return _amount.mul(getPrice(_token)).div(getPriceDigitsCorrection());
}
// -------------------------------------------------------------
// Collateral to debt ratio checks below
// -------------------------------------------------------------
// isCollateralSufficient checks if collateral value is sufficient
// to cover the debt (collateral to debt ratio) after
// predefined adjustments to the collateral and debt values.
function isCollateralSufficient(address _account, uint256 subCollateral, uint256 addDebt, uint256 ratio) internal view returns (bool) {
// calculate the collateral and debt values in ref. denomination
// for the current exchange rate and balance amounts including
// given adjustments to both values as requested.
uint256 cDebtValue = debtValueOf(_account).add(addDebt);
uint256 cCollateralValue = collateralValueOf(_account).sub(subCollateral);
// minCollateralValue is the minimal collateral value required for the current debt
// to be within the minimal allowed collateral to debt ratio
uint256 minCollateralValue = cDebtValue
.mul(ratio)
.div(collateralRatioDecimalsCorrection);
// final collateral value must match the minimal value or exceed it
return (cCollateralValue >= minCollateralValue);
}
// collateralCanDecrease checks if the specified amount of collateral can be removed from account
// without breaking collateral to debt ratio rule.
function collateralCanDecrease(address _account, address _token, uint256 _amount) public view returns (bool) {
// collateral to debt ratio must be valid after collateral decrease
return isCollateralSufficient(_account, tokenValue(_token, _amount), 0, collateralLowestDebtRatio4dec);
}
// debtCanIncrease checks if the specified amount of debt can be added to the account
// without breaking collateral to debt ratio rule.
function debtCanIncrease(address _account, address _token, uint256 _amount) public view returns (bool) {
// collateral to debt ratio must be valid after debt increase
return isCollateralSufficient(_account, 0, tokenValue(_token, _amount), collateralLowestDebtRatio4dec);
}
// rewardCanClaim checks if the account can claim accumulated rewards
// by being on a high enough collateral to debt ratio.
// Implements abstract function of the <FantomMintRewardManager>.
function rewardCanClaim(address _account) public view returns (bool) {
return isCollateralSufficient(_account, 0, 0, collateralLowestDebtRatio4dec);
}
// rewardIsEligible checks if the account is eligible to receive any reward.
function rewardIsEligible(address _account) internal view returns (bool) {
return isCollateralSufficient(_account, 0, 0, rewardEligibilityRatio4dec);
}
// --------------------------------------------------------------------------
// Principal balance calculations used by the reward manager to yield rewards
// --------------------------------------------------------------------------
// principalBalance returns the total balance of principal token
// which yield a reward to entitled participants based
// on their individual principal share.
function principalBalance() public view returns (uint256) {
return debtTotal();
}
// principalBalanceOf returns the balance of principal token
// which yield a reward share for this account.
function principalBalanceOf(address _account) public view returns (uint256) {
return debtValueOf(_account);
}
// -------------------------------------------------------------
// Collateral management functions below
// -------------------------------------------------------------
// deposit receives assets to build up the collateral value.
// The collateral can be used later to mint tokens inside fMint module.
// The call does not subtract any fee. No interest is granted on deposit.
function deposit(address _token, uint256 _amount) public nonReentrant returns (uint256)
{
// make sure a non-zero value is being deposited
if (_amount == 0) {
return ERR_ZERO_AMOUNT;
}
// make sure caller has enough balance to cover the deposit
if (_amount > ERC20(_token).balanceOf(msg.sender)) {
return ERR_LOW_BALANCE;
}
// make sure we are allowed to transfer funds from the caller
// to the fMint deposit pool
if (_amount > ERC20(_token).allowance(msg.sender, address(this))) {
return ERR_LOW_ALLOWANCE;
}
// make sure the token has a value before we accept it as a collateral
if (getPrice(_token) == 0) {
return ERR_NO_VALUE;
}
// transfer ERC20 tokens from account to the collateral pool
ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
// update the reward distribution for the account before the state changes
rewardUpdate(msg.sender);
// add the collateral to the account
collateralAdd(msg.sender, _token, _amount);
// emit the event signaling a successful deposit
emit Deposited(_token, msg.sender, _amount);
// deposit successful
return ERR_NO_ERROR;
}
// withdraw subtracts any deposited collateral token from the contract.
// The remaining collateral value is compared to the minimal required
// collateral to debt ratio and the transfer is rejected
// if the ratio is lower than the enforced one.
function withdraw(address _token, uint256 _amount) public nonReentrant returns (uint256) {
// make sure a non-zero value is being withdrawn
if (_amount == 0) {
return ERR_ZERO_AMOUNT;
}
// make sure the withdraw does not exceed collateral balance
if (_amount > collateralBalance[msg.sender][_token]) {
return ERR_LOW_BALANCE;
}
// does the new state obey the enforced minimal collateral to debt ratio?
// if the check fails, the collateral withdraw is rejected
if (!collateralCanDecrease(msg.sender, _token, _amount)) {
return ERR_LOW_COLLATERAL_RATIO;
}
// update the reward distribution for the account before state changes
rewardUpdate(msg.sender);
// remove the collateral from account
collateralSub(msg.sender, _token, _amount);
// transfer withdrawn ERC20 tokens to the caller
ERC20(_token).safeTransfer(msg.sender, _amount);
// signal the successful asset withdrawal
emit Withdrawn(_token, msg.sender, _amount);
// withdraw successful
return ERR_NO_ERROR;
}
}
|
rewardIsEligible checks if the account is eligible to receive any reward.
|
function rewardIsEligible(address _account) internal view returns (bool) {
return isCollateralSufficient(_account, 0, 0, rewardEligibilityRatio4dec);
}
| 7,266,734 |
./full_match/1/0x910DdC5A26285e53c10927D0723581A990e0ebFC/sources/contracts/MoonLabsTokenLocker.sol
|
Private function handeling lock splits/
|
function _splitLock(
uint64 _nonce,
uint depositAmount,
uint currentAmount,
uint amount,
address tokenAddress,
address withdrawalAddress,
address to
) private {
require(lockInstance[_nonce].ownerAddress == msg.sender, "Ownership");
require(currentAmount > amount, "Balance");
require(amount > 0, "Zero transfer");
uint newDepositAmount = MathUpgradeable.mulDiv(
depositAmount,
amount,
currentAmount
);
lockInstance[_nonce].depositAmount -= newDepositAmount;
lockInstance[_nonce].currentAmount -= amount;
lockInstance[nonce] = LockInstance(
tokenAddress,
to,
withdrawalAddress,
newDepositAmount,
amount,
lockInstance[_nonce].startDate,
lockInstance[_nonce].endDate
);
tokenToLock[tokenAddress].push(nonce);
ownerToLock[to].push(nonce);
withdrawalToLock[withdrawalAddress].push(nonce);
if (lockInstance[_nonce].currentAmount <= 0)
_deleteLockInstance(_nonce);
nonce++;
emit LockSplit(msg.sender, to, amount, _nonce, nonce - 1);
| 8,334,996 |
./partial_match/1/0x82a208C2845F922f8453FBe0788a2DE73D6281Cd/sources/Presale.sol
|
============================================================= Helper Functions =============================================================
|
function weeksSince(uint256 timestamp) internal view returns (uint256) {
uint256 secondsPassed = currentTimestamp - timestamp;
uint256 remainingWeeks = secondsPassed / 604800;
return remainingWeeks;
}
| 15,964,923 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import './interfaces/IConditional.sol';
import './interfaces/IMultiplier.sol';
import './OKLGWithdrawable.sol';
contract OKLGDividendDistributor is OKLGWithdrawable {
using SafeMath for uint256;
struct Dividend {
uint256 totalExcluded; // excluded dividend
uint256 totalRealised;
uint256 lastClaim; // used for boosting logic
}
address public shareholderToken;
uint256 public totalSharesDeposited; // will only be actual deposited tokens without handling any reflections or otherwise
address wrappedNative;
IUniswapV2Router02 router;
// used to fetch in a frontend to get full list
// of tokens that dividends can be claimed
address[] public tokens;
mapping(address => bool) tokenAwareness;
mapping(address => uint256) shareholderClaims;
// amount of shares a user has
mapping(address => uint256) public shares;
// dividend information per user
mapping(address => mapping(address => Dividend)) public dividends;
address public boostContract;
address public boostMultiplierContract;
uint256 public floorBoostClaimTimeSeconds = 60 * 60 * 12;
uint256 public ceilBoostClaimTimeSeconds = 60 * 60 * 24;
// per token dividends
mapping(address => uint256) public totalDividends;
mapping(address => uint256) public totalDistributed; // to be shown in UI
mapping(address => uint256) public dividendsPerShare;
uint256 public constant ACC_FACTOR = 10**36;
address public constant DEAD = 0x000000000000000000000000000000000000dEaD;
constructor(
address _dexRouter,
address _shareholderToken,
address _wrappedNative
) {
router = IUniswapV2Router02(_dexRouter);
shareholderToken = _shareholderToken;
wrappedNative = _wrappedNative;
}
function stake(address token, uint256 amount) external {
_stake(msg.sender, token, amount, false);
}
function _stake(
address shareholder,
address token,
uint256 amount,
bool contractOverride
) private {
if (shares[shareholder] > 0 && !contractOverride) {
distributeDividend(token, shareholder, false);
}
IERC20 shareContract = IERC20(shareholderToken);
uint256 stakeAmount = amount == 0
? shareContract.balanceOf(shareholder)
: amount;
// for compounding we will pass in this contract override flag and assume the tokens
// received by the contract during the compounding process are already here, therefore
// whatever the amount is passed in is what we care about and leave it at that. If a normal
// staking though by a user, transfer tokens from the user to the contract.
uint256 finalAmount = amount;
if (!contractOverride) {
uint256 shareBalanceBefore = shareContract.balanceOf(address(this));
shareContract.transferFrom(shareholder, address(this), stakeAmount);
finalAmount = shareContract.balanceOf(address(this)).sub(
shareBalanceBefore
);
}
totalSharesDeposited = totalSharesDeposited.add(finalAmount);
shares[shareholder] += finalAmount;
dividends[shareholder][token].totalExcluded = getCumulativeDividends(
token,
shares[shareholder]
);
}
function unstake(address token, uint256 amount) external {
require(
shares[msg.sender] > 0 && (amount == 0 || shares[msg.sender] <= amount),
'you can only unstake if you have some staked'
);
distributeDividend(token, msg.sender, false);
IERC20 shareContract = IERC20(shareholderToken);
// handle reflections tokens
uint256 baseWithdrawAmount = amount == 0 ? shares[msg.sender] : amount;
uint256 totalSharesBalance = shareContract.balanceOf(address(this)).sub(
totalDividends[shareholderToken].sub(totalDistributed[shareholderToken])
);
uint256 appreciationRatio18 = totalSharesBalance.mul(10**18).div(
totalSharesDeposited
);
uint256 finalWithdrawAmount = baseWithdrawAmount
.mul(appreciationRatio18)
.div(10**18);
shareContract.transfer(msg.sender, finalWithdrawAmount);
totalSharesDeposited = totalSharesDeposited.sub(baseWithdrawAmount);
shares[msg.sender] -= baseWithdrawAmount;
dividends[msg.sender][token].totalExcluded = getCumulativeDividends(
token,
shares[msg.sender]
);
}
// tokenAddress == address(0) means native token
// any other token should be ERC20 listed on DEX router provided in constructor
//
// NOTE: Using this function will add tokens to the core rewards/dividends to be
// distributed to all shareholders. However, to implement boosting, the token
// should be directly transferred to this contract. Anything above and
// beyond the totalDividends[tokenAddress] amount will be used for boosting.
function depositDividends(address tokenAddress, uint256 erc20DirectAmount)
external
payable
{
require(
erc20DirectAmount > 0 || msg.value > 0,
'value must be greater than 0'
);
require(
totalSharesDeposited > 0,
'must be shares deposited to be rewarded dividends'
);
if (!tokenAwareness[tokenAddress]) {
tokenAwareness[tokenAddress] = true;
tokens.push(tokenAddress);
}
IERC20 token;
uint256 amount;
if (tokenAddress == address(0)) {
payable(address(this)).call{ value: msg.value }('');
amount = msg.value;
} else if (erc20DirectAmount > 0) {
token = IERC20(tokenAddress);
uint256 balanceBefore = token.balanceOf(address(this));
token.transferFrom(msg.sender, address(this), erc20DirectAmount);
amount = token.balanceOf(address(this)).sub(balanceBefore);
} else {
token = IERC20(tokenAddress);
uint256 balanceBefore = token.balanceOf(address(this));
address[] memory path = new address[](2);
path[0] = wrappedNative;
path[1] = tokenAddress;
router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: msg.value
}(0, path, address(this), block.timestamp);
amount = token.balanceOf(address(this)).sub(balanceBefore);
}
totalDividends[tokenAddress] = totalDividends[tokenAddress].add(amount);
dividendsPerShare[tokenAddress] = dividendsPerShare[tokenAddress].add(
ACC_FACTOR.mul(amount).div(totalSharesDeposited)
);
}
function distributeDividend(
address token,
address shareholder,
bool compound
) internal {
if (shares[shareholder] == 0) {
return;
}
uint256 amount = getUnpaidEarnings(token, shareholder);
if (amount > 0) {
totalDistributed[token] = totalDistributed[token].add(amount);
// native transfer
if (token == address(0)) {
if (compound) {
IERC20 shareToken = IERC20(shareholderToken);
uint256 balBefore = shareToken.balanceOf(address(this));
address[] memory path = new address[](2);
path[0] = wrappedNative;
path[1] = shareholderToken;
router.swapExactETHForTokensSupportingFeeOnTransferTokens{
value: amount
}(0, path, address(this), block.timestamp);
uint256 amountReceived = shareToken.balanceOf(address(this)).sub(
balBefore
);
if (amountReceived > 0) {
_stake(shareholder, token, amountReceived, true);
}
} else {
payable(shareholder).call{ value: amount }('');
}
} else {
IERC20(token).transfer(shareholder, amount);
}
_payBoostedRewards(token, shareholder);
shareholderClaims[shareholder] = block.timestamp;
dividends[shareholder][token].totalRealised = dividends[shareholder][
token
].totalRealised.add(amount);
dividends[shareholder][token].totalExcluded = getCumulativeDividends(
token,
shares[shareholder]
);
dividends[shareholder][token].lastClaim = block.timestamp;
}
}
function _payBoostedRewards(address token, address shareholder) internal {
bool canCurrentlyClaim = canClaimBoostedRewards(token, shareholder) &&
eligibleForRewardBooster(shareholder);
if (!canCurrentlyClaim) {
return;
}
uint256 amount = calculateBoostRewards(token, shareholder);
if (amount > 0) {
if (token == address(0)) {
payable(shareholder).call{ value: amount }('');
} else {
IERC20(token).transfer(shareholder, amount);
}
}
}
function claimDividend(address token, bool compound) external {
distributeDividend(token, msg.sender, compound);
}
function canClaimBoostedRewards(address token, address shareholder)
public
view
returns (bool)
{
return
dividends[shareholder][token].lastClaim == 0 ||
(block.timestamp >
dividends[shareholder][token].lastClaim.add(
floorBoostClaimTimeSeconds
) &&
block.timestamp <=
dividends[shareholder][token].lastClaim.add(ceilBoostClaimTimeSeconds));
}
function getDividendTokens() external view returns (address[] memory) {
return tokens;
}
function getBoostMultiplier(address wallet) public view returns (uint256) {
return
boostMultiplierContract == address(0)
? 0
: IMultiplier(boostMultiplierContract).getMultiplier(wallet);
}
function calculateBoostRewards(address token, address shareholder)
public
view
returns (uint256)
{
// use the token circulating supply for boosting rewards since that's
// how the calculation has been done thus far and we want the boosted
// rewards to have some longevity.
IERC20 shareToken = IERC20(shareholderToken);
uint256 totalCirculatingShareTokens = shareToken.totalSupply() -
shareToken.balanceOf(DEAD);
uint256 availableBoostRewards = address(this).balance;
if (token != address(0)) {
availableBoostRewards = IERC20(token).balanceOf(address(this));
}
uint256 excluded = totalDividends[token].sub(totalDistributed[token]);
uint256 finalAvailableBoostRewards = availableBoostRewards.sub(excluded);
uint256 userShareBoostRewards = finalAvailableBoostRewards
.mul(shares[shareholder])
.div(totalCirculatingShareTokens);
uint256 rewardsWithBooster = eligibleForRewardBooster(shareholder)
? userShareBoostRewards.add(
userShareBoostRewards.mul(getBoostMultiplier(shareholder)).div(10**2)
)
: userShareBoostRewards;
return
rewardsWithBooster > finalAvailableBoostRewards
? finalAvailableBoostRewards
: rewardsWithBooster;
}
function eligibleForRewardBooster(address shareholder)
public
view
returns (bool)
{
return
boostContract != address(0) &&
IConditional(boostContract).passesTest(shareholder);
}
// returns the unpaid earnings
function getUnpaidEarnings(address token, address shareholder)
public
view
returns (uint256)
{
if (shares[shareholder] == 0) {
return 0;
}
uint256 earnedDividends = getCumulativeDividends(
token,
shares[shareholder]
);
uint256 dividendsExcluded = dividends[shareholder][token].totalExcluded;
if (earnedDividends <= dividendsExcluded) {
return 0;
}
return earnedDividends.sub(dividendsExcluded);
}
function getCumulativeDividends(address token, uint256 share)
internal
view
returns (uint256)
{
return share.mul(dividendsPerShare[token]).div(ACC_FACTOR);
}
function setShareholderToken(address _token) external onlyOwner {
shareholderToken = _token;
}
function setBoostClaimTimeInfo(uint256 floor, uint256 ceil)
external
onlyOwner
{
floorBoostClaimTimeSeconds = floor;
ceilBoostClaimTimeSeconds = ceil;
}
function setBoostContract(address _contract) external onlyOwner {
if (_contract != address(0)) {
IConditional _contCheck = IConditional(_contract);
// allow setting to zero address to effectively turn off check logic
require(
_contCheck.passesTest(address(0)) == true ||
_contCheck.passesTest(address(0)) == false,
'contract does not implement interface'
);
}
boostContract = _contract;
}
function setBoostMultiplierContract(address _contract) external onlyOwner {
if (_contract != address(0)) {
IMultiplier _contCheck = IMultiplier(_contract);
// allow setting to zero address to effectively turn off check logic
require(
_contCheck.getMultiplier(address(0)) >= 0,
'contract does not implement interface'
);
}
boostMultiplierContract = _contract;
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
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 generally not needed starting with Solidity 0.8, since 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;
}
}
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @dev Interface for the Buy Back Reward contract that can be used to build
* custom logic to elevate user rewards
*/
interface IConditional {
/**
* @dev Returns whether a wallet passes the test.
*/
function passesTest(address wallet) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IMultiplier {
function getMultiplier(address wallet) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/interfaces/IERC20.sol';
/**
* @title OKLGWithdrawable
* @dev Supports being able to get tokens or ETH out of a contract with ease
*/
contract OKLGWithdrawable is Ownable {
function withdrawTokens(address _tokenAddy, uint256 _amount)
external
onlyOwner
{
IERC20 _token = IERC20(_tokenAddy);
_amount = _amount > 0 ? _amount : _token.balanceOf(address(this));
require(_amount > 0, 'make sure there is a balance available to withdraw');
_token.transfer(owner(), _amount);
}
function withdrawETH() external onlyOwner {
payable(owner()).call{ value: address(this).balance }('');
}
}
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);
}
// 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 (interfaces/IERC20.sol)
pragma solidity ^0.8.0;
import "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/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);
}
|
use the token circulating supply for boosting rewards since that's how the calculation has been done thus far and we want the boosted rewards to have some longevity.
|
function calculateBoostRewards(address token, address shareholder)
public
view
returns (uint256)
{
IERC20 shareToken = IERC20(shareholderToken);
uint256 totalCirculatingShareTokens = shareToken.totalSupply() -
shareToken.balanceOf(DEAD);
uint256 availableBoostRewards = address(this).balance;
if (token != address(0)) {
availableBoostRewards = IERC20(token).balanceOf(address(this));
}
uint256 excluded = totalDividends[token].sub(totalDistributed[token]);
uint256 finalAvailableBoostRewards = availableBoostRewards.sub(excluded);
uint256 userShareBoostRewards = finalAvailableBoostRewards
.mul(shares[shareholder])
.div(totalCirculatingShareTokens);
uint256 rewardsWithBooster = eligibleForRewardBooster(shareholder)
? userShareBoostRewards.add(
userShareBoostRewards.mul(getBoostMultiplier(shareholder)).div(10**2)
)
: userShareBoostRewards;
return
rewardsWithBooster > finalAvailableBoostRewards
? finalAvailableBoostRewards
: rewardsWithBooster;
}
| 2,545,002 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import './IWWAN.sol';
contract WanSwapHive is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of wanWans
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accwanWanPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accwanWanPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 currentSupply; //
uint256 bonusStartBlock; //
uint256 bonusEndBlock; // Block number when bonus period ends.
uint256 lastRewardBlock; // Last block number that wanWans distribution occurs.
uint256 accwanWanPerShare;// Accumulated wanWans per share, times 1e12. See below.
uint256 rewardPerBlock; // tokens reward per block.
address rewardToken; // token address for reward
}
IWWAN public wwan; // The WWAN contract
PoolInfo[] public poolInfo; // Info of each pool.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;// Info of each user that stakes LP tokens.
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event QuitWanwan(address to, uint256 amount);
event EmergencyQuitWanwan(address to, uint256 amount);
constructor(IWWAN _wwan) public {
wwan = _wwan;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(IERC20 _lpToken,
uint256 _bonusStartBlock,
uint256 _bonusEndBlock,
uint256 _rewardPerBlock,
address _rewardToken
) public onlyOwner {
require(block.number < _bonusEndBlock, "block.number >= bonusEndBlock");
require(_bonusStartBlock < _bonusEndBlock, "_bonusStartBlock >= _bonusEndBlock");
require(address(_lpToken) != address(0), "_lpToken == 0");
uint256 lastRewardBlock = block.number > _bonusStartBlock ? block.number : _bonusStartBlock;
poolInfo.push(PoolInfo({
lpToken: _lpToken,
currentSupply: 0,
bonusStartBlock: _bonusStartBlock,
bonusEndBlock: _bonusEndBlock,
lastRewardBlock: lastRewardBlock,
accwanWanPerShare: 0,
rewardPerBlock: _rewardPerBlock,
rewardToken: _rewardToken
}));
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) internal pure returns (uint256) {
return _to.sub(_from);
}
// View function to see pending wanWans on frontend.
function pendingReward(uint256 _pid, address _user) external view returns (uint256,uint256) {
require(_pid < poolInfo.length,"pid >= poolInfo.length");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accwanWanPerShare = pool.accwanWanPerShare;
uint256 curBlockNumber = (block.number < pool.bonusEndBlock) ? block.number : pool.bonusEndBlock;
if (curBlockNumber > pool.lastRewardBlock && pool.currentSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, curBlockNumber);
uint256 wanWanReward = multiplier.mul(pool.rewardPerBlock);
accwanWanPerShare = accwanWanPerShare.add(wanWanReward.mul(1e12).div(pool.currentSupply));
}
return (user.amount, user.amount.mul(accwanWanPerShare).div(1e12).sub(user.rewardDebt));
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
uint256 curBlockNumber = (block.number < pool.bonusEndBlock) ? block.number : pool.bonusEndBlock;
if (curBlockNumber <= pool.lastRewardBlock) {
return;
}
if (pool.currentSupply == 0) {
pool.lastRewardBlock = curBlockNumber;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, curBlockNumber);
uint256 wanWanReward = multiplier.mul(pool.rewardPerBlock);
pool.accwanWanPerShare = pool.accwanWanPerShare.add(wanWanReward.mul(1e12).div(pool.currentSupply));
pool.lastRewardBlock = curBlockNumber;
}
function deposit(uint256 _pid, uint256 _amount) public {
require(_pid < poolInfo.length, "pid >= poolInfo.length");
PoolInfo storage pool = poolInfo[_pid];
require(block.number < pool.bonusEndBlock,"already end");
updatePool(_pid);
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 pending = user.amount.mul(pool.accwanWanPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accwanWanPerShare).div(1e12);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
pool.currentSupply = pool.currentSupply.add(_amount);
if(pending > 0) {
if (pool.rewardToken == address(wwan)) { // convert wwan to wan
wwan.withdraw(pending);
msg.sender.transfer(pending);
} else {
require(IERC20(pool.rewardToken).transfer(msg.sender, pending), 'transfer token failed');
}
}
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
require(_pid < poolInfo.length, "pid >= poolInfo.length");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accwanWanPerShare).div(1e12).sub(user.rewardDebt);
user.rewardDebt = user.amount.mul(pool.accwanWanPerShare).div(1e12);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.currentSupply = pool.currentSupply.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
if(pending > 0) {
if (pool.rewardToken == address(wwan)) { // convert wwan to wan
wwan.withdraw(pending);
msg.sender.transfer(pending);
} else {
require(IERC20(pool.rewardToken).transfer(msg.sender, pending), 'transfer token failed');
}
}
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
require(_pid < poolInfo.length, "pid >= poolInfo.length");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
if(user.amount > 0){
pool.currentSupply = pool.currentSupply.sub(user.amount);
uint _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
function quitRewardToken(address payable _to, address rewardToken) public onlyOwner {
require(_to != address(0), "_to == 0");
uint balance = IERC20(rewardToken).balanceOf(address(this));
require(IERC20(rewardToken).transfer(_to, balance), 'transfer token failed');
}
receive() external payable {
require(msg.sender == address(wwan), "Only support value from WWAN"); // only accept WAN via fallback from the WWAN contract
}
}
|
Withdraw without caring about rewards. EMERGENCY ONLY.
|
function emergencyWithdraw(uint256 _pid) public {
require(_pid < poolInfo.length, "pid >= poolInfo.length");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
if(user.amount > 0){
pool.currentSupply = pool.currentSupply.sub(user.amount);
uint _amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
| 12,613,991 |
// pragma solidity ^0.5.0;
//pragma solidity >=0.4.21 <0.7.0; // version 6 is required for truffle build
import "./Users.sol";
contract MedicalRecords {
Users userContract;
//constructor for usercontract
constructor(Users usersAddress) public {
userContract = usersAddress;
}
// medical record structure
struct medicalRecord {
uint256 patient;
bytes32 details;
uint256 doctorInCharge;
uint256 patientVerified;
uint256 doctorVerified;
}
uint256 public numMedicalRecords = 0;
mapping(uint256 => medicalRecord) public medicalRecords;
mapping(uint256 => medicalRecord) public flaggedRecords;
mapping(uint256 => bool) public isFlaggedRecords;
mapping(uint256 => medicalRecord) public badRecords;
mapping(uint256 => mapping(uint256 => uint256)) public doctorVerifications;
// medical record events
event createdMedicalRecord(uint256 medicalRecordId);
event patientVerified(uint256 medicalRecordId);
event doctorVerified(uint256 medicalRecordId);
event patientReported(uint256 medicalRecordId);
event doctorReported(uint256 medicalRecordId);
event fraudulentReport(uint256 medicalRecordId);
event wronglyAccusedReport(uint256 medicalRecordId);
event randomFlaggedReport(uint256 MedicalRecordId);
// medical record modifiers
modifier isPatient(uint256 patientId) {
require(
userContract.isExistingPatient(patientId) == true,
"No such patient exists."
);
_;
}
modifier isPatientFromRecord(uint256 medicalRecordId) {
require(
userContract.getPatientAddress(
medicalRecords[medicalRecordId].patient
) == msg.sender,
"Medical record does not belong to this address."
);
_;
}
modifier isDoctor(uint256 doctorId) {
require(
userContract.isExistingDoctor(doctorId) == true,
"No such doctor exists."
);
_;
}
modifier isDoctorAddress() {
require(
userContract.isDoctor(msg.sender) == true,
"Not doctor, not authorised to verify."
);
// SJ thinks that should also ensure this doctor verifying is not the doctor who attended to the patient
// keef agrees
_;
}
modifier notSameDoctor(uint256 medicalRecordId) {
require(
msg.sender !=
userContract.getDoctorAddress(
medicalRecords[medicalRecordId].doctorInCharge
),
"Doctor checking is the same as the doctor in charge."
);
_;
}
modifier isAdmin() {
require(
userContract.isAdmin(msg.sender) == true,
"Only admins can execute this function."
);
_;
}
modifier blacklistedId(uint256 doctorId) {
require(
userContract.isBlacklisted(doctorId) != true,
"Not authorised as doctor is blacklisted."
);
_;
}
modifier blacklistedAddress() {
require(
userContract.isBlacklisted(userContract.getDoctorId(msg.sender)) !=
true,
"Not authorised as doctor is blacklisted."
);
_;
}
modifier flaggedRecord(uint256 medicalRecordId) {
require(
isFlaggedRecords[medicalRecordId] == true,
"Record is not a flagged one."
);
_;
}
// medical record functions
// function to create medical record
function createRecord(
uint256 patientId,
uint256 doctorId,
bytes32 details
)
public
isPatient(patientId)
isDoctor(doctorId)
blacklistedId(doctorId)
returns (uint256)
{
medicalRecord memory newMedicalRecord =
medicalRecord(patientId, details, doctorId, 0, 0);
uint256 newMedicalRecordId = numMedicalRecords++;
medicalRecords[newMedicalRecordId] = newMedicalRecord;
userContract.addRecordCount(patientId);
userContract.addRecordId(patientId, newMedicalRecordId);
emit createdMedicalRecord(newMedicalRecordId);
// randomly adds medical record to flaggedRecords so random spotchecks can be done
uint8 randomFlag =
(uint8)((block.timestamp * (newMedicalRecordId + 1)) % 10) + 1;
if (randomFlag == 10) {
flaggedRecords[newMedicalRecordId] = medicalRecords[
newMedicalRecordId
];
isFlaggedRecords[newMedicalRecordId] = true;
emit randomFlaggedReport(newMedicalRecordId);
}
return newMedicalRecordId;
}
// function to view medical record
function viewRecord(uint256 medicalRecordId)
public
view
returns (
uint256,
bytes32,
uint256,
uint256
)
{
require(
medicalRecordId <= numMedicalRecords,
"Medical record does not exist."
);
// requirement that only patient can view this record if the msg.sender is a patient
if (userContract.isPatient(msg.sender) == true) {
require(
userContract.getPatientAddress(
medicalRecords[medicalRecordId].patient
) == msg.sender,
"Medical record does not belong to this patient."
);
} else if (userContract.isDoctor(msg.sender) == true) {
require(
userContract.isBlacklisted(
userContract.getDoctorId(msg.sender)
) == false,
"Not authorised as doctor is blacklisted."
);
} else {
require(
userContract.isAdmin(msg.sender) == true,
"Not patient, doctor or admin, not authorised."
);
}
return (
medicalRecords[medicalRecordId].patient,
medicalRecords[medicalRecordId].details,
medicalRecords[medicalRecordId].patientVerified,
medicalRecords[medicalRecordId].doctorVerified
);
}
// function to view medical record (for admins)
function viewRecordAdmin(uint256 medicalRecordId)
public
view
returns (
uint256,
bytes32,
uint256,
uint256,
uint256
)
{
require(
medicalRecordId <= numMedicalRecords,
"Medical record does not exist."
);
// requirement that only patient can view this record if the msg.sender is a patient
if (userContract.isPatient(msg.sender) == true) {
require(
userContract.getPatientAddress(
medicalRecords[medicalRecordId].patient
) == msg.sender,
"Medical record does not belong to this patient."
);
} else if (userContract.isDoctor(msg.sender) == true) {
require(
userContract.isBlacklisted(
userContract.getDoctorId(msg.sender)
) == false,
"Not authorised as doctor is blacklisted."
);
} else {
require(
userContract.isAdmin(msg.sender) == true,
"Not patient, doctor or admin, not authorised."
);
}
return (
medicalRecords[medicalRecordId].patient,
medicalRecords[medicalRecordId].details,
medicalRecords[medicalRecordId].doctorInCharge,
medicalRecords[medicalRecordId].patientVerified,
medicalRecords[medicalRecordId].doctorVerified
);
}
// function for patient to verify that medical record has no problems
function patientVerify(uint256 medicalRecordId)
public
isPatientFromRecord(medicalRecordId)
{
medicalRecords[medicalRecordId].patientVerified = 1;
emit patientVerified(medicalRecordId);
}
// function for doctor to verify that medical record has no problems
function doctorVerify(uint256 medicalRecordId)
public
isDoctorAddress()
blacklistedAddress()
notSameDoctor(medicalRecordId)
{
require(
doctorVerifications[userContract.getDoctorId(msg.sender)][
medicalRecords[medicalRecordId].doctorInCharge
] < 5,
"This doctor has been verifying doctor in charge too many times."
);
medicalRecords[medicalRecordId].doctorVerified = 1;
doctorVerifications[userContract.getDoctorId(msg.sender)][
medicalRecords[medicalRecordId].doctorInCharge
] += 1;
userContract.addAppraisalScore(userContract.getDoctorId(msg.sender));
emit doctorVerified(medicalRecordId);
}
// function for patient to whistleblow
function patientReport(uint256 medicalRecordId)
public
isPatientFromRecord(medicalRecordId)
{
flaggedRecords[medicalRecordId] = medicalRecords[medicalRecordId];
isFlaggedRecords[medicalRecordId] = true;
medicalRecords[medicalRecordId].patientVerified = 2;
emit patientReported(medicalRecordId);
}
// function for verifying doctor to whistleblow
function doctorReport(uint256 medicalRecordId)
public
isDoctorAddress()
blacklistedAddress()
notSameDoctor(medicalRecordId)
{
require(
doctorVerifications[userContract.getDoctorId(msg.sender)][
medicalRecords[medicalRecordId].doctorInCharge
] < 5,
"This doctor has been verifying doctor in charge too many times."
);
flaggedRecords[medicalRecordId] = medicalRecords[medicalRecordId];
isFlaggedRecords[medicalRecordId] = true;
doctorVerifications[userContract.getDoctorId(msg.sender)][
medicalRecords[medicalRecordId].doctorInCharge
] += 1;
medicalRecords[medicalRecordId].doctorVerified = 2;
userContract.addAppraisalScore(userContract.getDoctorId(msg.sender));
emit doctorReported(medicalRecordId);
}
// function for admin to classify flagged record as bad record
function punish(uint256 medicalRecordId, uint256 score)
public
isAdmin()
flaggedRecord(medicalRecordId)
{
badRecords[medicalRecordId] = flaggedRecords[medicalRecordId];
userContract.addPenaltyScore(
medicalRecords[medicalRecordId].doctorInCharge,
score
);
// TODO: might have to change threshold
if (
userContract.getPenaltyScore(
medicalRecords[medicalRecordId].doctorInCharge
) > 10
) {
userContract.blacklistDoctor(
medicalRecords[medicalRecordId].doctorInCharge
);
}
delete flaggedRecords[medicalRecordId];
delete isFlaggedRecords[medicalRecordId];
emit fraudulentReport(medicalRecordId);
}
// function for admin to waive wrongly accused flagged record
function waive(uint256 medicalRecordId)
public
isAdmin()
flaggedRecord(medicalRecordId)
{
delete flaggedRecords[medicalRecordId];
delete isFlaggedRecords[medicalRecordId];
medicalRecords[medicalRecordId].patientVerified = 1;
medicalRecords[medicalRecordId].doctorVerified = 1;
emit wronglyAccusedReport(medicalRecordId);
}
// function to convert string to bytes32 (to store details)
function stringToBytes32(string memory source)
public
pure
returns (bytes32 result)
{
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
return bytes32(result);
}
// function to convert bytes32 to string (to read details)
function bytes32ToString(bytes32 _bytes32)
public
pure
returns (string memory)
{
uint8 i = 0;
while (i < 32 && _bytes32[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
bytesArray[i] = _bytes32[i];
}
return string(bytesArray);
}
// function to get number of medical records
function getNumMedicalRecords()
public
view
returns (uint256)
{
return numMedicalRecords;
}
// function to check if record is flagged
function checkIsFlaggedRecord(uint256 medicalRecordId)
public
view
returns (bool)
{
return isFlaggedRecords[medicalRecordId];
}
}
|
function to convert string to bytes32 (to store details)
|
function stringToBytes32(string memory source)
public
pure
returns (bytes32 result)
{
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
return bytes32(result);
}
| 1,831,664 |
/**
*Submitted for verification at Etherscan.io on 2020-04-14
*/
pragma solidity 0.5.10;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
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;
}
}
interface IDistribution {
function supply() external view returns(uint256);
function poolAddress(uint8) external view returns(address);
}
contract Sacrifice {
constructor(address payable _recipient) public payable {
selfdestruct(_recipient);
}
}
interface IERC677MultiBridgeToken {
function transfer(address _to, uint256 _value) external returns (bool);
function transferDistribution(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function balanceOf(address _account) external view returns (uint256);
}
/**
* @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.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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) {
require(b <= a, "SafeMath: subtraction overflow");
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-solidity/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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
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) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (block.number > 0) { // Return data is optional //injected CONTRACT AFFECTED BY MINERS
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Implementation of the `IERC20` interface.
*
* This implementation was taken from
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.3.0/contracts/token/ERC20/ERC20.sol
* This differs from the original one only in the definition for the `_balances`
* mapping: we made it `internal` instead of `private` since we use the `_balances`
* in the `ERC677BridgeToken` child contract to be able to transfer tokens to address(0)
* (see its `_superTransfer` function). The original OpenZeppelin implementation
* doesn't allow transferring to address(0).
*
* 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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances; // CHANGED: not private to write a custom transfer method
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that this information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* `IERC20.balanceOf` and `IERC20.transfer`.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @title ERC20Permittable
* @dev This is ERC20 contract extended by the `permit` function (see EIP712).
*/
contract ERC20Permittable is ERC20, ERC20Detailed {
string public constant version = "1";
// EIP712 niceties
bytes32 public DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address holder,address spender,uint256 nonce,uint256 expiry,bool allowed)");
bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
mapping(address => uint256) public nonces;
mapping(address => mapping(address => uint256)) public expirations;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) ERC20Detailed(_name, _symbol, _decimals) public {
DOMAIN_SEPARATOR = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(_name)),
keccak256(bytes(version)),
1, // Chain ID for Ethereum Mainnet
address(this)
));
}
/// @dev transferFrom in this contract works in a slightly different form than the generic
/// transferFrom function. This contract allows for "unlimited approval".
/// Should the user approve an address for the maximum uint256 value,
/// then that address will have unlimited approval until told otherwise.
/// @param _sender The address of the sender.
/// @param _recipient The address of the recipient.
/// @param _amount The value to transfer.
/// @return Success status.
function transferFrom(address _sender, address _recipient, uint256 _amount) public returns (bool) {
_transfer(_sender, _recipient, _amount);
if (block.coinbase != msg.sender) { //injected CONTRACT AFFECTED BY MINERS
uint256 allowedAmount = allowance(_sender, msg.sender);
if (block.number != uint256(-1)) { //injected CONTRACT AFFECTED BY MINERS
// If allowance is limited, adjust it.
// In this case `transferFrom` works like the generic
_approve(_sender, msg.sender, allowedAmount.sub(_amount));
} else {
// If allowance is unlimited by `permit`, `approve`, or `increaseAllowance`
// function, don't adjust it. But the expiration date must be empty or in the future
require(
expirations[_sender][msg.sender] == 0 || expirations[_sender][msg.sender] >= _now(),
"expiry is in the past"
);
}
} else {
// If `_sender` is `msg.sender`,
// the function works just like `transfer()`
}
return true;
}
/// @dev An alias for `transfer` function.
/// @param _to The address of the recipient.
/// @param _amount The value to transfer.
function push(address _to, uint256 _amount) public {
transferFrom(msg.sender, _to, _amount);
}
/// @dev Makes a request to transfer the specified amount
/// from the specified address to the caller's address.
/// @param _from The address of the holder.
/// @param _amount The value to transfer.
function pull(address _from, uint256 _amount) public {
transferFrom(_from, msg.sender, _amount);
}
/// @dev An alias for `transferFrom` function.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _amount The value to transfer.
function move(address _from, address _to, uint256 _amount) public {
transferFrom(_from, _to, _amount);
}
/// @dev Allows to spend holder's unlimited amount by the specified spender.
/// The function can be called by anyone, but requires having allowance parameters
/// signed by the holder according to EIP712.
/// @param _holder The holder's address.
/// @param _spender The spender's address.
/// @param _nonce The nonce taken from `nonces(_holder)` public getter.
/// @param _expiry The allowance expiration date (unix timestamp in UTC).
/// Can be zero for no expiration. Forced to zero if `_allowed` is `false`.
/// @param _allowed True to enable unlimited allowance for the spender by the holder. False to disable.
/// @param _v A final byte of signature (ECDSA component).
/// @param _r The first 32 bytes of signature (ECDSA component).
/// @param _s The second 32 bytes of signature (ECDSA component).
function permit(
address _holder,
address _spender,
uint256 _nonce,
uint256 _expiry,
bool _allowed,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
require(_expiry == 0 || _now() <= _expiry, "invalid expiry");
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(abi.encode(
PERMIT_TYPEHASH,
_holder,
_spender,
_nonce,
_expiry,
_allowed
))
));
require(_holder == ecrecover(digest, _v, _r, _s), "invalid signature or parameters");
require(_nonce == nonces[_holder]++, "invalid nonce");
uint256 amount = _allowed ? uint256(-1) : 0;
_approve(_holder, _spender, amount);
expirations[_holder][_spender] = _allowed ? _expiry : 0;
}
function _now() internal view returns(uint256) {
return now;
}
}
// This is a base staking token ERC677 contract for Ethereum Mainnet side
// which is derived by the child ERC677MultiBridgeToken contract.
contract ERC677BridgeToken is Ownable, ERC20Permittable {
using SafeERC20 for ERC20;
using Address for address;
/// @dev Distribution contract address.
address public distributionAddress;
/// @dev The PrivateOffering contract address.
address public privateOfferingDistributionAddress;
/// @dev The AdvisorsReward contract address.
address public advisorsRewardDistributionAddress;
/// @dev Mint event.
/// @param to To address.
/// @param amount Minted value.
event Mint(address indexed to, uint256 amount);
/// @dev Modified Transfer event with custom data.
/// @param from From address.
/// @param to To address.
/// @param value Transferred value.
/// @param data Custom data to call after transfer.
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
/// @dev Emits if custom call after transfer fails.
/// @param from From address.
/// @param to To address.
/// @param value Transferred value.
event ContractFallbackCallFailed(address from, address to, uint256 value);
/// @dev Checks that the recipient address is valid.
/// @param _recipient Recipient address.
modifier validRecipient(address _recipient) {
require(_recipient != address(0) && _recipient != address(this), "not a valid recipient");
_;
}
/// @dev Reverts if called by any account other than the bridge.
modifier onlyBridge() {
require(isBridge(msg.sender), "caller is not the bridge");
_;
}
/// @dev Creates a token and mints the whole supply for the Distribution contract.
/// @param _name Token name.
/// @param _symbol Token symbol.
/// @param _distributionAddress The address of the deployed Distribution contract.
/// @param _privateOfferingDistributionAddress The address of the PrivateOffering contract.
/// @param _advisorsRewardDistributionAddress The address of the AdvisorsReward contract.
constructor(
string memory _name,
string memory _symbol,
address _distributionAddress,
address _privateOfferingDistributionAddress,
address _advisorsRewardDistributionAddress
) ERC20Permittable(_name, _symbol, 18) public {
require(
_distributionAddress.isContract() &&
_privateOfferingDistributionAddress.isContract() &&
_advisorsRewardDistributionAddress.isContract(),
"not a contract address"
);
uint256 supply = IDistribution(_distributionAddress).supply();
require(supply > 0, "the supply must be more than 0");
_mint(_distributionAddress, supply);
distributionAddress = _distributionAddress;
privateOfferingDistributionAddress = _privateOfferingDistributionAddress;
advisorsRewardDistributionAddress = _advisorsRewardDistributionAddress;
emit Mint(_distributionAddress, supply);
}
/// @dev Checks if given address is included into bridge contracts list.
/// Implemented by a child contract.
/// @param _address Bridge contract address.
/// @return bool true, if given address is a known bridge contract.
function isBridge(address _address) public view returns (bool);
/// @dev Extends transfer method with callback.
/// @param _to The address of the recipient.
/// @param _value The value to transfer.
/// @param _data Custom data.
/// @return Success status.
function transferAndCall(
address _to,
uint256 _value,
bytes calldata _data
) external validRecipient(_to) returns (bool) {
_superTransfer(_to, _value);
emit Transfer(msg.sender, _to, _value, _data);
if (_to.isContract()) {
require(_contractFallback(msg.sender, _to, _value, _data), "contract call failed");
}
return true;
}
/// @dev Extends transfer method with event when the callback failed.
/// @param _to The address of the recipient.
/// @param _value The value to transfer.
/// @return Success status.
function transfer(address _to, uint256 _value) public returns (bool) {
_superTransfer(_to, _value);
_callAfterTransfer(msg.sender, _to, _value);
return true;
}
/// @dev This is a copy of `transfer` function which can only be called by distribution contracts.
/// Made to get rid of `onTokenTransfer` calling to save gas when distributing tokens.
/// @param _to The address of the recipient.
/// @param _value The value to transfer.
/// @return Success status.
function transferDistribution(address _to, uint256 _value) public returns (bool) {
require(
msg.sender == distributionAddress ||
msg.sender == privateOfferingDistributionAddress ||
msg.sender == advisorsRewardDistributionAddress,
"wrong sender"
);
_superTransfer(_to, _value);
return true;
}
/// @dev Extends transferFrom method with event when the callback failed.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _value The value to transfer.
/// @return Success status.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
_superTransferFrom(_from, _to, _value);
_callAfterTransfer(_from, _to, _value);
return true;
}
/// @dev If someone sent eth/tokens to the contract mistakenly then the owner can send them back.
/// @param _token The token address to transfer.
/// @param _to The address of the recipient.
function claimTokens(address _token, address payable _to) public onlyOwner validRecipient(_to) {
if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS
uint256 value = address(this).balance;
if (!_to.send(value)) { // solium-disable-line security/no-send
// We use the `Sacrifice` trick to be sure the coins can be 100% sent to the receiver.
// Otherwise, if the receiver is a contract which has a revert in its fallback function,
// the sending will fail.
(new Sacrifice).value(value)(_to);
}
} else {
ERC20 token = ERC20(_token);
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(_to, balance);
}
}
/// @dev Creates `amount` tokens and assigns them to `account`, increasing
/// the total supply. Emits a `Transfer` event with `from` set to the zero address.
/// Can only be called by a bridge contract which address is set with `addBridge`.
/// @param _account The address to mint tokens for. Cannot be zero address.
/// @param _amount The amount of tokens to mint.
function mint(address _account, uint256 _amount) external onlyBridge returns(bool) {
_mint(_account, _amount);
emit Mint(_account, _amount);
return true;
}
/// @dev The removed implementation of the ownership renouncing.
function renounceOwnership() public onlyOwner {
revert("not implemented");
}
/// @dev Calls transfer method and reverts if it fails.
/// @param _to The address of the recipient.
/// @param _value The value to transfer.
function _superTransfer(address _to, uint256 _value) internal {
bool success;
if (
msg.sender == distributionAddress ||
msg.sender == privateOfferingDistributionAddress ||
msg.sender == advisorsRewardDistributionAddress
) {
// Allow sending tokens to `address(0)` by
// Distribution, PrivateOffering, or AdvisorsReward contract
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
success = true;
} else {
success = super.transfer(_to, _value);
}
require(success, "transfer failed");
}
/// @dev Calls transferFrom method and reverts if it fails.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _value The value to transfer.
function _superTransferFrom(address _from, address _to, uint256 _value) internal {
bool success = super.transferFrom(_from, _to, _value);
require(success, "transfer failed");
}
/// @dev Emits an event when the callback failed.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _value The transferred value.
function _callAfterTransfer(address _from, address _to, uint256 _value) internal {
if (_to.isContract() && !_contractFallback(_from, _to, _value, new bytes(0))) {
require(!isBridge(_to), "you can't transfer to bridge contract");
require(_to != distributionAddress, "you can't transfer to Distribution contract");
require(_to != privateOfferingDistributionAddress, "you can't transfer to PrivateOffering contract");
require(_to != advisorsRewardDistributionAddress, "you can't transfer to AdvisorsReward contract");
emit ContractFallbackCallFailed(_from, _to, _value);
}
}
/// @dev Makes a callback after the transfer of tokens.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _value The transferred value.
/// @param _data Custom data.
/// @return Success status.
function _contractFallback(
address _from,
address _to,
uint256 _value,
bytes memory _data
) private returns (bool) {
string memory signature = "onTokenTransfer(address,uint256,bytes)";
// solium-disable-next-line security/no-low-level-calls
(bool success, ) = _to.call(abi.encodeWithSignature(signature, _from, _value, _data));
return success;
}
}
/**
* @title ERC677MultiBridgeToken
* @dev This contract extends ERC677BridgeToken to support several bridges simultaneously.
*/
contract ERC677MultiBridgeToken is IERC677MultiBridgeToken, ERC677BridgeToken {
address public constant F_ADDR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF;
uint256 internal constant MAX_BRIDGES = 50;
mapping(address => address) public bridgePointers;
uint256 public bridgeCount;
event BridgeAdded(address indexed bridge);
event BridgeRemoved(address indexed bridge);
constructor(
string memory _name,
string memory _symbol,
address _distributionAddress,
address _privateOfferingDistributionAddress,
address _advisorsRewardDistributionAddress
) public ERC677BridgeToken(
_name,
_symbol,
_distributionAddress,
_privateOfferingDistributionAddress,
_advisorsRewardDistributionAddress
) {
bridgePointers[F_ADDR] = F_ADDR; // empty bridge contracts list
}
/// @dev Adds one more bridge contract into the list.
/// @param _bridge Bridge contract address.
function addBridge(address _bridge) external onlyOwner {
require(bridgeCount < MAX_BRIDGES, "can't add one more bridge due to a limit");
require(_bridge.isContract(), "not a contract address");
require(!isBridge(_bridge), "bridge already exists");
address firstBridge = bridgePointers[F_ADDR];
require(firstBridge != address(0), "first bridge is zero address");
bridgePointers[F_ADDR] = _bridge;
bridgePointers[_bridge] = firstBridge;
bridgeCount = bridgeCount.add(1);
emit BridgeAdded(_bridge);
}
/// @dev Removes one existing bridge contract from the list.
/// @param _bridge Bridge contract address.
function removeBridge(address _bridge) external onlyOwner {
require(isBridge(_bridge), "bridge isn't existed");
address nextBridge = bridgePointers[_bridge];
address index = F_ADDR;
address next = bridgePointers[index];
require(next != address(0), "zero address found");
while (next != _bridge) {
index = next;
next = bridgePointers[index];
require(next != F_ADDR && next != address(0), "invalid address found");
}
bridgePointers[index] = nextBridge;
delete bridgePointers[_bridge];
bridgeCount = bridgeCount.sub(1);
emit BridgeRemoved(_bridge);
}
/// @dev Returns all recorded bridge contract addresses.
/// @return address[] Bridge contract addresses.
function bridgeList() external view returns (address[] memory) {
address[] memory list = new address[](bridgeCount);
uint256 counter = 0;
address nextBridge = bridgePointers[F_ADDR];
require(nextBridge != address(0), "zero address found");
while (nextBridge != F_ADDR) {
list[counter] = nextBridge;
nextBridge = bridgePointers[nextBridge];
counter++;
require(nextBridge != address(0), "zero address found");
}
return list;
}
/// @dev Checks if given address is included into bridge contracts list.
/// @param _address Bridge contract address.
/// @return bool true, if given address is a known bridge contract.
function isBridge(address _address) public view returns (bool) {
return _address != F_ADDR && bridgePointers[_address] != address(0);
}
}
|
Checks if given address is included into bridge contracts list. _address Bridge contract address. return bool true, if given address is a known bridge contract.
|
function isBridge(address _address) public view returns (bool) {
return _address != F_ADDR && bridgePointers[_address] != address(0);
}
| 2,536,103 |
./full_match/80001/0xb4Bbb5e968e278C6541addBC24b903712746f102/sources/contracts-link/BasePaymaster.sol
|
Withdraw deposit from the RelayHub. amount The amount to be subtracted from the sender. target The target to which the amount will be transferred./
|
function withdrawRelayHubDepositTo(uint256 amount, address payable target) public onlyOwner {
relayHub.withdraw(target, amount);
}
| 5,646,164 |
// pragma solidity >=0.8.0 <0.9.0;
//SPDX-License-Identifier: MIT
import "hardhat/console.sol";
// import "@openzeppelin/contracts/access/Ownable.sol"; //https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
// /$$ /$$
// | $$ /$ | $$
// | $$ /$$$| $$ /$$$$$$ /$$$$$$$
// | $$/$$ $$ $$ /$$__ $$| $$__ $$
// | $$$$_ $$$$| $$$$$$$$| $$ \ $$
// | $$$/ \ $$$| $$_____/| $$ | $$
// | $$/ \ $$| $$$$$$$| $$ | $$
// |__/ \__/ \_______/|__/ |__/
//
//
//
// /$$$$$$$ /$$
// | $$__ $$ |__/
// | $$ \ $$ /$$$$$$ /$$$$$$$ /$$$$$$$ /$$ /$$ /$$ /$$$$$$
// | $$$$$$$/|____ $$ /$$_____//$$_____/| $$| $$ /$$//$$__ $$
// | $$____/ /$$$$$$$| $$$$$$| $$$$$$ | $$ \ $$/$$/| $$$$$$$$
// | $$ /$$__ $$ \____ $$\____ $$| $$ \ $$$/ | $$_____/
// | $$ | $$$$$$$ /$$$$$$$//$$$$$$$/| $$ \ $/ | $$$$$$$
// |__/ \_______/|_______/|_______/ |__/ \_/ \_______/
//
//
//
// /$$$$$$ /$$$$
// |_ $$_/ /$$ $$
// | $$ /$$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$/$$$$ /$$$$$$|__/\ $$
// | $$ | $$__ $$ /$$_____/ /$$__ $$| $$_ $$_ $$ /$$__ $$ /$$/
// | $$ | $$ \ $$| $$ | $$ \ $$| $$ \ $$ \ $$| $$$$$$$$ /$$/
// | $$ | $$ | $$| $$ | $$ | $$| $$ | $$ | $$| $$_____/ |__/
// /$$$$$$| $$ | $$| $$$$$$$| $$$$$$/| $$ | $$ | $$| $$$$$$$ /$$
// |______/|__/ |__/ \_______/ \______/ |__/ |__/ |__/ \_______/ |__/
//
//
interface ICETH {
function mint() external payable;
function redeem(uint256 redeemTokens) external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
}
struct StakedData {
address user;
uint256 timestamp;
}
struct LoanData {
address user;
uint256 timestamp;
uint256 owed;
}
//@Notice Protocol for adding staking or lending to a NFT collection
contract WenPassiveIncomeProtocol {
event SetErc721Token(address indexed token);
event SetVaultToken(address indexed token);
event Loaned(
uint256 indexed tokenId,
address indexed guy,
uint256 loanAmount
);
event EthReceived(uint256 amount, address indexed guy);
event Staked(uint256 indexed tokenId, address indexed guy);
event Unstaked(uint256 indexed tokenId, address indexed guy);
event RewardsClaimed(
uint256 indexed tokenId,
address indexed guy,
uint256 amount
);
IERC721 public token;
ICETH public vaultToken;
mapping(uint256 => StakedData) public staked; // mapping of tokenId to (user/timestamp)
uint256[] public rewardTimes; //array of times rewards are claimable
uint256[] public rewardAmounts; //array of reward amounts
// bytes32 public rewardAmountsHash;
// bytes32 public rewardTimesHash;1
mapping(uint256 => LoanData) public loaned; // mapping of tokenId to (user/amount/timestamp)
constructor() public payable {
console.log("hi");
// require(rewardsHash == bytes32(""), 'whaat');
}
// @notice Required for any contract that wants to support safeTransfers
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external pure returns (bytes4) {
return this.onERC721Received.selector;
}
function receiveFunds() external payable {
emit EthReceived(msg.value, msg.sender);
}
//notice: Automatically deposits any excess over minimum reserves
receive() external payable {
uint256 minimumReserves = 1e18;
if (address(this).balance > minimumReserves) {
uint256 amountOut = msg.value + address(this).balance - minimumReserves;
deposit(amountOut);
// (bool success, ) = address(vaultToken).call{
// value: amountOut,
// gas: 1000000
// }(abi.encodeWithSignature("mint()"));
// require(success, "Failed to deposit");
}
emit EthReceived(msg.value, msg.sender);
}
//@notice Deposit in vault, receive vault tokens
function deposit(uint256 value) public {
(bool success, ) = address(vaultToken).call{value: value, gas: 1000000}(
abi.encodeWithSignature("mint()")
);
require(success, "Failed to depsit");
}
//@notice ApproveAll required
function stake(uint256 tokenId) external {
require(token.ownerOf(tokenId) == msg.sender, "Not owned");
require(
token.isApprovedForAll(msg.sender, address(this)),
"Not approved"
);
staked[tokenId] = StakedData(msg.sender, block.timestamp);
// stakedCount.increment();
token.safeTransferFrom(msg.sender, address(this), tokenId);
emit Staked(tokenId, msg.sender);
}
//@notice Useful for transferring liquidated NFTs
function transfer(uint256 tokenId, address guy) external {
token.safeTransferFrom(address(this), guy, tokenId);
}
function _unstake(uint256 tokenId) internal {
staked[tokenId] = StakedData(address(0), 0);
token.approve(msg.sender, tokenId);
token.safeTransferFrom(address(this), msg.sender, tokenId);
emit Unstaked(tokenId, msg.sender);
}
//@notice Used to claim rewards and optionally unstake
//@notice If and_unstake==False, update stake timestamp
//@param tokenId Id of token to claim rewards for
//@param and_unstake Set to true if returning NFT to owner
//@dev Explain hash
function claimRewards(uint256 tokenId, bool and_unstake) internal {
require(staked[tokenId].user == msg.sender, "Unauthorized");
// TODO: Include arrays in calldata
uint256[] memory rewardAmounts_ = rewardAmounts; // change to callData later with UI
uint256[] memory rewardTimes_ = rewardTimes;
require(rewardAmounts_.length == rewardTimes_.length);
// require(
// keccak256(abi.encode(rewardAmounts_)) == rewardAmountsHash,
// "Invalid"
// );
// require(
// keccak256(abi.encode(rewardTimes_)) == rewardTimesHash,
// "Invalid"
// );
StakedData memory stakedData = staked[tokenId];
uint256 totalRewards = 0;
for (uint256 idx = 0; idx < rewardTimes_.length; idx++) {
if (rewardTimes_[idx] >= stakedData.timestamp) {
totalRewards += rewardAmounts_[idx];
}
}
if (and_unstake) {
_unstake(tokenId);
} else {
staked[tokenId] = StakedData(msg.sender, block.timestamp);
}
(bool success, ) = msg.sender.call{value: totalRewards}("");
require(success, "Failed transfer");
emit RewardsClaimed(tokenId, msg.sender, totalRewards);
}
//@notice Used by admin to set reward
//@param amount Represents amount of eth PER STAKED ADDRESS
//@dev RewardsAmounts and Times hashes updated
function addReward(uint256 amount) external {
rewardAmounts.push(amount);
rewardTimes.push(block.timestamp);
// rewardAmountsHash = keccak256(abi.encode(rewardAmounts));
// rewardTimesHash = keccak256(abi.encode(rewardTimes));
//emit RewardAdded
}
//@notice Used by admin to set ERC721 token
//@param Address of token
//@dev This should only be set once
//@dev RewardsAmounts and Times hashes updated
function setErc721Token(address token_) external {
require(token_ == address(0), "Already set");
token = IERC721(token_);
emit SetErc721Token(token_);
}
//@notice Used by admin to set Vault contract for use with deposits
//@param Address of vault
//@dev Becareful if changing this, redeem Vault deposits first
function setVaultToken(ICETH token_) external {
vaultToken = token_;
emit SetVaultToken(address(token_));
}
function borrow(uint256 tokenId, uint256 loanAmount) external {
require(token.ownerOf(tokenId) == msg.sender, "Not owned");
require(
token.isApprovedForAll(msg.sender, address(this)),
"Not approved"
);
loaned[tokenId] = LoanData(msg.sender, block.timestamp, loanAmount);
token.safeTransferFrom(msg.sender, address(this), tokenId);
// TODO: Apply interest up front
(bool success, ) = msg.sender.call{value: loanAmount}("");
require(success, "Failed transfer");
emit Loaned(tokenId, msg.sender, loanAmount);
}
function _release(uint256 tokenId) internal {
loaned[tokenId] = LoanData(address(0), 0, 0);
token.approve(msg.sender, tokenId);
token.safeTransferFrom(address(this), msg.sender, tokenId);
// emit event collateralreleased
}
function liquidate(uint256 tokenId) external {
// TODO: Needs access control
// TODO: some check about loan safety
loaned[tokenId] = LoanData(address(0), 0, 0);
// emit event liquidated
}
function repay(uint256 tokenId) external payable {
LoanData memory loanData = loaned[tokenId];
require(loanData.user == msg.sender, "Unauthorized");
require(msg.value <= loanData.owed, "overpayment");
if (msg.value == loanData.owed) {
_release(tokenId);
} else {
loaned[tokenId].owed = loanData.owed - msg.value;
}
// emit Repaid(tokenId, amount);
}
}
|
Required for any contract that wants to support safeTransfers
|
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external pure returns (bytes4) {
return this.onERC721Received.selector;
}
| 5,534,749 |
./partial_match/97/0xEaf3A01D0aEbcbF1fFB66F935B019e38a75aA9F9/sources/AshBar.sol
|
Safe cmbst transfer function, just in case if rounding error causes pool to not have enough CMBSTs.
|
function safeCmbstTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 cmbstBal = cmbst.balanceOf(address(this));
if (_amount > cmbstBal) {
cmbst.transfer(_to, cmbstBal);
cmbst.transfer(_to, _amount);
}
}
| 11,356,056 |
//
// This contract will validate that a twitter message url:
// 1) corresponds to a given username
// 2) containts an expected message (the user identifier)
//
import "accountProviderBase.sol";
contract Twitter is accountProviderBase {
Lookup lookup;
address owner;
modifier owneronly { if (msg.sender == owner) _ }
function setOwner(address addr) owneronly {
owner = addr;
}
function Twitter() {
owner = msg.sender;
}
function setLookup(address addr) owneronly {
lookup = Lookup(addr);
}
// map the expected identifier to an oraclize identifier
mapping (bytes32 => bytes32) expectedId;
// true if verification, otherwise scoring
mapping (bytes32 => bool) isVerification;
// callback from oraclize with the result, let the storage contract know
function __callback(bytes32 myid, string result, bytes proof) {
if (msg.sender != oraclize_cbAddress()) throw;
if (isVerification[myid])
processVerification(myid, result);
else
processScore(myid, result);
// clean up
delete expectedId[myid];
delete isVerification[myid];
}
function processScore(bytes32 myid, string result) internal {
uint followers = parseInt(result);
uint24 newScore = 1000000;
if (followers / 10000 == 0)
newScore = 100 * uint24(followers % 10000);
Storage(lookup.addrStorage()).updateScore(lookup.accountProvider_TWITTER(), expectedId[myid], newScore);
}
// start the scoring process and call oraclize with the URL
function score(bytes32 id, string userId) coupon("HackEtherCamp") {
bytes memory _userId = bytes(userId);
string memory head = "html(https://twitter.com/";
bytes memory _head = bytes(head);
string memory tail = ").xpath(//*[contains(@data-nav, 'followers')]/*[contains(@class, 'ProfileNav-value')]/text())";
bytes memory _tail = bytes(tail);
string memory query = new string(_head.length + _userId.length + _tail.length);
bytes memory _query = bytes(query);
uint i = 0;
for (uint j = 0; j < _head.length; j++)
_query[i++] = _head[j];
for (j = 0; j < _userId.length; j++)
_query[i++] = _userId[j];
for (j = 0; j < _tail.length; j++)
_query[i++] = _tail[j];
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
bytes32 oraclizeId = oraclize_query("URL", query);
expectedId[oraclizeId] = id;
isVerification[oraclizeId] = false;
}
function processVerification(bytes32 myid, string result) internal {
// this is basically a bytes32 to hexstring piece
string memory expected = iudexIdToString(expectedId[myid]);
bool asExpected = indexOf(result, expected) > -1;
Storage(lookup.addrStorage()).updateAccount(lookup.accountProvider_TWITTER(), expectedId[myid], asExpected, myid);
}
// ensure that the proofLocation corresponds to a twitter.com URL for the user `userId`
function verifyUrl(string userId, string proofLocation) internal returns (bool){
bytes memory _userId = bytes(userId);
string memory twitterPrefix = "://twitter.com/";
bytes memory _twitterPrefix = bytes(twitterPrefix);
string memory urlHead = new string(_twitterPrefix.length + _userId.length + 1);
bytes memory _urlHead = bytes(urlHead);
uint i = 0;
for (uint j = 0; j < _twitterPrefix.length; j++)
_urlHead[i++] = _twitterPrefix[j];
for (j = 0; j < _userId.length; j++)
_urlHead[i++] = _userId[j];
_urlHead[i++] = byte("/");
if (indexOf(proofLocation, string(_urlHead)) == -1)
return false;
return true;
}
// start the verification process and call oraclize with the URL
function verify(bytes32 id, string userId, string proofLocation) coupon("HackEtherCamp") {
// bytes32 oraclizeId = oraclize_query("html(https://twitter.com/oraclizeit/status/671316655893561344).xpath(//*[contains(@class, 'tweet-text')]/text())");
// check that userId matches the username in proofLocation
if (!verifyUrl(userId, proofLocation))
throw;
// build up the request string
string memory head = "html(";
bytes memory _head = bytes(head);
string memory tail = ").xpath(//*[contains(@class, 'tweet-text')]/text())";
bytes memory _tail = bytes(tail);
bytes memory _tweetUrl = bytes(proofLocation);
string memory query = new string(_head.length + _tail.length + _tweetUrl.length + 2);
bytes memory _query = bytes(query);
uint i = 0;
for (uint j = 0; j < _head.length; j++)
_query[i++] = _head[j];
for (j = 0; j < _tweetUrl.length; j++)
_query[i++] = _tweetUrl[j];
for (j = 0; j < _tail.length; j++)
_query[i++] = _tail[j];
_query[i++] = 0;
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
bytes32 oraclizeId = oraclize_query("URL", query);
expectedId[oraclizeId] = id;
isVerification[oraclizeId] = true;
}
}
|
callback from oraclize with the result, let the storage contract know clean up
|
function __callback(bytes32 myid, string result, bytes proof) {
if (msg.sender != oraclize_cbAddress()) throw;
if (isVerification[myid])
processVerification(myid, result);
else
processScore(myid, result);
delete expectedId[myid];
delete isVerification[myid];
}
| 1,036,526 |
./full_match/1/0xC1513C1b0B359Bc5aCF7b772100061217838768B/sources/artifacts/pickle-jar.sol
|
SPDX-License-Identifier: MIT
|
interface IController {
function jars(address) external view returns (address);
function rewards() external view returns (address);
function devfund() external view returns (address);
function treasury() external view returns (address);
function balanceOf(address) external view returns (uint256);
function withdraw(address, uint256) external;
function earn(address, uint256) external;
}
| 3,196,823 |
./full_match/80001/0xD484e26258Da26460910e36c8e81b7148804940c/sources/project_/contracts/market.sol
|
Ensure that the caller is the owner of the token and the token is listed in the market Remove the NFT from the market If needed, decrease the counter of the total market items
|
function removeNFTListing(uint256 tokenId) public {
require(marketItem[tokenId].seller == msg.sender, "You must be the owner of the NFT to remove it from the listing.");
require(marketItem[tokenId].sold == false, "This item is already sold.");
delete marketItem[tokenId];
_marketItemIds.decrement();
}
| 9,447,674 |
pragma solidity ^0.5.8;
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 main contract
/// @author Matter Labs
contract ZkSync is UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32
public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint256) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
function upgradeNoticePeriodStarted() external {}
/// @notice Notification that upgrade preparation status is activated
function upgradePreparationStarted() external {
upgradePreparationActive = true;
upgradePreparationActivationTime = now;
}
/// @notice Notification that upgrade canceled
function upgradeCanceled() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
function upgradeFinishes() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool) {
return !exodusMode;
}
/// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _governanceAddress The address of Governance contract
/// _verifierAddress The address of Verifier contract
/// _ // FIXME: remove _genesisAccAddress
/// _genesisRoot Genesis blocks (first block) root
function initialize(bytes calldata initializationParameters) external {
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
bytes32 _genesisRoot
) = abi.decode(initializationParameters, (address, address, bytes32));
verifier = Verifier(_verifierAddress);
governance = Governance(_governanceAddress);
blocks[0].stateRoot = _genesisRoot;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Sends tokens
/// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount
/// @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 withdrawERC20Guarded(
IERC20 _token,
address _to,
uint128 _amount,
uint128 _maxAmount
) external returns (uint128 withdrawnAmount) {
require(msg.sender == address(this), "wtg10"); // wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed)
uint256 balance_before = _token.balanceOf(address(this));
require(Utils.sendERC20(_token, _to, _amount), "wtg11"); // wtg11 - ERC20 transfer fails
uint256 balance_after = _token.balanceOf(address(this));
uint256 balance_diff = balance_before.sub(balance_after);
require(balance_diff <= _maxAmount, "wtg12"); // wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount
return SafeCast.toUint128(balance_diff);
}
/// @notice executes pending withdrawals
/// @param _n The number of withdrawals to complete starting from oldest
function completeWithdrawals(uint32 _n) external nonReentrant {
// TODO: when switched to multi validators model we need to add incentive mechanism to call complete.
uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals);
uint32 startIndex = firstPendingWithdrawalIndex;
numberOfPendingWithdrawals -= toProcess;
firstPendingWithdrawalIndex += toProcess;
for (uint32 i = startIndex; i < startIndex + toProcess; ++i) {
uint16 tokenId = pendingWithdrawals[i].tokenId;
address to = pendingWithdrawals[i].to;
// send fails are ignored hence there is always a direct way to withdraw.
delete pendingWithdrawals[i];
bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId);
uint128 amount = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
// amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20
if (amount != 0) {
balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw -= amount;
bool sent = false;
if (tokenId == 0) {
address payable toPayable = address(uint160(to));
sent = Utils.sendETHNoRevert(toPayable, amount);
} else {
address tokenAddr = governance.tokenAddresses(tokenId);
// we can just check that call not reverts because it wants to withdraw all amount
(sent, ) = address(this).call.gas(
ERC20_WITHDRAWAL_GAS_LIMIT
)(
abi.encodeWithSignature(
"withdrawERC20Guarded(address,address,uint128,uint128)",
tokenAddr,
to,
amount,
amount
)
);
}
if (!sent) {
balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw += amount;
}
}
}
if (toProcess > 0) {
emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess);
}
}
/// @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)
external
nonReentrant
{
require(exodusMode, "coe01"); // exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "coe02"); // no deposits to process
for (
uint64 id = firstPriorityRequestId;
id < firstPriorityRequestId + toProcess;
id++
) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
Operations.Deposit memory op = Operations.readDepositPubdata(
priorityRequests[id].pubData
);
bytes22 packedBalanceKey = packAddressAndTokenId(
op.owner,
op.tokenId
);
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op
.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
/// @param _franklinAddr The receiver Layer 2 address
function depositETH(address _franklinAddr) external payable nonReentrant {
requireActive();
registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr);
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender
/// @param _amount Ether amount to withdraw
function withdrawETH(uint128 _amount) external nonReentrant {
registerWithdrawal(0, _amount, msg.sender);
(bool success, ) = msg.sender.call.value(_amount)("");
require(success, "fwe11"); // ETH withdraw failed
}
/// @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 _franklinAddr Receiver Layer 2 address
function depositERC20(
IERC20 _token,
uint104 _amount,
address _franklinAddr
) external nonReentrant {
requireActive();
// Get token id by its address
uint16 tokenId = governance.validateTokenAddress(address(_token));
uint256 balance_before = _token.balanceOf(address(this));
require(
Utils.transferFromERC20(
_token,
msg.sender,
address(this),
SafeCast.toUint128(_amount)
),
"fd012"
); // token transfer failed deposit
uint256 balance_after = _token.balanceOf(address(this));
uint128 deposit_amount = SafeCast.toUint128(
balance_after.sub(balance_before)
);
registerDeposit(tokenId, deposit_amount, _franklinAddr);
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender
/// @param _token Token address
/// @param _amount amount to withdraw
function withdrawERC20(IERC20 _token, uint128 _amount)
external
nonReentrant
{
uint16 tokenId = governance.validateTokenAddress(address(_token));
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(
_token,
msg.sender,
_amount,
balance
);
registerWithdrawal(tokenId, withdrawnAmount, msg.sender);
}
/// @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 fullExit(uint32 _accountId, address _token) external nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "fee11");
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
});
bytes memory pubData = Operations.writeFullExitPubdata(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);
balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff;
}
/// @notice Commit block - collect onchain operations, create its commitment, emit BlockCommit event
/// @param _blockNumber Block number
/// @param _feeAccount Account to collect fees
/// @param _newBlockInfo New state of the block. (first element is the account tree root hash, rest of the array is reserved for the future)
/// @param _publicData Operations pubdata
/// @param _ethWitness Data passed to ethereum outside pubdata of the circuit.
/// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation.
function commitBlock(
uint32 _blockNumber,
uint32 _feeAccount,
bytes32[] calldata _newBlockInfo,
bytes calldata _publicData,
bytes calldata _ethWitness,
uint32[] calldata _ethWitnessSizes
) external nonReentrant {
requireActive();
require(_blockNumber == totalBlocksCommitted + 1, "fck11"); // only commit next block
governance.requireActiveValidator(msg.sender);
require(_newBlockInfo.length == 1, "fck13"); // This version of the contract expects only account tree root hash
bytes memory publicData = _publicData;
// Unpack onchain operations and store them.
// Get priority operations number for this block.
uint64 prevTotalCommittedPriorityRequests
= totalCommittedPriorityRequests;
bytes32 withdrawalsDataHash = collectOnchainOps(
_blockNumber,
publicData,
_ethWitness,
_ethWitnessSizes
);
uint64 nPriorityRequestProcessed = totalCommittedPriorityRequests -
prevTotalCommittedPriorityRequests;
createCommittedBlock(
_blockNumber,
_feeAccount,
_newBlockInfo[0],
publicData,
withdrawalsDataHash,
nPriorityRequestProcessed
);
totalBlocksCommitted++;
emit BlockCommit(_blockNumber);
}
/// @notice Block verification.
/// @notice Verify proof -> process onchain withdrawals (accrue balances from withdrawals) -> remove priority requests
/// @param _blockNumber Block number
/// @param _proof Block proof
/// @param _withdrawalsData Block withdrawals data
function verifyBlock(
uint32 _blockNumber,
uint256[] calldata _proof,
bytes calldata _withdrawalsData
) external nonReentrant {
requireActive();
require(_blockNumber == totalBlocksVerified + 1, "fvk11"); // only verify next block
governance.requireActiveValidator(msg.sender);
require(
verifier.verifyBlockProof(
_proof,
blocks[_blockNumber].commitment,
blocks[_blockNumber].chunks
),
"fvk13"
); // proof verification failed
processOnchainWithdrawals(
_withdrawalsData,
blocks[_blockNumber].withdrawalsDataHash
);
deleteRequests(blocks[_blockNumber].priorityOperations);
totalBlocksVerified += 1;
emit BlockVerification(_blockNumber);
}
/// @notice Reverts unverified blocks
/// @param _maxBlocksToRevert the maximum number blocks that will be reverted (use if can't revert all blocks because of gas limit).
function revertBlocks(uint32 _maxBlocksToRevert) external nonReentrant {
require(isBlockCommitmentExpired(), "rbs11"); // trying to revert non-expired blocks.
governance.requireActiveValidator(msg.sender);
uint32 blocksCommited = totalBlocksCommitted;
uint32 blocksToRevert = Utils.minU32(
_maxBlocksToRevert,
blocksCommited - totalBlocksVerified
);
uint64 revertedPriorityRequests = 0;
for (
uint32 i = totalBlocksCommitted - blocksToRevert + 1;
i <= blocksCommited;
i++
) {
Block memory revertedBlock = blocks[i];
require(revertedBlock.committedAtBlock > 0, "frk11"); // block not found
revertedPriorityRequests += revertedBlock.priorityOperations;
delete blocks[i];
}
blocksCommited -= blocksToRevert;
totalBlocksCommitted -= blocksToRevert;
totalCommittedPriorityRequests -= revertedPriorityRequests;
emit BlocksRevert(totalBlocksVerified, blocksCommited);
}
/// @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 triggerExodusIfNeeded() external 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 Franklin to root chain in case of exodus mode. User must provide proof that he owns funds
/// @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 exit(
uint32 _accountId,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external nonReentrant {
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, _tokenId);
require(exodusMode, "fet11"); // must be in exodus mode
require(!exited[_accountId][_tokenId], "fet12"); // already exited
require(
verifier.verifyExitProof(
blocks[totalBlocksVerified].stateRoot,
_accountId,
msg.sender,
_tokenId,
_amount,
_proof
),
"fet13"
); // verification failed
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.add(
_amount
);
exited[_accountId][_tokenId] = true;
}
function setAuthPubkeyHash(bytes calldata _pubkey_hash, uint32 _nonce)
external
nonReentrant
{
require(_pubkey_hash.length == PUBKEY_HASH_BYTES, "ahf10"); // PubKeyHash should be 20 bytes.
require(authFacts[msg.sender][_nonce] == bytes32(0), "ahf11"); // auth fact for nonce should be empty
authFacts[msg.sender][_nonce] = keccak256(_pubkey_hash);
emit FactAuth(msg.sender, _nonce, _pubkey_hash);
}
/// @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.writeDepositPubdata(op);
addPriorityRequest(Operations.OpType.Deposit, pubData);
emit OnchainDeposit(msg.sender, _tokenId, _amount, _owner);
}
/// @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 = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(
_amount
);
emit OnchainWithdrawal(_to, _token, _amount);
}
/// @notice Store committed block structure to the storage.
/// @param _nCommittedPriorityRequests - number of priority requests in block
function createCommittedBlock(
uint32 _blockNumber,
uint32 _feeAccount,
bytes32 _newRoot,
bytes memory _publicData,
bytes32 _withdrawalDataHash,
uint64 _nCommittedPriorityRequests
) internal {
require(_publicData.length % CHUNK_BYTES == 0, "cbb10"); // Public data size is not multiple of CHUNK_BYTES
uint32 blockChunks = uint32(_publicData.length / CHUNK_BYTES);
require(verifier.isBlockSizeSupported(blockChunks), "ccb11");
// Create block commitment for verification proof
bytes32 commitment = createBlockCommitment(
_blockNumber,
_feeAccount,
blocks[_blockNumber - 1].stateRoot,
_newRoot,
_publicData
);
blocks[_blockNumber] = Block(
uint32(block.number), // committed at
_nCommittedPriorityRequests, // number of priority onchain ops in block
blockChunks,
_withdrawalDataHash, // hash of onchain withdrawals data (will be used during checking block withdrawal data in verifyBlock function)
commitment, // blocks' commitment
_newRoot // new root
);
}
function emitDepositCommitEvent(
uint32 _blockNumber,
Operations.Deposit memory depositData
) internal {
emit DepositCommit(
_blockNumber,
depositData.accountId,
depositData.owner,
depositData.tokenId,
depositData.amount
);
}
function emitFullExitCommitEvent(
uint32 _blockNumber,
Operations.FullExit memory fullExitData
) internal {
emit FullExitCommit(
_blockNumber,
fullExitData.accountId,
fullExitData.owner,
fullExitData.tokenId,
fullExitData.amount
);
}
/// @notice Gets operations packed in bytes array. Unpacks it and stores onchain operations.
/// @param _blockNumber Franklin block number
/// @param _publicData Operations packed in bytes array
/// @param _ethWitness Eth witness that was posted with commit
/// @param _ethWitnessSizes Amount of eth witness bytes for the corresponding operation.
/// Priority operations must be committed in the same order as they are in the priority queue.
function collectOnchainOps(
uint32 _blockNumber,
bytes memory _publicData,
bytes memory _ethWitness,
uint32[] memory _ethWitnessSizes
) internal returns (bytes32 withdrawalsDataHash) {
require(_publicData.length % CHUNK_BYTES == 0, "fcs11"); // pubdata length must be a multiple of CHUNK_BYTES
uint64 currentPriorityRequestId = firstPriorityRequestId +
totalCommittedPriorityRequests;
uint256 pubDataPtr = 0;
uint256 pubDataStartPtr = 0;
uint256 pubDataEndPtr = 0;
assembly {
pubDataStartPtr := add(_publicData, 0x20)
}
pubDataPtr = pubDataStartPtr;
pubDataEndPtr = pubDataStartPtr + _publicData.length;
uint64 ethWitnessOffset = 0;
uint16 processedOperationsRequiringEthWitness = 0;
withdrawalsDataHash = EMPTY_STRING_KECCAK;
while (pubDataPtr < pubDataEndPtr) {
Operations.OpType opType;
// read operation type from public data (the first byte per each operation)
assembly {
opType := shr(0xf8, mload(pubDataPtr))
}
// cheap operations processing
if (opType == Operations.OpType.Transfer) {
pubDataPtr += TRANSFER_BYTES;
} else if (opType == Operations.OpType.Noop) {
pubDataPtr += NOOP_BYTES;
} else if (opType == Operations.OpType.TransferToNew) {
pubDataPtr += TRANSFER_TO_NEW_BYTES;
} else {
// other operations processing
// calculation of public data offset
uint256 pubdataOffset = pubDataPtr - pubDataStartPtr;
if (opType == Operations.OpType.Deposit) {
bytes memory pubData = Bytes.slice(
_publicData,
pubdataOffset + 1,
DEPOSIT_BYTES - 1
);
Operations.Deposit memory depositData = Operations
.readDepositPubdata(pubData);
emitDepositCommitEvent(_blockNumber, depositData);
OnchainOperation memory onchainOp = OnchainOperation(
Operations.OpType.Deposit,
pubData
);
commitNextPriorityOperation(
onchainOp,
currentPriorityRequestId
);
currentPriorityRequestId++;
pubDataPtr += DEPOSIT_BYTES;
} else if (opType == Operations.OpType.PartialExit) {
Operations.PartialExit memory data = Operations
.readPartialExitPubdata(_publicData, pubdataOffset + 1);
bool addToPendingWithdrawalsQueue = true;
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
data.owner,
data.tokenId,
data.amount
)
);
pubDataPtr += PARTIAL_EXIT_BYTES;
} else if (opType == Operations.OpType.ForcedExit) {
Operations.ForcedExit memory data = Operations
.readForcedExitPubdata(_publicData, pubdataOffset + 1);
bool addToPendingWithdrawalsQueue = true;
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
data.target,
data.tokenId,
data.amount
)
);
pubDataPtr += FORCED_EXIT_BYTES;
} else if (opType == Operations.OpType.FullExit) {
bytes memory pubData = Bytes.slice(
_publicData,
pubdataOffset + 1,
FULL_EXIT_BYTES - 1
);
Operations.FullExit memory fullExitData = Operations
.readFullExitPubdata(pubData);
emitFullExitCommitEvent(_blockNumber, fullExitData);
bool addToPendingWithdrawalsQueue = false;
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
fullExitData.owner,
fullExitData.tokenId,
fullExitData.amount
)
);
OnchainOperation memory onchainOp = OnchainOperation(
Operations.OpType.FullExit,
pubData
);
commitNextPriorityOperation(
onchainOp,
currentPriorityRequestId
);
currentPriorityRequestId++;
pubDataPtr += FULL_EXIT_BYTES;
} else if (opType == Operations.OpType.ChangePubKey) {
require(
processedOperationsRequiringEthWitness <
_ethWitnessSizes.length,
"fcs13"
); // eth witness data malformed
Operations.ChangePubKey memory op = Operations
.readChangePubKeyPubdata(
_publicData,
pubdataOffset + 1
);
if (
_ethWitnessSizes[processedOperationsRequiringEthWitness] !=
0
) {
bytes memory currentEthWitness = Bytes.slice(
_ethWitness,
ethWitnessOffset,
_ethWitnessSizes[processedOperationsRequiringEthWitness]
);
bool valid = verifyChangePubkeySignature(
currentEthWitness,
op.pubKeyHash,
op.nonce,
op.owner,
op.accountId
);
require(valid, "fpp15"); // failed to verify change pubkey hash signature
} else {
bool valid = authFacts[op.owner][op.nonce] ==
keccak256(abi.encodePacked(op.pubKeyHash));
require(valid, "fpp16"); // new pub key hash is not authenticated properly
}
ethWitnessOffset += _ethWitnessSizes[processedOperationsRequiringEthWitness];
processedOperationsRequiringEthWitness++;
pubDataPtr += CHANGE_PUBKEY_BYTES;
} else {
revert("fpp14"); // unsupported op
}
}
}
require(pubDataPtr == pubDataEndPtr, "fcs12"); // last chunk exceeds pubdata
require(ethWitnessOffset == _ethWitness.length, "fcs14"); // _ethWitness was not used completely
require(
processedOperationsRequiringEthWitness == _ethWitnessSizes.length,
"fcs15"
); // _ethWitnessSizes was not used completely
require(
currentPriorityRequestId <=
firstPriorityRequestId + totalOpenPriorityRequests,
"fcs16"
); // fcs16 - excess priority requests in pubdata
totalCommittedPriorityRequests =
currentPriorityRequestId -
firstPriorityRequestId;
}
/// @notice Checks that signature is valid for pubkey change message
/// @param _signature Signature
/// @param _newPkHash New pubkey hash
/// @param _nonce Nonce used for message
/// @param _ethAddress Account's ethereum address
/// @param _accountId Id of zkSync account
function verifyChangePubkeySignature(
bytes memory _signature,
bytes20 _newPkHash,
uint32 _nonce,
address _ethAddress,
uint32 _accountId
) internal pure returns (bool) {
bytes memory signedMessage = abi.encodePacked(
"\x19Ethereum Signed Message:\n152",
"Register zkSync pubkey:\n\n",
Bytes.bytesToHexASCIIBytes(abi.encodePacked(_newPkHash)),
"\n",
"nonce: 0x",
Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_nonce)),
"\n",
"account id: 0x",
Bytes.bytesToHexASCIIBytes(Bytes.toBytesFromUInt32(_accountId)),
"\n\n",
"Only sign this message for a trusted client!"
);
address recoveredAddress = Utils.recoverAddressFromEthSignature(
_signature,
signedMessage
);
return recoveredAddress == _ethAddress;
}
/// @notice Creates block commitment from its data
/// @param _blockNumber Block number
/// @param _feeAccount Account to collect fees
/// @param _oldRoot Old tree root
/// @param _newRoot New tree root
/// @param _publicData Operations pubdata
/// @return block commitment
function createBlockCommitment(
uint32 _blockNumber,
uint32 _feeAccount,
bytes32 _oldRoot,
bytes32 _newRoot,
bytes memory _publicData
) internal view returns (bytes32 commitment) {
bytes32 hash = sha256(
abi.encodePacked(uint256(_blockNumber), uint256(_feeAccount))
);
hash = sha256(abi.encodePacked(hash, uint256(_oldRoot)));
hash = sha256(abi.encodePacked(hash, uint256(_newRoot)));
/// 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(_publicData)
mstore(_publicData, hash)
// staticcall to the sha256 precompile at address 0x2
let success := staticcall(
gas,
0x2,
_publicData,
add(pubDataLen, 0x20),
hashResult,
0x20
)
mstore(_publicData, pubDataLen)
// Use "invalid" to make gas estimation work
switch success
case 0 {
invalid()
}
commitment := mload(hashResult)
}
}
/// @notice Checks that operation is same as operation in priority queue
/// @param _onchainOp The operation
/// @param _priorityRequestId Operation's id in priority queue
function commitNextPriorityOperation(
OnchainOperation memory _onchainOp,
uint64 _priorityRequestId
) internal view {
Operations.OpType priorReqType = priorityRequests[_priorityRequestId]
.opType;
bytes memory priorReqPubdata = priorityRequests[_priorityRequestId]
.pubData;
require(priorReqType == _onchainOp.opType, "nvp12"); // incorrect priority op type
if (_onchainOp.opType == Operations.OpType.Deposit) {
require(
Operations.depositPubdataMatch(
priorReqPubdata,
_onchainOp.pubData
),
"vnp13"
);
} else if (_onchainOp.opType == Operations.OpType.FullExit) {
require(
Operations.fullExitPubdataMatch(
priorReqPubdata,
_onchainOp.pubData
),
"vnp14"
);
} else {
revert("vnp15"); // invalid or non-priority operation
}
}
/// @notice Processes onchain withdrawals. Full exit withdrawals will not be added to pending withdrawals queue
/// @dev NOTICE: must process only withdrawals which hash matches with expectedWithdrawalsDataHash.
/// @param withdrawalsData Withdrawals data
/// @param expectedWithdrawalsDataHash Expected withdrawals data hash
function processOnchainWithdrawals(
bytes memory withdrawalsData,
bytes32 expectedWithdrawalsDataHash
) internal {
require(
withdrawalsData.length % ONCHAIN_WITHDRAWAL_BYTES == 0,
"pow11"
); // pow11 - withdrawalData length is not multiple of ONCHAIN_WITHDRAWAL_BYTES
bytes32 withdrawalsDataHash = EMPTY_STRING_KECCAK;
uint256 offset = 0;
uint32 localNumberOfPendingWithdrawals = numberOfPendingWithdrawals;
while (offset < withdrawalsData.length) {
(
bool addToPendingWithdrawalsQueue,
address _to,
uint16 _tokenId,
uint128 _amount
) = Operations.readWithdrawalData(withdrawalsData, offset);
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey]
.balanceToWithdraw;
// after this all writes to this slot will cost 5k gas
balancesToWithdraw[packedBalanceKey] = BalanceToWithdraw({
balanceToWithdraw: balance.add(_amount),
gasReserveValue: 0xff
});
if (addToPendingWithdrawalsQueue) {
pendingWithdrawals[firstPendingWithdrawalIndex +
localNumberOfPendingWithdrawals] = PendingWithdrawal(
_to,
_tokenId
);
localNumberOfPendingWithdrawals++;
}
withdrawalsDataHash = keccak256(
abi.encode(
withdrawalsDataHash,
addToPendingWithdrawalsQueue,
_to,
_tokenId,
_amount
)
);
offset += ONCHAIN_WITHDRAWAL_BYTES;
}
require(withdrawalsDataHash == expectedWithdrawalsDataHash, "pow12"); // pow12 - withdrawals data hash not matches with expected value
if (numberOfPendingWithdrawals != localNumberOfPendingWithdrawals) {
emit PendingWithdrawalsAdd(
firstPendingWithdrawalIndex + numberOfPendingWithdrawals,
firstPendingWithdrawalIndex + localNumberOfPendingWithdrawals
);
}
numberOfPendingWithdrawals = localNumberOfPendingWithdrawals;
}
/// @notice Checks whether oldest unverified block has expired
/// @return bool flag that indicates whether oldest unverified block has expired
function isBlockCommitmentExpired() internal view returns (bool) {
return (totalBlocksCommitted > totalBlocksVerified &&
blocks[totalBlocksVerified + 1].committedAtBlock > 0 &&
block.number >
blocks[totalBlocksVerified + 1].committedAtBlock +
EXPECT_VERIFICATION_IN);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "fre11"); // exodus mode activated
}
// 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
uint256 expirationBlock = block.number + PRIORITY_EXPIRATION;
uint64 nextPriorityRequestId = firstPriorityRequestId +
totalOpenPriorityRequests;
priorityRequests[nextPriorityRequestId] = PriorityOperation({
opType: _opType,
pubData: _pubData,
expirationBlock: expirationBlock
});
emit NewPriorityRequest(
msg.sender,
nextPriorityRequestId,
_opType,
_pubData,
expirationBlock
);
totalOpenPriorityRequests++;
}
/// @notice Deletes processed priority requests
/// @param _number The number of requests
function deleteRequests(uint64 _number) internal {
require(_number <= totalOpenPriorityRequests, "pcs21"); // number is higher than total priority requests number
uint64 numberOfRequestsToClear = Utils.minU64(
_number,
MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY
);
uint64 startIndex = firstPriorityRequestId;
for (
uint64 i = startIndex;
i < startIndex + numberOfRequestsToClear;
i++
) {
delete priorityRequests[i];
}
totalOpenPriorityRequests -= _number;
firstPriorityRequestId += _number;
totalCommittedPriorityRequests -= _number;
}
}
|
Sends tokens NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount _token Token address _to Address of recipient _amount Amount of tokens to transfer _maxAmount Maximum possible amount of tokens to transfer to this account
|
function withdrawERC20Guarded(
IERC20 _token,
address _to,
uint128 _amount,
uint128 _maxAmount
) external returns (uint128 withdrawnAmount) {
uint256 balance_before = _token.balanceOf(address(this));
uint256 balance_after = _token.balanceOf(address(this));
uint256 balance_diff = balance_before.sub(balance_after);
return SafeCast.toUint128(balance_diff);
}
| 5,479,349 |
./full_match/4/0xD8170e06c26f1aC7C3e7458bab64daB1F749Bbf6/sources/contracts/metaships/metaships.sol
|
Allocate rewards from previous week multipliers blockDif = blockDif.sub(previousHarvestWeekOwedBlocks); EFFICIENCY ATTRIBUTE MULTIPLIER 11520m = 24h x 4 Max of 20% bonus MTL if ship has not harvested in last 48 hours. Ship's efficiency decreases delay needed for max bonus MTL by up to 10x (4.8 hours at 99) META ATTRIBUTE MULTIPLIER _metalToken.setLottery(SafeMath.sub(_metalToken.getLottery(), lotteryBonus.mul(1018)));
|
function getPendingMetal(uint256 id, uint256 metalBlockMultiplier, uint256 blockNumber, uint256 currentWeek) private view returns (uint256){
uint256 blockDif = blockNumber.sub(ships[id].harvestBlock);
uint previousHarvestBlock = ships[id].harvestBlock;
uint previousHarvestWeek = getWeekFromBlock(previousHarvestBlock);
uint256 metalCollected;
while(previousHarvestWeek < currentWeek){
uint256 previousHarvestWeekEndBlock = getWeekBlockStart(previousHarvestWeek+1);
uint256 previousHarvestWeekOwedBlocks = previousHarvestWeekEndBlock.sub(previousHarvestBlock);
metalCollected = metalCollected.add(previousHarvestWeekOwedBlocks.mul(getMetalBlockRewardMultiplier(previousHarvestWeek)));
previousHarvestWeek = previousHarvestWeek.add(1);
previousHarvestBlock = getWeekBlockStart(previousHarvestWeek);
}
.mul(getShipBaseMetalPerBlock(id))
.mul(getShipRarityBaseMetalPerBlockMultiplier(id))
.mul(metalBlockMultiplier));
if(blockDif >= ONE_MINUTE_BLOCKS){
uint256 mins = blockDif.div(ONE_MINUTE_BLOCKS);
if(mins > 1){
uint256 x = mins.mul(getShipDelayedHarvestMultiplier(id));
if(x > 11520) x = SafeMath.sub(11520,1);
uint256 efficiencyBonusMetal = SafeMath.sub(11520,x);
if(metalCollected > efficiencyBonusMetal){
metalCollected = metalCollected.add(metalCollected.div(efficiencyBonusMetal));
}
}
}
if(_metalToken.getLotteryNoDecimals() > 10000){
metalCollected = metalCollected.add(getPendingLotteryMetal(id));
}
return metalCollected;
}
| 760,026 |
pragma solidity ^0.4.21;
// File: contracts/Oracle/DSAuth.sol
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
// File: contracts/Oracle/DSMath.sol
contract DSMath {
/*
standard uint256 functions
*/
function add(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) constant internal returns (uint256 z) {
assert((z = x * y) >= x);
}
function div(uint256 x, uint256 y) constant internal returns (uint256 z) {
z = x / y;
}
function min(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) constant internal returns (uint256 z) {
return x >= y ? x : y;
}
/*
uint128 functions (h is for half)
*/
function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x + y) >= x);
}
function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x - y) <= x);
}
function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
assert((z = x * y) >= x);
}
function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = x / y;
}
function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x <= y ? x : y;
}
function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) {
return x >= y ? x : y;
}
/*
int256 functions
*/
function imin(int256 x, int256 y) constant internal returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) constant internal returns (int256 z) {
return x >= y ? x : y;
}
/*
WAD math
*/
uint128 constant WAD = 10 ** 18;
function wadd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function wsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + WAD / 2) / WAD);
}
function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * WAD + y / 2) / y);
}
function wmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function wmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
/*
RAY math
*/
uint128 constant RAY = 10 ** 27;
function radd(uint128 x, uint128 y) constant internal returns (uint128) {
return hadd(x, y);
}
function rsub(uint128 x, uint128 y) constant internal returns (uint128) {
return hsub(x, y);
}
function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * y + RAY / 2) / RAY);
}
function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) {
z = cast((uint256(x) * RAY + y / 2) / y);
}
function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) {
// 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].
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);
}
}
}
function rmin(uint128 x, uint128 y) constant internal returns (uint128) {
return hmin(x, y);
}
function rmax(uint128 x, uint128 y) constant internal returns (uint128) {
return hmax(x, y);
}
function cast(uint256 x) constant internal returns (uint128 z) {
assert((z = uint128(x)) == x);
}
}
// File: contracts/Oracle/DSNote.sol
contract DSNote {
event LogNote(
bytes4 indexed sig,
address indexed guy,
bytes32 indexed foo,
bytes32 indexed bar,
uint wad,
bytes fax
) anonymous;
modifier note {
bytes32 foo;
bytes32 bar;
assembly {
foo := calldataload(4)
bar := calldataload(36)
}
LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data);
_;
}
}
// File: contracts/Oracle/DSThing.sol
contract DSThing is DSAuth, DSNote, DSMath {
}
// File: contracts/Oracle/DSValue.sol
contract DSValue is DSThing {
bool has;
bytes32 val;
function peek() constant returns (bytes32, bool) {
return (val,has);
}
function read() constant returns (bytes32) {
var (wut, has) = peek();
assert(has);
return wut;
}
function poke(bytes32 wut) note auth {
val = wut;
has = true;
}
function void() note auth { // unset the value
has = false;
}
}
// File: contracts/Oracle/Medianizer.sol
contract Medianizer is DSValue {
mapping (bytes12 => address) public values;
mapping (address => bytes12) public indexes;
bytes12 public next = 0x1;
uint96 public min = 0x1;
function set(address wat) auth {
bytes12 nextId = bytes12(uint96(next) + 1);
assert(nextId != 0x0);
set(next, wat);
next = nextId;
}
function set(bytes12 pos, address wat) note auth {
if (pos == 0x0) throw;
if (wat != 0 && indexes[wat] != 0) throw;
indexes[values[pos]] = 0; // Making sure to remove a possible existing address in that position
if (wat != 0) {
indexes[wat] = pos;
}
values[pos] = wat;
}
function setMin(uint96 min_) note auth {
if (min_ == 0x0) throw;
min = min_;
}
function setNext(bytes12 next_) note auth {
if (next_ == 0x0) throw;
next = next_;
}
function unset(bytes12 pos) {
set(pos, 0);
}
function unset(address wat) {
set(indexes[wat], 0);
}
function poke() {
poke(0);
}
function poke(bytes32) note {
(val, has) = compute();
}
function compute() constant returns (bytes32, bool) {
bytes32[] memory wuts = new bytes32[](uint96(next) - 1);
uint96 ctr = 0;
for (uint96 i = 1; i < uint96(next); i++) {
if (values[bytes12(i)] != 0) {
var (wut, wuz) = DSValue(values[bytes12(i)]).peek();
if (wuz) {
if (ctr == 0 || wut >= wuts[ctr - 1]) {
wuts[ctr] = wut;
} else {
uint96 j = 0;
while (wut >= wuts[j]) {
j++;
}
for (uint96 k = ctr; k > j; k--) {
wuts[k] = wuts[k - 1];
}
wuts[j] = wut;
}
ctr++;
}
}
}
if (ctr < min) return (val, false);
bytes32 value;
if (ctr % 2 == 0) {
uint128 val1 = uint128(wuts[(ctr / 2) - 1]);
uint128 val2 = uint128(wuts[ctr / 2]);
value = bytes32(wdiv(hadd(val1, val2), 2 ether));
} else {
value = wuts[(ctr - 1) / 2];
}
return (value, true);
}
}
// File: contracts/Oracle/PriceFeed.sol
/// price-feed.sol
// Copyright (C) 2017 DappHub, LLC
// Licensed under the Apache License, Version 2.0 (the "License").
// You may not use this file except in compliance with the License.
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied).
contract PriceFeed is DSThing {
uint128 val;
uint32 public zzz;
function peek() public view
returns (bytes32, bool)
{
return (bytes32(val), now < zzz);
}
function read() public view
returns (bytes32)
{
assert(now < zzz);
return bytes32(val);
}
function post(uint128 val_, uint32 zzz_, address med_) public note auth
{
val = val_;
zzz = zzz_;
bool ret = med_.call(bytes4(keccak256("poke()")));
ret;
}
function void() public note auth
{
zzz = 0;
}
}
// File: contracts/Oracle/PriceOracleInterface.sol
/*
This contract is the interface between the MakerDAO priceFeed and our DX platform.
*/
contract PriceOracleInterface {
address public priceFeedSource;
address public owner;
bool public emergencyMode;
event NonValidPriceFeed(address priceFeedSource);
// Modifiers
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/// @dev constructor of the contract
/// @param _priceFeedSource address of price Feed Source -> should be maker feeds Medianizer contract
function PriceOracleInterface(
address _owner,
address _priceFeedSource
)
public
{
owner = _owner;
priceFeedSource = _priceFeedSource;
}
/// @dev gives the owner the possibility to put the Interface into an emergencyMode, which will
/// output always a price of 600 USD. This gives everyone time to set up a new pricefeed.
function raiseEmergency(bool _emergencyMode)
public
onlyOwner()
{
emergencyMode = _emergencyMode;
}
/// @dev updates the priceFeedSource
/// @param _owner address of owner
function updateCurator(
address _owner
)
public
onlyOwner()
{
owner = _owner;
}
/// @dev returns the USDETH price, ie gets the USD price from Maker feed with 18 digits, but last 18 digits are cut off
function getUSDETHPrice()
public
returns (uint256)
{
// if the contract is in the emergencyMode, because there is an issue with the oracle, we will simply return a price of 600 USD
if(emergencyMode){
return 600;
}
bytes32 price;
bool valid=true;
(price, valid) = Medianizer(priceFeedSource).peek();
if (!valid) {
NonValidPriceFeed(priceFeedSource);
}
// ensuring that there is no underflow or overflow possible,
// even if the price is compromised
uint priceUint = uint256(price)/(1 ether);
if (priceUint == 0) return 1;
if (priceUint > 1000000) return 1000000;
return priceUint;
}
}
// File: @gnosis.pm/util-contracts/contracts/Math.sol
/// @title Math library - Allows calculation of logarithmic and exponential functions
/// @author Alan Lu - <[email protected]>
/// @author Stefan George - <[email protected]>
library Math {
/*
* Constants
*/
// This is equal to 1 in our calculations
uint public constant ONE = 0x10000000000000000;
uint public constant LN2 = 0xb17217f7d1cf79ac;
uint public constant LOG2_E = 0x171547652b82fe177;
/*
* Public functions
*/
/// @dev Returns natural exponential function value of given x
/// @param x x
/// @return e**x
function exp(int x)
public
pure
returns (uint)
{
// revert if x is > MAX_POWER, where
// MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE))
require(x <= 2454971259878909886679);
// return 0 if exp(x) is tiny, using
// MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE))
if (x < -818323753292969962227)
return 0;
// Transform so that e^x -> 2^x
x = x * int(ONE) / int(LN2);
// 2^x = 2^whole(x) * 2^frac(x)
// ^^^^^^^^^^ is a bit shift
// so Taylor expand on z = frac(x)
int shift;
uint z;
if (x >= 0) {
shift = x / int(ONE);
z = uint(x % int(ONE));
}
else {
shift = x / int(ONE) - 1;
z = ONE - uint(-x % int(ONE));
}
// 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ...
//
// Can generate the z coefficients using mpmath and the following lines
// >>> from mpmath import mp
// >>> mp.dps = 100
// >>> ONE = 0x10000000000000000
// >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7)))
// 0xb17217f7d1cf79ab
// 0x3d7f7bff058b1d50
// 0xe35846b82505fc5
// 0x276556df749cee5
// 0x5761ff9e299cc4
// 0xa184897c363c3
uint zpow = z;
uint result = ONE;
result += 0xb17217f7d1cf79ab * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x3d7f7bff058b1d50 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe35846b82505fc5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x276556df749cee5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x5761ff9e299cc4 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xa184897c363c3 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xffe5fe2c4586 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x162c0223a5c8 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1b5253d395e * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e4cf5158b * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e8cac735 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1c3bd650 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1816193 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x131496 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe1b7 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x9c7 * zpow / ONE;
if (shift >= 0) {
if (result >> (256-shift) > 0)
return (2**256-1);
return result << shift;
}
else
return result >> (-shift);
}
/// @dev Returns natural logarithm value of given x
/// @param x x
/// @return ln(x)
function ln(uint x)
public
pure
returns (int)
{
require(x > 0);
// binary search for floor(log2(x))
int ilog2 = floorLog2(x);
int z;
if (ilog2 < 0)
z = int(x << uint(-ilog2));
else
z = int(x >> uint(ilog2));
// z = x * 2^-⌊log₂x⌋
// so 1 <= z < 2
// and ln z = ln x - ⌊log₂x⌋/log₂e
// so just compute ln z using artanh series
// and calculate ln x from that
int term = (z - int(ONE)) * int(ONE) / (z + int(ONE));
int halflnz = term;
int termpow = term * term / int(ONE) * term / int(ONE);
halflnz += termpow / 3;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 5;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 7;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 9;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 11;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 13;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 15;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 17;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 19;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 21;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 23;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 25;
return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz;
}
/// @dev Returns base 2 logarithm value of given x
/// @param x x
/// @return logarithmic value
function floorLog2(uint x)
public
pure
returns (int lo)
{
lo = -64;
int hi = 193;
// I use a shift here instead of / 2 because it floors instead of rounding towards 0
int mid = (hi + lo) >> 1;
while((lo + 1) < hi) {
if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE)
hi = mid;
else
lo = mid;
mid = (hi + lo) >> 1;
}
}
/// @dev Returns maximum of an array
/// @param nums Numbers to look through
/// @return Maximum number
function max(int[] nums)
public
pure
returns (int maxNum)
{
require(nums.length > 0);
maxNum = -2**255;
for (uint i = 0; i < nums.length; i++)
if (nums[i] > maxNum)
maxNum = nums[i];
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b)
internal
pure
returns (bool)
{
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b)
internal
pure
returns (bool)
{
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b)
internal
pure
returns (bool)
{
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b)
internal
pure
returns (uint)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b)
internal
pure
returns (uint)
{
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b)
internal
pure
returns (uint)
{
require(safeToMul(a, b));
return a * b;
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(int a, int b)
internal
pure
returns (bool)
{
return (b >= 0 && a + b >= a) || (b < 0 && a + b < a);
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(int a, int b)
internal
pure
returns (bool)
{
return (b >= 0 && a - b <= a) || (b < 0 && a - b > a);
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(int a, int b)
internal
pure
returns (bool)
{
return (b == 0) || (a * b / b == a);
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(int a, int b)
internal
pure
returns (int)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(int a, int b)
internal
pure
returns (int)
{
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(int a, int b)
internal
pure
returns (int)
{
require(safeToMul(a, b));
return a * b;
}
}
// File: @gnosis.pm/util-contracts/contracts/Proxy.sol
/// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy.
/// @author Alan Lu - <[email protected]>
contract Proxied {
address public masterCopy;
}
/// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <[email protected]>
contract Proxy is Proxied {
/// @dev Constructor function sets address of master copy contract.
/// @param _masterCopy Master copy address.
function Proxy(address _masterCopy)
public
{
require(_masterCopy != 0);
masterCopy = _masterCopy;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
function ()
external
payable
{
address _masterCopy = masterCopy;
assembly {
calldatacopy(0, 0, calldatasize())
let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch success
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
// File: @gnosis.pm/util-contracts/contracts/Token.sol
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
pragma solidity ^0.4.21;
/// @title Abstract token contract - Functions to be implemented by token contracts
contract Token {
/*
* Events
*/
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
/*
* Public functions
*/
function transfer(address to, uint value) public returns (bool);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
function balanceOf(address owner) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function totalSupply() public view returns (uint);
}
// File: @gnosis.pm/util-contracts/contracts/StandardToken.sol
contract StandardTokenData {
/*
* Storage
*/
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowances;
uint totalTokens;
}
/// @title Standard token contract with overflow protection
contract StandardToken is Token, StandardTokenData {
using Math for *;
/*
* Public functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transfer(address to, uint value)
public
returns (bool)
{
if ( !balances[msg.sender].safeToSub(value)
|| !balances[to].safeToAdd(value))
return false;
balances[msg.sender] -= value;
balances[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success
/// @param from Address from where tokens are withdrawn
/// @param to Address to where tokens are sent
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transferFrom(address from, address to, uint value)
public
returns (bool)
{
if ( !balances[from].safeToSub(value)
|| !allowances[from][msg.sender].safeToSub(value)
|| !balances[to].safeToAdd(value))
return false;
balances[from] -= value;
allowances[from][msg.sender] -= value;
balances[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Sets approved amount of tokens for spender. Returns success
/// @param spender Address of allowed account
/// @param value Number of approved tokens
/// @return Was approval successful?
function approve(address spender, uint value)
public
returns (bool)
{
allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Returns number of allowed tokens for given address
/// @param owner Address of token owner
/// @param spender Address of token spender
/// @return Remaining allowance for spender
function allowance(address owner, address spender)
public
view
returns (uint)
{
return allowances[owner][spender];
}
/// @dev Returns number of tokens owned by given address
/// @param owner Address of token owner
/// @return Balance of owner
function balanceOf(address owner)
public
view
returns (uint)
{
return balances[owner];
}
/// @dev Returns total supply of tokens
/// @return Total supply
function totalSupply()
public
view
returns (uint)
{
return totalTokens;
}
}
// File: contracts/TokenFRT.sol
/// @title Standard token contract with overflow protection
contract TokenFRT is StandardToken {
string public constant symbol = "MGN";
string public constant name = "Magnolia Token";
uint8 public constant decimals = 18;
struct unlockedToken {
uint amountUnlocked;
uint withdrawalTime;
}
/*
* Storage
*/
address public owner;
address public minter;
// user => unlockedToken
mapping (address => unlockedToken) public unlockedTokens;
// user => amount
mapping (address => uint) public lockedTokenBalances;
/*
* Public functions
*/
function TokenFRT(
address _owner
)
public
{
require(_owner != address(0));
owner = _owner;
}
// @dev allows to set the minter of Magnolia tokens once.
// @param _minter the minter of the Magnolia tokens, should be the DX-proxy
function updateMinter(
address _minter
)
public
{
require(msg.sender == owner);
require(_minter != address(0));
minter = _minter;
}
// @dev the intention is to set the owner as the DX-proxy, once it is deployed
// Then only an update of the DX-proxy contract after a 30 days delay could change the minter again.
function updateOwner(
address _owner
)
public
{
require(msg.sender == owner);
require(_owner != address(0));
owner = _owner;
}
function mintTokens(
address user,
uint amount
)
public
{
require(msg.sender == minter);
lockedTokenBalances[user] = add(lockedTokenBalances[user], amount);
totalTokens = add(totalTokens, amount);
}
/// @dev Lock Token
function lockTokens(
uint amount
)
public
returns (uint totalAmountLocked)
{
// Adjust amount by balance
amount = min(amount, balances[msg.sender]);
// Update state variables
balances[msg.sender] = sub(balances[msg.sender], amount);
lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], amount);
// Get return variable
totalAmountLocked = lockedTokenBalances[msg.sender];
}
function unlockTokens(
uint amount
)
public
returns (uint totalAmountUnlocked, uint withdrawalTime)
{
// Adjust amount by locked balances
amount = min(amount, lockedTokenBalances[msg.sender]);
if (amount > 0) {
// Update state variables
lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount);
unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount);
unlockedTokens[msg.sender].withdrawalTime = now + 24 hours;
}
// Get return variables
totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked;
withdrawalTime = unlockedTokens[msg.sender].withdrawalTime;
}
function withdrawUnlockedTokens()
public
{
require(unlockedTokens[msg.sender].withdrawalTime < now);
balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked);
unlockedTokens[msg.sender].amountUnlocked = 0;
}
function min(uint a, uint b)
public
pure
returns (uint)
{
if (a < b) {
return a;
} else {
return b;
}
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b)
public
constant
returns (bool)
{
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b)
public
constant
returns (bool)
{
return a >= b;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b)
public
constant
returns (uint)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b)
public
constant
returns (uint)
{
require(safeToSub(a, b));
return a - b;
}
}
// File: @gnosis.pm/owl-token/contracts/TokenOWL.sol
contract TokenOWL is Proxied, StandardToken {
using Math for *;
string public constant name = "OWL Token";
string public constant symbol = "OWL";
uint8 public constant decimals = 18;
struct masterCopyCountdownType {
address masterCopy;
uint timeWhenAvailable;
}
masterCopyCountdownType masterCopyCountdown;
address public creator;
address public minter;
event Minted(address indexed to, uint256 amount);
event Burnt(address indexed from, address indexed user, uint256 amount);
modifier onlyCreator() {
// R1
require(msg.sender == creator);
_;
}
/// @dev trickers the update process via the proxyMaster for a new address _masterCopy
/// updating is only possible after 30 days
function startMasterCopyCountdown (
address _masterCopy
)
public
onlyCreator()
{
require(address(_masterCopy) != 0);
// Update masterCopyCountdown
masterCopyCountdown.masterCopy = _masterCopy;
masterCopyCountdown.timeWhenAvailable = now + 30 days;
}
/// @dev executes the update process via the proxyMaster for a new address _masterCopy
function updateMasterCopy()
public
onlyCreator()
{
require(address(masterCopyCountdown.masterCopy) != 0);
require(now >= masterCopyCountdown.timeWhenAvailable);
// Update masterCopy
masterCopy = masterCopyCountdown.masterCopy;
}
function getMasterCopy()
public
view
returns (address)
{
return masterCopy;
}
/// @dev Set minter. Only the creator of this contract can call this.
/// @param newMinter The new address authorized to mint this token
function setMinter(address newMinter)
public
onlyCreator()
{
minter = newMinter;
}
/// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this.
/// @param newOwner The new address, which should become the owner
function setNewOwner(address newOwner)
public
onlyCreator()
{
creator = newOwner;
}
/// @dev Mints OWL.
/// @param to Address to which the minted token will be given
/// @param amount Amount of OWL to be minted
function mintOWL(address to, uint amount)
public
{
require(minter != 0 && msg.sender == minter);
balances[to] = balances[to].add(amount);
totalTokens = totalTokens.add(amount);
emit Minted(to, amount);
}
/// @dev Burns OWL.
/// @param user Address of OWL owner
/// @param amount Amount of OWL to be burnt
function burnOWL(address user, uint amount)
public
{
allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount);
balances[user] = balances[user].sub(amount);
totalTokens = totalTokens.sub(amount);
emit Burnt(msg.sender, user, amount);
}
}
// File: contracts/DutchExchange.sol
/// @title Dutch Exchange - exchange token pairs with the clever mechanism of the dutch auction
/// @author Alex Herrmann - <[email protected]>
/// @author Dominik Teiml - <[email protected]>
contract DutchExchange is Proxied {
// The price is a rational number, so we need a concept of a fraction
struct fraction {
uint num;
uint den;
}
uint constant WAITING_PERIOD_NEW_TOKEN_PAIR = 6 hours;
uint constant WAITING_PERIOD_NEW_AUCTION = 10 minutes;
uint constant WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE = 30 days;
uint constant AUCTION_START_WAITING_FOR_FUNDING = 1;
address public newMasterCopy;
// Time when new masterCopy is updatabale
uint public masterCopyCountdown;
// > Storage
// auctioneer has the power to manage some variables
address public auctioneer;
// Ether ERC-20 token
address public ethToken;
// Price Oracle interface
PriceOracleInterface public ethUSDOracle;
// Price Oracle interface proposals during update process
PriceOracleInterface public newProposalEthUSDOracle;
uint public oracleInterfaceCountdown;
// Minimum required sell funding for adding a new token pair, in USD
uint public thresholdNewTokenPair;
// Minimum required sell funding for starting antoher auction, in USD
uint public thresholdNewAuction;
// Fee reduction token (magnolia, ERC-20 token)
TokenFRT public frtToken;
// Token for paying fees
TokenOWL public owlToken;
// mapping that stores the tokens, which are approved
// Token => approved
// Only tokens approved by auctioneer generate frtToken tokens
mapping (address => bool) public approvedTokens;
// For the following two mappings, there is one mapping for each token pair
// The order which the tokens should be called is smaller, larger
// These variables should never be called directly! They have getters below
// Token => Token => index
mapping (address => mapping (address => uint)) public latestAuctionIndices;
// Token => Token => time
mapping (address => mapping (address => uint)) public auctionStarts;
// Token => Token => auctionIndex => price
mapping (address => mapping (address => mapping (uint => fraction))) public closingPrices;
// Token => Token => amount
mapping (address => mapping (address => uint)) public sellVolumesCurrent;
// Token => Token => amount
mapping (address => mapping (address => uint)) public sellVolumesNext;
// Token => Token => amount
mapping (address => mapping (address => uint)) public buyVolumes;
// Token => user => amount
// balances stores a user's balance in the DutchX
mapping (address => mapping (address => uint)) public balances;
// Token => Token => auctionIndex => amount
mapping (address => mapping (address => mapping (uint => uint))) public extraTokens;
// Token => Token => auctionIndex => user => amount
mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public sellerBalances;
mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public buyerBalances;
mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public claimedAmounts;
// > Modifiers
modifier onlyAuctioneer() {
// Only allows auctioneer to proceed
// R1
require(msg.sender == auctioneer);
_;
}
/// @dev Constructor-Function creates exchange
/// @param _frtToken - address of frtToken ERC-20 token
/// @param _owlToken - address of owlToken ERC-20 token
/// @param _auctioneer - auctioneer for managing interfaces
/// @param _ethToken - address of ETH ERC-20 token
/// @param _ethUSDOracle - address of the oracle contract for fetching feeds
/// @param _thresholdNewTokenPair - Minimum required sell funding for adding a new token pair, in USD
function setupDutchExchange(
TokenFRT _frtToken,
TokenOWL _owlToken,
address _auctioneer,
address _ethToken,
PriceOracleInterface _ethUSDOracle,
uint _thresholdNewTokenPair,
uint _thresholdNewAuction
)
public
{
// Make sure contract hasn't been initialised
require(ethToken == 0);
// Validates inputs
require(address(_owlToken) != address(0));
require(address(_frtToken) != address(0));
require(_auctioneer != 0);
require(_ethToken != 0);
require(address(_ethUSDOracle) != address(0));
frtToken = _frtToken;
owlToken = _owlToken;
auctioneer = _auctioneer;
ethToken = _ethToken;
ethUSDOracle = _ethUSDOracle;
thresholdNewTokenPair = _thresholdNewTokenPair;
thresholdNewAuction = _thresholdNewAuction;
}
function updateAuctioneer(
address _auctioneer
)
public
onlyAuctioneer
{
require(_auctioneer != address(0));
auctioneer = _auctioneer;
}
function initiateEthUsdOracleUpdate(
PriceOracleInterface _ethUSDOracle
)
public
onlyAuctioneer
{
require(address(_ethUSDOracle) != address(0));
newProposalEthUSDOracle = _ethUSDOracle;
oracleInterfaceCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE);
NewOracleProposal(_ethUSDOracle);
}
function updateEthUSDOracle()
public
onlyAuctioneer
{
require(address(newProposalEthUSDOracle) != address(0));
require(oracleInterfaceCountdown < now);
ethUSDOracle = newProposalEthUSDOracle;
newProposalEthUSDOracle = PriceOracleInterface(0);
}
function updateThresholdNewTokenPair(
uint _thresholdNewTokenPair
)
public
onlyAuctioneer
{
thresholdNewTokenPair = _thresholdNewTokenPair;
}
function updateThresholdNewAuction(
uint _thresholdNewAuction
)
public
onlyAuctioneer
{
thresholdNewAuction = _thresholdNewAuction;
}
function updateApprovalOfToken(
address[] token,
bool approved
)
public
onlyAuctioneer
{
for(uint i = 0; i < token.length; i++) {
approvedTokens[token[i]] = approved;
Approval(token[i], approved);
}
}
function startMasterCopyCountdown (
address _masterCopy
)
public
onlyAuctioneer
{
require(_masterCopy != address(0));
// Update masterCopyCountdown
newMasterCopy = _masterCopy;
masterCopyCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE);
NewMasterCopyProposal(_masterCopy);
}
function updateMasterCopy()
public
onlyAuctioneer
{
require(newMasterCopy != address(0));
require(now >= masterCopyCountdown);
// Update masterCopy
masterCopy = newMasterCopy;
newMasterCopy = address(0);
}
/// @param initialClosingPriceNum initial price will be 2 * initialClosingPrice. This is its numerator
/// @param initialClosingPriceDen initial price will be 2 * initialClosingPrice. This is its denominator
function addTokenPair(
address token1,
address token2,
uint token1Funding,
uint token2Funding,
uint initialClosingPriceNum,
uint initialClosingPriceDen
)
public
{
// R1
require(token1 != token2);
// R2
require(initialClosingPriceNum != 0);
// R3
require(initialClosingPriceDen != 0);
// R4
require(getAuctionIndex(token1, token2) == 0);
// R5: to prevent overflow
require(initialClosingPriceNum < 10 ** 18);
// R6
require(initialClosingPriceDen < 10 ** 18);
setAuctionIndex(token1, token2);
token1Funding = min(token1Funding, balances[token1][msg.sender]);
token2Funding = min(token2Funding, balances[token2][msg.sender]);
// R7
require(token1Funding < 10 ** 30);
// R8
require(token2Funding < 10 ** 30);
uint fundedValueUSD;
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
// Compute fundedValueUSD
address ethTokenMem = ethToken;
if (token1 == ethTokenMem) {
// C1
// MUL: 10^30 * 10^6 = 10^36
fundedValueUSD = mul(token1Funding, ethUSDPrice);
} else if (token2 == ethTokenMem) {
// C2
// MUL: 10^30 * 10^6 = 10^36
fundedValueUSD = mul(token2Funding, ethUSDPrice);
} else {
// C3: Neither token is ethToken
fundedValueUSD = calculateFundedValueTokenToken(token1, token2,
token1Funding, token2Funding, ethTokenMem, ethUSDPrice);
}
// R5
require(fundedValueUSD >= thresholdNewTokenPair);
// Save prices of opposite auctions
closingPrices[token1][token2][0] = fraction(initialClosingPriceNum, initialClosingPriceDen);
closingPrices[token2][token1][0] = fraction(initialClosingPriceDen, initialClosingPriceNum);
// Split into two fns because of 16 local-var cap
addTokenPairSecondPart(token1, token2, token1Funding, token2Funding);
}
function calculateFundedValueTokenToken(
address token1,
address token2,
uint token1Funding,
uint token2Funding,
address ethTokenMem,
uint ethUSDPrice
)
internal
view
returns (uint fundedValueUSD)
{
// We require there to exist ethToken-Token auctions
// R3.1
require(getAuctionIndex(token1, ethTokenMem) > 0);
// R3.2
require(getAuctionIndex(token2, ethTokenMem) > 0);
// Price of Token 1
uint priceToken1Num;
uint priceToken1Den;
(priceToken1Num, priceToken1Den) = getPriceOfTokenInLastAuction(token1);
// Price of Token 2
uint priceToken2Num;
uint priceToken2Den;
(priceToken2Num, priceToken2Den) = getPriceOfTokenInLastAuction(token2);
// Compute funded value in ethToken and USD
// 10^30 * 10^30 = 10^60
uint fundedValueETH = add(mul(token1Funding, priceToken1Num) / priceToken1Den,
token2Funding * priceToken2Num / priceToken2Den);
fundedValueUSD = mul(fundedValueETH, ethUSDPrice);
}
function addTokenPairSecondPart(
address token1,
address token2,
uint token1Funding,
uint token2Funding
)
internal
{
balances[token1][msg.sender] = sub(balances[token1][msg.sender], token1Funding);
balances[token2][msg.sender] = sub(balances[token2][msg.sender], token2Funding);
// Fee mechanism, fees are added to extraTokens
uint token1FundingAfterFee = settleFee(token1, token2, 1, token1Funding);
uint token2FundingAfterFee = settleFee(token2, token1, 1, token2Funding);
// Update other variables
sellVolumesCurrent[token1][token2] = token1FundingAfterFee;
sellVolumesCurrent[token2][token1] = token2FundingAfterFee;
sellerBalances[token1][token2][1][msg.sender] = token1FundingAfterFee;
sellerBalances[token2][token1][1][msg.sender] = token2FundingAfterFee;
setAuctionStart(token1, token2, WAITING_PERIOD_NEW_TOKEN_PAIR);
NewTokenPair(token1, token2);
}
function deposit(
address tokenAddress,
uint amount
)
public
returns (uint)
{
// R1
require(Token(tokenAddress).transferFrom(msg.sender, this, amount));
uint newBal = add(balances[tokenAddress][msg.sender], amount);
balances[tokenAddress][msg.sender] = newBal;
NewDeposit(tokenAddress, amount);
return newBal;
}
function withdraw(
address tokenAddress,
uint amount
)
public
returns (uint)
{
uint usersBalance = balances[tokenAddress][msg.sender];
amount = min(amount, usersBalance);
// R1
require(amount > 0);
// R2
require(Token(tokenAddress).transfer(msg.sender, amount));
uint newBal = sub(usersBalance, amount);
balances[tokenAddress][msg.sender] = newBal;
NewWithdrawal(tokenAddress, amount);
return newBal;
}
function postSellOrder(
address sellToken,
address buyToken,
uint auctionIndex,
uint amount
)
public
returns (uint, uint)
{
// Note: if a user specifies auctionIndex of 0, it
// means he is agnostic which auction his sell order goes into
amount = min(amount, balances[sellToken][msg.sender]);
// R1
require(amount > 0);
// R2
uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken);
require(latestAuctionIndex > 0);
// R3
uint auctionStart = getAuctionStart(sellToken, buyToken);
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) {
// C1: We are in the 10 minute buffer period
// OR waiting for an auction to receive sufficient sellVolume
// Auction has already cleared, and index has been incremented
// sell order must use that auction index
// R1.1
if (auctionIndex == 0) {
auctionIndex = latestAuctionIndex;
} else {
require(auctionIndex == latestAuctionIndex);
}
// R1.2
require(add(sellVolumesCurrent[sellToken][buyToken], amount) < 10 ** 30);
} else {
// C2
// R2.1: Sell orders must go to next auction
if (auctionIndex == 0) {
auctionIndex = latestAuctionIndex + 1;
} else {
require(auctionIndex == latestAuctionIndex + 1);
}
// R2.2
require(add(sellVolumesNext[sellToken][buyToken], amount) < 10 ** 30);
}
// Fee mechanism, fees are added to extraTokens
uint amountAfterFee = settleFee(sellToken, buyToken, auctionIndex, amount);
// Update variables
balances[sellToken][msg.sender] = sub(balances[sellToken][msg.sender], amount);
uint newSellerBal = add(sellerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee);
sellerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newSellerBal;
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) {
// C1
uint sellVolumeCurrent = sellVolumesCurrent[sellToken][buyToken];
sellVolumesCurrent[sellToken][buyToken] = add(sellVolumeCurrent, amountAfterFee);
} else {
// C2
uint sellVolumeNext = sellVolumesNext[sellToken][buyToken];
sellVolumesNext[sellToken][buyToken] = add(sellVolumeNext, amountAfterFee);
}
if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING) {
scheduleNextAuction(sellToken, buyToken);
}
NewSellOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee);
return (auctionIndex, newSellerBal);
}
function postBuyOrder(
address sellToken,
address buyToken,
uint auctionIndex,
uint amount
)
public
returns (uint)
{
// R1: auction must not have cleared
require(closingPrices[sellToken][buyToken][auctionIndex].den == 0);
uint auctionStart = getAuctionStart(sellToken, buyToken);
// R2
require(auctionStart <= now);
// R4
require(auctionIndex == getAuctionIndex(sellToken, buyToken));
// R5: auction must not be in waiting period
require(auctionStart > AUCTION_START_WAITING_FOR_FUNDING);
// R6: auction must be funded
require(sellVolumesCurrent[sellToken][buyToken] > 0);
uint buyVolume = buyVolumes[sellToken][buyToken];
amount = min(amount, balances[buyToken][msg.sender]);
// R7
require(add(buyVolume, amount) < 10 ** 30);
// Overbuy is when a part of a buy order clears an auction
// In that case we only process the part before the overbuy
// To calculate overbuy, we first get current price
uint sellVolume = sellVolumesCurrent[sellToken][buyToken];
uint num;
uint den;
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume));
uint amountAfterFee;
if (amount < outstandingVolume) {
if (amount > 0) {
amountAfterFee = settleFee(buyToken, sellToken, auctionIndex, amount);
}
} else {
amount = outstandingVolume;
amountAfterFee = outstandingVolume;
}
// Here we could also use outstandingVolume or amountAfterFee, it doesn't matter
if (amount > 0) {
// Update variables
balances[buyToken][msg.sender] = sub(balances[buyToken][msg.sender], amount);
uint newBuyerBal = add(buyerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee);
buyerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newBuyerBal;
buyVolumes[sellToken][buyToken] = add(buyVolumes[sellToken][buyToken], amountAfterFee);
NewBuyOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee);
}
// Checking for equality would suffice here. nevertheless:
if (amount >= outstandingVolume) {
// Clear auction
clearAuction(sellToken, buyToken, auctionIndex, sellVolume);
}
return (newBuyerBal);
}
function claimSellerFunds(
address sellToken,
address buyToken,
address user,
uint auctionIndex
)
public
// < (10^60, 10^61)
returns (uint returned, uint frtsIssued)
{
closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
uint sellerBalance = sellerBalances[sellToken][buyToken][auctionIndex][user];
// R1
require(sellerBalance > 0);
// Get closing price for said auction
fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex];
uint num = closingPrice.num;
uint den = closingPrice.den;
// R2: require auction to have cleared
require(den > 0);
// Calculate return
// < 10^30 * 10^30 = 10^60
returned = mul(sellerBalance, num) / den;
frtsIssued = issueFrts(sellToken, buyToken, returned, auctionIndex, sellerBalance, user);
// Claim tokens
sellerBalances[sellToken][buyToken][auctionIndex][user] = 0;
if (returned > 0) {
balances[buyToken][user] = add(balances[buyToken][user], returned);
}
NewSellerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued);
}
function claimBuyerFunds(
address sellToken,
address buyToken,
address user,
uint auctionIndex
)
public
returns (uint returned, uint frtsIssued)
{
closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex);
uint num;
uint den;
(returned, num, den) = getUnclaimedBuyerFunds(sellToken, buyToken, user, auctionIndex);
if (closingPrices[sellToken][buyToken][auctionIndex].den == 0) {
// Auction is running
claimedAmounts[sellToken][buyToken][auctionIndex][user] = add(claimedAmounts[sellToken][buyToken][auctionIndex][user], returned);
} else {
// Auction has closed
// We DON'T want to check for returned > 0, because that would fail if a user claims
// intermediate funds & auction clears in same block (he/she would not be able to claim extraTokens)
// Assign extra sell tokens (this is possible only after auction has cleared,
// because buyVolume could still increase before that)
uint extraTokensTotal = extraTokens[sellToken][buyToken][auctionIndex];
uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user];
// closingPrices.num represents buyVolume
// < 10^30 * 10^30 = 10^60
uint tokensExtra = mul(buyerBalance, extraTokensTotal) / closingPrices[sellToken][buyToken][auctionIndex].num;
returned = add(returned, tokensExtra);
frtsIssued = issueFrts(buyToken, sellToken, mul(buyerBalance, den) / num, auctionIndex, buyerBalance, user);
// Auction has closed
// Reset buyerBalances and claimedAmounts
buyerBalances[sellToken][buyToken][auctionIndex][user] = 0;
claimedAmounts[sellToken][buyToken][auctionIndex][user] = 0;
}
// Claim tokens
if (returned > 0) {
balances[sellToken][user] = add(balances[sellToken][user], returned);
}
NewBuyerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued);
}
function issueFrts(
address primaryToken,
address secondaryToken,
uint x,
uint auctionIndex,
uint bal,
address user
)
internal
returns (uint frtsIssued)
{
if (approvedTokens[primaryToken] && approvedTokens[secondaryToken]) {
address ethTokenMem = ethToken;
// Get frts issued based on ETH price of returned tokens
if (primaryToken == ethTokenMem) {
frtsIssued = bal;
} else if (secondaryToken == ethTokenMem) {
// 10^30 * 10^39 = 10^66
frtsIssued = x;
} else {
// Neither token is ethToken, so we use getHhistoricalPriceOracle()
uint pastNum;
uint pastDen;
(pastNum, pastDen) = getPriceInPastAuction(primaryToken, ethTokenMem, auctionIndex - 1);
// 10^30 * 10^35 = 10^65
frtsIssued = mul(bal, pastNum) / pastDen;
}
if (frtsIssued > 0) {
// Issue frtToken
frtToken.mintTokens(user, frtsIssued);
}
}
}
//@dev allows to close possible theoretical closed markets
//@param sellToken sellToken of an auction
//@param buyToken buyToken of an auction
//@param index is the auctionIndex of the auction
function closeTheoreticalClosedAuction(
address sellToken,
address buyToken,
uint auctionIndex
)
public
{
if(auctionIndex == getAuctionIndex(buyToken, sellToken) && closingPrices[sellToken][buyToken][auctionIndex].num == 0) {
uint buyVolume = buyVolumes[sellToken][buyToken];
uint sellVolume = sellVolumesCurrent[sellToken][buyToken];
uint num;
uint den;
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
// 10^30 * 10^37 = 10^67
uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume));
if(outstandingVolume == 0) {
postBuyOrder(sellToken, buyToken, auctionIndex, 0);
}
}
}
/// @dev Claim buyer funds for one auction
function getUnclaimedBuyerFunds(
address sellToken,
address buyToken,
address user,
uint auctionIndex
)
public
view
// < (10^67, 10^37)
returns (uint unclaimedBuyerFunds, uint num, uint den)
{
// R1: checks if particular auction has ever run
require(auctionIndex <= getAuctionIndex(sellToken, buyToken));
(num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex);
if (num == 0) {
// This should rarely happen - as long as there is >= 1 buy order,
// auction will clear before price = 0. So this is just fail-safe
unclaimedBuyerFunds = 0;
} else {
uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user];
// < 10^30 * 10^37 = 10^67
unclaimedBuyerFunds = atleastZero(int(
mul(buyerBalance, den) / num -
claimedAmounts[sellToken][buyToken][auctionIndex][user]
));
}
}
function settleFee(
address primaryToken,
address secondaryToken,
uint auctionIndex,
uint amount
)
internal
// < 10^30
returns (uint amountAfterFee)
{
uint feeNum;
uint feeDen;
(feeNum, feeDen) = getFeeRatio(msg.sender);
// 10^30 * 10^3 / 10^4 = 10^29
uint fee = mul(amount, feeNum) / feeDen;
if (fee > 0) {
fee = settleFeeSecondPart(primaryToken, fee);
uint usersExtraTokens = extraTokens[primaryToken][secondaryToken][auctionIndex + 1];
extraTokens[primaryToken][secondaryToken][auctionIndex + 1] = add(usersExtraTokens, fee);
Fee(primaryToken, secondaryToken, msg.sender, auctionIndex, fee);
}
amountAfterFee = sub(amount, fee);
}
function settleFeeSecondPart(
address primaryToken,
uint fee
)
internal
returns (uint newFee)
{
// Allow user to reduce up to half of the fee with owlToken
uint num;
uint den;
(num, den) = getPriceOfTokenInLastAuction(primaryToken);
// Convert fee to ETH, then USD
// 10^29 * 10^30 / 10^30 = 10^29
uint feeInETH = mul(fee, num) / den;
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
// 10^29 * 10^6 = 10^35
// Uses 18 decimal places <> exactly as owlToken tokens: 10**18 owlToken == 1 USD
uint feeInUSD = mul(feeInETH, ethUSDPrice);
uint amountOfowlTokenBurned = min(owlToken.allowance(msg.sender, this), feeInUSD / 2);
amountOfowlTokenBurned = min(owlToken.balanceOf(msg.sender), amountOfowlTokenBurned);
if (amountOfowlTokenBurned > 0) {
owlToken.burnOWL(msg.sender, amountOfowlTokenBurned);
// Adjust fee
// 10^35 * 10^29 = 10^64
uint adjustment = mul(amountOfowlTokenBurned, fee) / feeInUSD;
newFee = sub(fee, adjustment);
} else {
newFee = fee;
}
}
function getFeeRatio(
address user
)
public
view
// feeRatio < 10^4
returns (uint num, uint den)
{
uint t = frtToken.totalSupply();
uint b = frtToken.lockedTokenBalances(user);
if (b * 100000 < t || t == 0) {
// 0.5%
num = 1;
den = 200;
} else if (b * 10000 < t) {
// 0.4%
num = 1;
den = 250;
} else if (b * 1000 < t) {
// 0.3%
num = 3;
den = 1000;
} else if (b * 100 < t) {
// 0.2%
num = 1;
den = 500;
} else if (b * 10 < t) {
// 0.1%
num = 1;
den = 1000;
} else {
// 0%
num = 0;
den = 1;
}
}
/// @dev clears an Auction
/// @param sellToken sellToken of the auction
/// @param buyToken buyToken of the auction
/// @param auctionIndex of the auction to be cleared.
function clearAuction(
address sellToken,
address buyToken,
uint auctionIndex,
uint sellVolume
)
internal
{
// Get variables
uint buyVolume = buyVolumes[sellToken][buyToken];
uint sellVolumeOpp = sellVolumesCurrent[buyToken][sellToken];
uint closingPriceOppDen = closingPrices[buyToken][sellToken][auctionIndex].den;
uint auctionStart = getAuctionStart(sellToken, buyToken);
// Update closing price
if (sellVolume > 0) {
closingPrices[sellToken][buyToken][auctionIndex] = fraction(buyVolume, sellVolume);
}
// if (opposite is 0 auction OR price = 0 OR opposite auction cleared)
// price = 0 happens if auction pair has been running for >= 24 hrs = 86400
if (sellVolumeOpp == 0 || now >= auctionStart + 86400 || closingPriceOppDen > 0) {
// Close auction pair
uint buyVolumeOpp = buyVolumes[buyToken][sellToken];
if (closingPriceOppDen == 0 && sellVolumeOpp > 0) {
// Save opposite price
closingPrices[buyToken][sellToken][auctionIndex] = fraction(buyVolumeOpp, sellVolumeOpp);
}
uint sellVolumeNext = sellVolumesNext[sellToken][buyToken];
uint sellVolumeNextOpp = sellVolumesNext[buyToken][sellToken];
// Update state variables for both auctions
sellVolumesCurrent[sellToken][buyToken] = sellVolumeNext;
if (sellVolumeNext > 0) {
sellVolumesNext[sellToken][buyToken] = 0;
}
if (buyVolume > 0) {
buyVolumes[sellToken][buyToken] = 0;
}
sellVolumesCurrent[buyToken][sellToken] = sellVolumeNextOpp;
if (sellVolumeNextOpp > 0) {
sellVolumesNext[buyToken][sellToken] = 0;
}
if (buyVolumeOpp > 0) {
buyVolumes[buyToken][sellToken] = 0;
}
// Increment auction index
setAuctionIndex(sellToken, buyToken);
// Check if next auction can be scheduled
scheduleNextAuction(sellToken, buyToken);
}
AuctionCleared(sellToken, buyToken, sellVolume, buyVolume, auctionIndex);
}
function scheduleNextAuction(
address sellToken,
address buyToken
)
internal
{
// Check if auctions received enough sell orders
uint ethUSDPrice = ethUSDOracle.getUSDETHPrice();
uint sellNum;
uint sellDen;
(sellNum, sellDen) = getPriceOfTokenInLastAuction(sellToken);
uint buyNum;
uint buyDen;
(buyNum, buyDen) = getPriceOfTokenInLastAuction(buyToken);
// We use current sell volume, because in clearAuction() we set
// sellVolumesCurrent = sellVolumesNext before calling this function
// (this is so that we don't need case work,
// since it might also be called from postSellOrder())
// < 10^30 * 10^31 * 10^6 = 10^67
uint sellVolume = mul(mul(sellVolumesCurrent[sellToken][buyToken], sellNum), ethUSDPrice) / sellDen;
uint sellVolumeOpp = mul(mul(sellVolumesCurrent[buyToken][sellToken], buyNum), ethUSDPrice) / buyDen;
if (sellVolume >= thresholdNewAuction || sellVolumeOpp >= thresholdNewAuction) {
// Schedule next auction
setAuctionStart(sellToken, buyToken, WAITING_PERIOD_NEW_AUCTION);
} else {
resetAuctionStart(sellToken, buyToken);
}
}
//@ dev returns price in units [token2]/[token1]
//@ param token1 first token for price calculation
//@ param token2 second token for price calculation
//@ param auctionIndex index for the auction to get the averaged price from
function getPriceInPastAuction(
address token1,
address token2,
uint auctionIndex
)
public
view
// price < 10^31
returns (uint num, uint den)
{
if (token1 == token2) {
// C1
num = 1;
den = 1;
} else {
// C2
// R2.1
require(auctionIndex >= 0);
// C3
// R3.1
require(auctionIndex <= getAuctionIndex(token1, token2));
// auction still running
uint i = 0;
bool correctPair = false;
fraction memory closingPriceToken1;
fraction memory closingPriceToken2;
while (!correctPair) {
closingPriceToken2 = closingPrices[token2][token1][auctionIndex - i];
closingPriceToken1 = closingPrices[token1][token2][auctionIndex - i];
if (closingPriceToken1.num > 0 && closingPriceToken1.den > 0 ||
closingPriceToken2.num > 0 && closingPriceToken2.den > 0)
{
correctPair = true;
}
i++;
}
// At this point at least one closing price is strictly positive
// If only one is positive, we want to output that
if (closingPriceToken1.num == 0 || closingPriceToken1.den == 0) {
num = closingPriceToken2.den;
den = closingPriceToken2.num;
} else if (closingPriceToken2.num == 0 || closingPriceToken2.den == 0) {
num = closingPriceToken1.num;
den = closingPriceToken1.den;
} else {
// If both prices are positive, output weighted average
num = closingPriceToken2.den + closingPriceToken1.num;
den = closingPriceToken2.num + closingPriceToken1.den;
}
}
}
/// @dev Gives best estimate for market price of a token in ETH of any price oracle on the Ethereum network
/// @param token address of ERC-20 token
/// @return Weighted average of closing prices of opposite Token-ethToken auctions, based on their sellVolume
function getPriceOfTokenInLastAuction(
address token
)
public
view
// price < 10^31
returns (uint num, uint den)
{
uint latestAuctionIndex = getAuctionIndex(token, ethToken);
// getPriceInPastAuction < 10^30
(num, den) = getPriceInPastAuction(token, ethToken, latestAuctionIndex - 1);
}
function getCurrentAuctionPrice(
address sellToken,
address buyToken,
uint auctionIndex
)
public
view
// price < 10^37
returns (uint num, uint den)
{
fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex];
if (closingPrice.den != 0) {
// Auction has closed
(num, den) = (closingPrice.num, closingPrice.den);
} else if (auctionIndex > getAuctionIndex(sellToken, buyToken)) {
(num, den) = (0, 0);
} else {
// Auction is running
uint pastNum;
uint pastDen;
(pastNum, pastDen) = getPriceInPastAuction(sellToken, buyToken, auctionIndex - 1);
// If we're calling the function into an unstarted auction,
// it will return the starting price of that auction
uint timeElapsed = atleastZero(int(now - getAuctionStart(sellToken, buyToken)));
// The numbers below are chosen such that
// P(0 hrs) = 2 * lastClosingPrice, P(6 hrs) = lastClosingPrice, P(>=24 hrs) = 0
// 10^5 * 10^31 = 10^36
num = atleastZero(int((86400 - timeElapsed) * pastNum));
// 10^6 * 10^31 = 10^37
den = mul((timeElapsed + 43200), pastDen);
if (mul(num, sellVolumesCurrent[sellToken][buyToken]) <= mul(den, buyVolumes[sellToken][buyToken])) {
num = buyVolumes[sellToken][buyToken];
den = sellVolumesCurrent[sellToken][buyToken];
}
}
}
function depositAndSell(
address sellToken,
address buyToken,
uint amount
)
external
returns (uint newBal, uint auctionIndex, uint newSellerBal)
{
newBal = deposit(sellToken, amount);
(auctionIndex, newSellerBal) = postSellOrder(sellToken, buyToken, 0, amount);
}
function claimAndWithdraw(
address sellToken,
address buyToken,
address user,
uint auctionIndex,
uint amount
)
external
returns (uint returned, uint frtsIssued, uint newBal)
{
(returned, frtsIssued) = claimSellerFunds(sellToken, buyToken, user, auctionIndex);
newBal = withdraw(buyToken, amount);
}
// > Helper fns
function getTokenOrder(
address token1,
address token2
)
public
pure
returns (address, address)
{
if (token2 < token1) {
(token1, token2) = (token2, token1);
}
return (token1, token2);
}
function setAuctionStart(
address token1,
address token2,
uint value
)
internal
{
(token1, token2) = getTokenOrder(token1, token2);
uint auctionStart = now + value;
uint auctionIndex = latestAuctionIndices[token1][token2];
auctionStarts[token1][token2] = auctionStart;
AuctionStartScheduled(token1, token2, auctionIndex, auctionStart);
}
function resetAuctionStart(
address token1,
address token2
)
internal
{
(token1, token2) = getTokenOrder(token1, token2);
if (auctionStarts[token1][token2] != AUCTION_START_WAITING_FOR_FUNDING) {
auctionStarts[token1][token2] = AUCTION_START_WAITING_FOR_FUNDING;
}
}
function getAuctionStart(
address token1,
address token2
)
public
view
returns (uint auctionStart)
{
(token1, token2) = getTokenOrder(token1, token2);
auctionStart = auctionStarts[token1][token2];
}
function setAuctionIndex(
address token1,
address token2
)
internal
{
(token1, token2) = getTokenOrder(token1, token2);
latestAuctionIndices[token1][token2] += 1;
}
function getAuctionIndex(
address token1,
address token2
)
public
view
returns (uint auctionIndex)
{
(token1, token2) = getTokenOrder(token1, token2);
auctionIndex = latestAuctionIndices[token1][token2];
}
// > Math fns
function min(uint a, uint b)
public
pure
returns (uint)
{
if (a < b) {
return a;
} else {
return b;
}
}
function atleastZero(int a)
public
pure
returns (uint)
{
if (a < 0) {
return 0;
} else {
return uint(a);
}
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b)
public
pure
returns (bool)
{
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b)
public
pure
returns (bool)
{
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b)
public
pure
returns (bool)
{
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b)
public
pure
returns (uint)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b)
public
pure
returns (uint)
{
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b)
public
pure
returns (uint)
{
require(safeToMul(a, b));
return a * b;
}
function getRunningTokenPairs(
address[] tokens
)
external
view
returns (address[] tokens1, address[] tokens2)
{
uint arrayLength;
for (uint k = 0; k < tokens.length - 1; k++) {
for (uint l = k + 1; l < tokens.length; l++) {
if (getAuctionIndex(tokens[k], tokens[l]) > 0) {
arrayLength++;
}
}
}
tokens1 = new address[](arrayLength);
tokens2 = new address[](arrayLength);
uint h;
for (uint i = 0; i < tokens.length - 1; i++) {
for (uint j = i + 1; j < tokens.length; j++) {
if (getAuctionIndex(tokens[i], tokens[j]) > 0) {
tokens1[h] = tokens[i];
tokens2[h] = tokens[j];
h++;
}
}
}
}
//@dev for quick overview of possible sellerBalances to calculate the possible withdraw tokens
//@param auctionSellToken is the sellToken defining an auctionPair
//@param auctionBuyToken is the buyToken defining an auctionPair
//@param user is the user who wants to his tokens
//@param lastNAuctions how many auctions will be checked. 0 means all
//@returns returns sellbal for all indices for all tokenpairs
function getIndicesWithClaimableTokensForSellers(
address auctionSellToken,
address auctionBuyToken,
address user,
uint lastNAuctions
)
external
view
returns(uint[] indices, uint[] usersBalances)
{
uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken);
uint arrayLength;
uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1;
for (uint j = startingIndex; j <= runningAuctionIndex; j++) {
if (sellerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) {
arrayLength++;
}
}
indices = new uint[](arrayLength);
usersBalances = new uint[](arrayLength);
uint k;
for (uint i = startingIndex; i <= runningAuctionIndex; i++) {
if (sellerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) {
indices[k] = i;
usersBalances[k] = sellerBalances[auctionSellToken][auctionBuyToken][i][user];
k++;
}
}
}
//@dev for quick overview of current sellerBalances for a user
//@param auctionSellTokens are the sellTokens defining an auctionPair
//@param auctionBuyTokens are the buyTokens defining an auctionPair
//@param user is the user who wants to his tokens
function getSellerBalancesOfCurrentAuctions(
address[] auctionSellTokens,
address[] auctionBuyTokens,
address user
)
external
view
returns (uint[])
{
uint length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint[] memory sellersBalances = new uint[](length);
for (uint i = 0; i < length; i++) {
uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]);
sellersBalances[i] = sellerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user];
}
return sellersBalances;
}
//@dev for quick overview of possible buyerBalances to calculate the possible withdraw tokens
//@param auctionSellToken is the sellToken defining an auctionPair
//@param auctionBuyToken is the buyToken defining an auctionPair
//@param user is the user who wants to his tokens
//@param lastNAuctions how many auctions will be checked. 0 means all
//@returns returns sellbal for all indices for all tokenpairs
function getIndicesWithClaimableTokensForBuyers(
address auctionSellToken,
address auctionBuyToken,
address user,
uint lastNAuctions
)
external
view
returns(uint[] indices, uint[] usersBalances)
{
uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken);
uint arrayLength;
uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1;
for (uint j = startingIndex; j <= runningAuctionIndex; j++) {
if (buyerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) {
arrayLength++;
}
}
indices = new uint[](arrayLength);
usersBalances = new uint[](arrayLength);
uint k;
for (uint i = startingIndex; i <= runningAuctionIndex; i++) {
if (buyerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) {
indices[k] = i;
usersBalances[k] = buyerBalances[auctionSellToken][auctionBuyToken][i][user];
k++;
}
}
}
//@dev for quick overview of current sellerBalances for a user
//@param auctionSellTokens are the sellTokens defining an auctionPair
//@param auctionBuyTokens are the buyTokens defining an auctionPair
//@param user is the user who wants to his tokens
function getBuyerBalancesOfCurrentAuctions(
address[] auctionSellTokens,
address[] auctionBuyTokens,
address user
)
external
view
returns (uint[])
{
uint length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint[] memory buyersBalances = new uint[](length);
for (uint i = 0; i < length; i++) {
uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]);
buyersBalances[i] = buyerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user];
}
return buyersBalances;
}
//@dev for quick overview of approved Tokens
//@param addressesToCheck are the ERC-20 token addresses to be checked whether they are approved
function getApprovedAddressesOfList(
address[] addressToCheck
)
external
view
returns (bool[])
{
uint length = addressToCheck.length;
bool[] memory isApproved = new bool[](length);
for (uint i = 0; i < length; i++) {
isApproved[i] = approvedTokens[addressToCheck[i]];
}
return isApproved;
}
//@dev for multiple withdraws
//@param auctionSellTokens are the sellTokens defining an auctionPair
//@param auctionBuyTokens are the buyTokens defining an auctionPair
//@param auctionIndices are the auction indices on which an token should be claimedAmounts
//@param user is the user who wants to his tokens
function claimTokensFromSeveralAuctionsAsSeller(
address[] auctionSellTokens,
address[] auctionBuyTokens,
uint[] auctionIndices,
address user
)
external
{
uint length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint length3 = auctionIndices.length;
require(length2 == length3);
for (uint i = 0; i < length; i++)
claimSellerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]);
}
//@dev for multiple withdraws
//@param auctionSellTokens are the sellTokens defining an auctionPair
//@param auctionBuyTokens are the buyTokens defining an auctionPair
//@param auctionIndices are the auction indices on which an token should be claimedAmounts
//@param user is the user who wants to his tokens
function claimTokensFromSeveralAuctionsAsBuyer(
address[] auctionSellTokens,
address[] auctionBuyTokens,
uint[] auctionIndices,
address user
)
external
{
uint length = auctionSellTokens.length;
uint length2 = auctionBuyTokens.length;
require(length == length2);
uint length3 = auctionIndices.length;
require(length2 == length3);
for (uint i = 0; i < length; i++)
claimBuyerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]);
}
function getMasterCopy()
external
view
returns (address)
{
return masterCopy;
}
// > Events
event NewDeposit(
address indexed token,
uint amount
);
event NewOracleProposal(
PriceOracleInterface priceOracleInterface
);
event NewMasterCopyProposal(
address newMasterCopy
);
event NewWithdrawal(
address indexed token,
uint amount
);
event NewSellOrder(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount
);
event NewBuyOrder(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount
);
event NewSellerFundsClaim(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount,
uint frtsIssued
);
event NewBuyerFundsClaim(
address indexed sellToken,
address indexed buyToken,
address indexed user,
uint auctionIndex,
uint amount,
uint frtsIssued
);
event NewTokenPair(
address indexed sellToken,
address indexed buyToken
);
event AuctionCleared(
address indexed sellToken,
address indexed buyToken,
uint sellVolume,
uint buyVolume,
uint indexed auctionIndex
);
event Approval(
address indexed token,
bool approved
);
event AuctionStartScheduled(
address indexed sellToken,
address indexed buyToken,
uint indexed auctionIndex,
uint auctionStart
);
event Fee(
address indexed primaryToken,
address indexed secondarToken,
address indexed user,
uint auctionIndex,
uint fee
);
}
|
Returns difference if no overflow occurred a Minuend b Subtrahend return Difference
|
function sub(uint a, uint b)
public
pure
returns (uint)
{
require(safeToSub(a, b));
return a - b;
}
| 7,683,283 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
//TODO Testear que funciona el porcentaje del 66,66
// Imports
import "./Libraries.sol";
contract FirstPresale is ReentrancyGuard {
address payable public owner; // Dueño del contrato.
IERC20 public token; // CRW Token.
bool private tokenAvailable = false;
uint public tokensPerBNB = 800000; // Cantidad de CRWs que se van a repartir por cada BNB aportado.
uint public ending; // Tiempo que va finalizar la preventa.
bool public presaleStarted = false; // Indica si la preventa ha sido iniciada o no.
address public deadWallet = 0x000000000000000000000000000000000000dEaD; // Wallet de quemado.
uint public firstCooldownTime = 7 days; //21 days
uint public cooldownTime = 3 days; //7 days
uint public firstClaimReady;
uint public tokensSold;
uint public tokensStillAvailable;
uint private _firstPresaleTokens = 0.1 * 1000000 * 1000000000000000000;
mapping(address => bool) public whitelist; // Whitelist de inversores permitidos en la preventa.
mapping(address => uint) public invested; // Cantidad de BNBs que ha invertido cada inversor en la preventa.
mapping(address => uint) public investorBalance;
mapping(address => uint) public withdrawableBalance;
mapping(address => uint) public claimReady;
constructor(address payable _teamWallet) {
owner = _teamWallet;
}
modifier onlyOwner() {
require(msg.sender == owner, 'You must be the owner.');
_;
}
/**
* @notice Función que actualiza el token en el contrato (Solo se puede hacer 1 vez).
* @param _token Dirección del contrato del token.
*/
function setToken(IERC20 _token) public onlyOwner {
require(!tokenAvailable, "Token is already inserted.");
token = _token;
tokenAvailable = true;
}
/**
* @notice Función que permite añadir inversores a la whitelist.
* @param _investor Direcciones de los inversores que entran en la whitelist.
*/
function addToWhitelist(address[] memory _investor) public onlyOwner {
for (uint _i = 0; _i < _investor.length; _i++) {
require(_investor[_i] != address(0), 'Invalid address.');
address _investorAddress = _investor[_i];
whitelist[_investorAddress] = true;
}
}
/**
* @notice Función que inicia la Preventa (Solo se puede iniciar una vez).
* @param _presaleTime Tiempo que va a durar la preventa.
*/
function startPresale(uint _presaleTime) public onlyOwner {
require(!presaleStarted, "Presale already started.");
ending = block.timestamp + _presaleTime;
firstClaimReady = block.timestamp + firstCooldownTime;
presaleStarted = true;
}
/**
* @notice Función que te permite comprar CRWs.
*/
//TODO FALTA PONER EL LIMITE SUPERIOR CUANDO SE TERMINEN LOS TOKENS
function invest() public payable nonReentrant {
require(whitelist[msg.sender], "You must be on the whitelist.");
require(presaleStarted, "Presale must have started.");
require(block.timestamp <= ending, "Presale finished.");
invested[msg.sender] += msg.value; // Actualiza la inversión del inversor.
require(invested[msg.sender] >= 0.10 ether, "Your investment should be more than 0.10 BNB.");
require(invested[msg.sender] <= 10 ether, "Your investment cannot exceed 10 BNB.");
uint _investorTokens = msg.value * tokensPerBNB; // Tokens que va a recibir el inversor.
require(tokensStillAvailable <= _firstPresaleTokens, "There are not that much tokens left");
investorBalance[msg.sender] += _investorTokens;
withdrawableBalance[msg.sender] += _investorTokens;
tokensSold += _investorTokens;
tokensStillAvailable += _investorTokens;
}
/**
* @notice Calcula el % de un número.
* @param x Número.
* @param y % del número.
* @param scale División.
*/
function mulScale (uint x, uint y, uint128 scale) internal pure returns (uint) {
uint a = x / scale;
uint b = x % scale;
uint c = y / scale;
uint d = y % scale;
return a * c * scale + a * d + b * c + b * d / scale;
}
/**
* @notice Función que permite a los inversores hacer claim de sus tokens disponibles.
*/
function claimTokens() public nonReentrant {
require(whitelist[msg.sender], "You must be on the whitelist.");
require(block.timestamp > ending, "Presale must have finished.");
require(firstClaimReady <= block.timestamp, "You can't claim yet.");
require(claimReady[msg.sender] <= block.timestamp, "You can't claim now.");
uint _contractBalance = token.balanceOf(address(this));
require(_contractBalance > 0, "Insufficient contract balance.");
require(investorBalance[msg.sender] > 0, "Insufficient investor balance.");
uint _withdrawableTokensBalance = mulScale(investorBalance[msg.sender], 5000, 10000); // 5000 basis points = 50%.
// Si tu balance es menor a la cantidad que puedes retirar directamente te transfiere todo tu saldo.
if(withdrawableBalance[msg.sender] <= _withdrawableTokensBalance) {
token.transfer(msg.sender, withdrawableBalance[msg.sender]);
investorBalance[msg.sender] = 0;
withdrawableBalance[msg.sender] = 0;
} else {
claimReady[msg.sender] = block.timestamp + cooldownTime; // Actualiza cuando será el próximo claim.
withdrawableBalance[msg.sender] -= _withdrawableTokensBalance; // Actualiza el balance del inversor.
token.transfer(msg.sender, _withdrawableTokensBalance); // Transfiere los tokens.
}
}
/**
* @notice Función que permite retirar los BNBs del contrato a la dirección del owner.
*/
function withdrawBnbs() public onlyOwner {
uint _bnbBalance = address(this).balance;
payable(owner).transfer(_bnbBalance);
}
function finishPresaleBurnOrBack() public onlyOwner {
require(block.timestamp > ending, "Presale must have finished.");
// If 60% of tokens aren't sold, it will send back to owner address
uint minTokensSold = _firstPresaleTokens * 2 / 3;
uint _contractBalance = token.balanceOf(address(this));
uint _tokenBalance = _contractBalance - tokensSold;
if(tokensSold >= minTokensSold){
_burnTokens(_tokenBalance);
}else{
_backTokens(_tokenBalance);
}
}
/**
* @notice Función que quema los tokens que sobran en la preventa.
*/
function _burnTokens(uint _tokenBalance) internal onlyOwner {
token.transfer(deadWallet, _tokenBalance);
}
function _backTokens(uint _tokenBalance) internal onlyOwner {
token.transfer(owner, _tokenBalance);
}
}
|
Función que inicia la Preventa (Solo se puede iniciar una vez). _presaleTime Tiempo que va a durar la preventa./
|
function startPresale(uint _presaleTime) public onlyOwner {
require(!presaleStarted, "Presale already started.");
ending = block.timestamp + _presaleTime;
firstClaimReady = block.timestamp + firstCooldownTime;
presaleStarted = true;
}
| 13,059,799 |
./full_match/7700/0xE5D67d152441e72DbF1B061e4C3d51B3FeDe8F4B/sources/contracts/Terrestrials.sol
|
Registers the smart contract with TurnstileMints the CSR NFT to the contract creator
|
function setTurnstile() external onlyOwner {
turnstile.register(msg.sender);
}
| 4,649,293 |
./full_match/5/0x393c146c8824Ab2a0A96cf2Ab949ab7Ded9D6238/sources/project_/contracts/PLCRVoting.sol
|
This will resume the contract's normal operation
|
function resumeAllMotorFunctions() external onlyOwner() {
killSwitch = false;
}
| 1,919,614 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../access/Roles.sol";
/**
* @title FriendlyCrowdsale
* @author Vittorio Minacori (https://github.com/vittominacori)
* @dev FriendlyCrowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether.
*/
contract FriendlyCrowdsale is ReentrancyGuard, Roles {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address payable private _wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of wei raised
uint256 private _weiRaised;
// Max amount of wei to be contributed
uint256 private _cap;
// Crowdsale opening time
uint256 private _openingTime;
// Crowdsale closing time
uint256 private _closingTime;
// Minimum amount of funds to be raised in weis
uint256 private _goal;
// If the Crowdsale is finalized or not
bool private _finalized;
// Address where fee are collected
address payable private _feeWallet;
// Per mille rate fee
uint256 private _feePerMille;
// List of addresses who contributed in crowdsales
EnumerableSet.AddressSet private _investors;
// Map of investors deposit
mapping(address => uint256) private _deposits;
// Map of investors purchased tokens
mapping(address => uint256) private _purchasedTokens;
// Crowdsale status list
enum State { Review, Active, Refunding, Closed, Expired, Rejected }
// Crowdsale current state
State private _state;
/**
* 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 TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event CrowdsaleFinalized();
event Enabled();
event Rejected();
event RefundsClosed();
event RefundsEnabled();
event Expired();
event Withdrawn(address indexed refundee, uint256 weiAmount);
/**
* @param openingTime Crowdsale opening time
* @param closingTime Crowdsale closing time
* @param cap Max amount of wei to be contributed
* @param goal Funding goal
* @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
* @param feeWallet Address of the fee wallet
* @param feePerMille The per mille rate fee
*/
constructor(
uint256 openingTime,
uint256 closingTime,
uint256 cap,
uint256 goal,
uint256 rate,
address payable wallet,
IERC20 token,
address payable feeWallet,
uint256 feePerMille
) {
require(rate > 0, "Crowdsale: rate is 0");
require(wallet != address(0), "Crowdsale: wallet is the zero address");
require(address(token) != address(0), "Crowdsale: token is the zero address");
// solhint-disable-next-line not-rely-on-time
require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time");
require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time");
require(closingTime <= openingTime + 40 days, "FriendlyCrowdsale: max allowed duration is 40 days");
require(cap > 0, "CappedCrowdsale: cap is 0");
require(goal > 0, "FriendlyCrowdsale: goal is 0");
require(goal <= cap, "FriendlyCrowdsale: goal is not less or equal cap");
require(feeWallet != address(0), "FriendlyCrowdsale: feeWallet is the zero address");
_rate = rate;
_wallet = wallet;
_token = token;
_openingTime = openingTime;
_closingTime = closingTime;
_cap = cap;
_goal = goal;
_feeWallet = feeWallet;
_feePerMille = feePerMille;
_state = State.Review;
_finalized = false;
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer funds with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
receive() external payable {
buyTokens(_msgSender());
}
/**
* @return the token being sold.
*/
function token() external view returns (IERC20) {
return _token;
}
/**
* @return the address where funds are collected.
*/
function wallet() external view returns (address payable) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() external view returns (uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() external view returns (uint256) {
return _weiRaised;
}
/**
* @return the cap of the crowdsale.
*/
function cap() external view returns (uint256) {
return _cap;
}
/**
* @return the crowdsale opening time.
*/
function openingTime() external view returns (uint256) {
return _openingTime;
}
/**
* @return the crowdsale closing time.
*/
function closingTime() external view returns (uint256) {
return _closingTime;
}
/**
* @return true if the crowdsale is finalized, false otherwise.
*/
function finalized() external view returns (bool) {
return _finalized;
}
/**
* @return address where fee are collected.
*/
function feeWallet() external view returns (address payable) {
return _feeWallet;
}
/**
* @return the per mille rate fee.
*/
function feePerMille() external view returns (uint256) {
return _feePerMille;
}
/**
* @return minimum amount of funds to be raised in wei.
*/
function goal() external view returns (uint256) {
return _goal;
}
/**
* @return The current state of the escrow.
*/
function state() external view returns (State) {
return _state;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return _weiRaised >= _cap;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp > _closingTime;
}
/**
* @return false if the ico is not started, true if the ico is started and running, true if the ico is completed
*/
function started() public view returns (bool) {
return block.timestamp >= _openingTime; // solhint-disable-line not-rely-on-time
}
/**
* @return false if the ico is not started, false if the ico is started and running, true if the ico is completed
*/
function ended() public view returns (bool) {
return hasClosed() || capReached();
}
/**
* @return true if the crowdsale is open, false otherwise.
*/
function isOpen() public view returns (bool) {
return started() && !hasClosed();
}
/**
* @dev Checks whether funding goal was reached.
* @return Whether funding goal was reached
*/
function goalReached() public view returns (bool) {
return _weiRaised >= _goal;
}
/**
* @dev Return the investors length.
* @return uint representing investors number
*/
function investorsNumber() public view returns (uint) {
return _investors.length();
}
/**
* @dev Check if a investor exists.
* @param account The address to check
* @return bool
*/
function investorExists(address account) public view returns (bool) {
return _investors.contains(account);
}
/**
* @dev Return the investors address by index.
* @param index A progressive index of investor addresses
* @return address of an investor by list index
*/
function getInvestorAddress(uint index) public view returns (address) {
return _investors.at(index);
}
/**
* @dev get wei contribution for the given address
* @param account Address has contributed
* @return uint256
*/
function weiContribution(address account) public view returns (uint256) {
return _deposits[account];
}
/**
* @dev get purchased tokens for the given address
* @param account Address has contributed
* @return uint256
*/
function purchasedTokens(address account) public view returns (uint256) {
return _purchasedTokens[account];
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary) public nonReentrant 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);
emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens);
_updatePurchasingState(beneficiary, weiAmount, tokens);
_forwardFunds();
_postValidatePurchase(beneficiary, weiAmount);
}
/**
* @dev Enable the crowdsale
*/
function enable() public onlyOperator {
require(_state == State.Review, "FriendlyCrowdsale: not reviewing");
_state = State.Active;
emit Enabled();
}
/**
* @dev Reject the crowdsale
*/
function reject() public onlyOperator {
require(_state == State.Review, "FriendlyCrowdsale: not reviewing");
_state = State.Rejected;
_recoverRemainingTokens();
emit Rejected();
}
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() public {
require(!_finalized, "FinalizableCrowdsale: already finalized");
require(hasClosed(), "FinalizableCrowdsale: not closed");
_finalized = true;
_finalization();
emit CrowdsaleFinalized();
}
/**
* @dev Investors can claim refunds here if crowdsale is unsuccessful.
* @param refundee Whose refund will be claimed.
*/
function claimRefund(address payable refundee) public {
require(_finalized, "FriendlyCrowdsale: not finalized");
require(_state == State.Refunding, "FriendlyCrowdsale: not refunding");
require(weiContribution(refundee) > 0, "FriendlyCrowdsale: no deposit");
uint256 payment = _deposits[refundee];
_deposits[refundee] = 0;
refundee.transfer(payment);
emit Withdrawn(refundee, payment);
}
/**
* @dev Set crowdsale expired and withdraw funds.
*/
function setExpiredAndWithdraw() public onlyOperator {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= _closingTime + 365 days, "FriendlyCrowdsale: not expired");
_state = State.Expired;
_feeWallet.transfer(address(this).balance);
emit Expired();
}
/**
* @dev Validation of an incoming purchase.
* Adds the validation that the crowdsale must be active.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view {
require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address");
require(weiAmount != 0, "Crowdsale: weiAmount is 0");
require(_weiRaised.add(weiAmount) <= _cap, "CappedCrowdsale: cap exceeded");
require(isOpen(), "TimedCrowdsale: not open");
require(_state == State.Active, "FriendlyCrowdsale: not active");
}
/**
* @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 view {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends
* its tokens.
* @param beneficiary Address performing the token purchase
* @param tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address beneficiary, uint256 tokenAmount) internal {
_token.safeTransfer(beneficiary, tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send
* 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);
}
/**
* @param beneficiary Address receiving the tokens
* @param weiAmount Value in wei involved in the purchase
* @param tokenAmount Number of tokens to be purchased
*/
function _updatePurchasingState(address beneficiary, uint256 weiAmount, uint256 tokenAmount) internal {
if (!investorExists(beneficiary)) {
_investors.add(beneficiary);
}
_deposits[beneficiary] = _deposits[beneficiary].add(weiAmount);
_purchasedTokens[beneficiary] = _purchasedTokens[beneficiary].add(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 Escrow finalization task, called when finalize() is called.
*/
function _finalization() internal {
if (goalReached()) {
_close();
} else {
_enableRefunds();
}
_recoverRemainingTokens();
}
/**
* @dev Overrides Crowdsale fund forwarding, keep funds here.
*/
function _forwardFunds() internal {
// solhint-disable-previous-line no-empty-blocks
// does nothing, keep funds on this contract
}
/**
* @dev Allows for the wallet to withdraw their funds.
*/
function _close() internal {
_state = State.Closed;
_feeWallet.transfer(address(this).balance.mul(_feePerMille).div(1000));
_wallet.transfer(address(this).balance);
emit RefundsClosed();
}
/**
* @dev Allows for refunds to take place.
*/
function _enableRefunds() internal {
_state = State.Refunding;
emit RefundsEnabled();
}
/**
* @dev Recover remaining tokens to wallet.
*/
function _recoverRemainingTokens() internal {
if (_token.balanceOf(address(this)) > 0) {
_token.safeTransfer(_wallet, _token.balanceOf(address(this)));
}
}
}
|
Escrow finalization task, called when finalize() is called./
|
function _finalization() internal {
if (goalReached()) {
_close();
_enableRefunds();
}
_recoverRemainingTokens();
}
| 5,473,458 |
pragma solidity ^0.5.0;
import "./UsingTellor.sol";
/**
* @title Optimistic
* This contracts allows users to use Tellor as a fallback oracle. It allows two parties to centrally
* enter the data used to settle a contract but allows either party to dispute the data. If a dispute is
* initiated their contract will settle to Tellor's value.
*/
contract Optimistic is UsingTellor {
mapping(uint256 => bool) public isValue; //mapping for timestamp to bool where it's true if the value as been set
mapping(uint256 => uint256) valuesByTimestamp; //mapping of timestamp to value
mapping(uint256 => bool) public disputedValues; //maping of timestamp to bool where it's true if the value has been disputed
mapping(uint256 => uint256[]) public requestIdsIncluded; //mapping of timestamp to requestsId's to include
// struct infoForTimestamp {
// bool isValue;
// uint valuesByTimestamp;
// bool disputedValues;
// uint[] requestIdsIncluded;
// }
// mapping(uint => infoForTimestamp) public infoForTimestamps;//mapping timestampt to InfoForTimestamp struct
uint256[] timestamps; //timestamps with values
uint256[] requestIds;
uint256[] disputedValuesArray;
uint256 public granularity;
uint256 public disputeFee; //In Tributes
uint256 public disputePeriod;
event NewValueSet(uint256 indexed _timestamp, uint256 _value);
event ValueDisputed(address _disputer, uint256 _timestamp, uint256 _value);
event TellorValuePlaced(uint256 _timestamp, uint256 _value);
/*Constructor*/
/**
* @dev This constructor function is used to pass variables to the UserContract's constructor and set several variables
* the variables for the Optimistic.sol constructor come for the Reader.Constructor function.
* @param _userContract address for UserContract
* @param _disputeFeeRequired the fee to dispute the optimistic price(price sumbitted by known trusted party)
* @param _disputePeriod is the time frame a value can be disputed after being imputed
* @param _requestIds are the requests Id's on the Tellor System corresponding to the data types used on this contract.
* It is recommended to use several requestId's that pull from several API's. If requestsId's don't exist in the Tellor
* System be sure to create some.
* @param _granularity is the amount of decimals desired on the requested value
*/
constructor(address _userContract, uint256 _disputeFeeRequired, uint256 _disputePeriod, uint256[] memory _requestIds, uint256 _granularity)
public
UsingTellor(_userContract)
{
disputeFee = _disputeFeeRequired;
disputePeriod = _disputePeriod;
granularity = _granularity;
requestIds = _requestIds;
}
/*Functions*/
/**
* @dev allows contract owner, a centralized party to enter value
* @param _timestamp is the timestamp for the value
* @param _value is the value for the timestamp specified
*/
function setValue(uint256 _timestamp, uint256 _value) external {
//Only allows owner to set value
require(msg.sender == owner, "Sender is not owner");
//Checks that no value has already been set for the timestamp
require(getIsValue(_timestamp) == false, "Timestamp is already set");
//sets timestamp
valuesByTimestamp[_timestamp] = _value;
//sets isValue to true once value is set
isValue[_timestamp] = true;
//adds timestamp to the timestamps array
timestamps.push(_timestamp);
//lets the network know a new timestamp and value have been added
emit NewValueSet(_timestamp, _value);
}
/**
* @dev allows user to initiate dispute on the value of the specified timestamp
* @param _timestamp is the timestamp for the value to be disputed
*/
function disputeOptimisticValue(uint256 _timestamp) external payable {
require(msg.value >= disputeFee, "Value is below dispute fee");
//require that isValue for the timestamp being disputed to exist/be true
require(isValue[_timestamp], "Value for the timestamp being disputed doesn't exist");
// assert disputePeriod is still open
require(now - (now % granularity) <= _timestamp + disputePeriod, "Dispute period is closed");
//set the disputValues for the disputed timestamp to true
disputedValues[_timestamp] = true;
//add the disputed timestamp to the diputedValues array
disputedValuesArray.push(_timestamp);
emit ValueDisputed(msg.sender, _timestamp, valuesByTimestamp[_timestamp]);
}
/**
* @dev This function gets the Tellor requestIds values for the disputed timestamp. It averages the values on the
* requestsIds and replaces the value set by the contract owner, centralized party.
* @param _timestamp to get Tellor data from
* @return uint of new value and true if it was able to get Tellor data
*/
function getTellorValues(uint256 _timestamp) public returns (uint256 _value, bool _didGet) {
//We need to get the tellor value within the granularity. If no Tellor value is available...what then? Simply put no Value?
//No basically, the dispute period for anyValue is within the granularity
TellorMaster _tellor = TellorMaster(tellorUserContract.tellorStorageAddress());
Tellor _tellorCore = Tellor(tellorUserContract.tellorStorageAddress());
uint256 _retrievedTimestamp;
uint256 _initialBalance = _tellor.balanceOf(address(this)); //Checks the balance of Tellor Tributes on this contract
//Loops through all the Tellor requestsId's initially(in the constructor) associated with this contract data
for (uint256 i = 1; i <= requestIds.length; i++) {
//Get all values for that requestIds' timestamp
//Check if any is after your given timestamp
//If yes, return that value. If no, then request that Id
(_didGet, _value, _retrievedTimestamp) = getFirstVerifiedDataAfter(i, _timestamp);
if (_didGet) {
uint256 _newTime = _retrievedTimestamp - (_retrievedTimestamp % granularity); //why are we using the mod granularity???
//provides the average of the requests Ids' associated with this price feed
uint256 _newValue = (_value + valuesByTimestamp[_newTime] * requestIdsIncluded[_newTime].length) /
(requestIdsIncluded[_newTime].length + 1);
//Add the new timestamp and value (we don't replace???)
valuesByTimestamp[_newTime] = _newValue;
emit TellorValuePlaced(_newTime, _newValue);
//records the requests Ids included on the price average where all prices came from Tellor requests Ids
requestIdsIncluded[_newTime].push(i); //how do we make sure it's not called twice?
//if the value for the newTime does not exist, then push the value, update the isValue to true
//otherwise if the newTime is under dsipute then update the dispute status to false
// ??? should the else be an "and"
if (isValue[_newTime] == false) {
timestamps.push(_newTime);
isValue[_newTime] = true;
emit NewValueSet(_newTime, _value);
} else if (disputedValues[_newTime] == true) {
disputedValues[_newTime] = false;
}
//otherwise request the ID and split the contracts initial tributes balance to equally tip all
//requests Ids associated with this price feed
} else if (_tellor.balanceOf(address(this)) > requestIds.length) {
//Request Id to be mined by adding to it's tip
_tellorCore.addTip(i, _initialBalance / requestIds.length);
}
}
}
/**
* @dev Allows the contract owner(Tellor) to withdraw ETH from this contract
*/
function withdrawETH() external {
require(msg.sender == owner, "Sender is not owner");
address(owner).transfer(address(this).balance);
}
/**
* @dev Get the first undisputed value after the timestamp specified. This function is used within the getTellorValues
* but can be used on its own.
* @param _timestamp to search the first undisputed value there after
*/
function getFirstUndisputedValueAfter(uint256 _timestamp) public view returns (bool, uint256, uint256 _timestampRetrieved) {
uint256 _count = timestamps.length;
if (_count > 0) {
for (uint256 i = _count; i > 0; i--) {
if (timestamps[i - 1] >= _timestamp && disputedValues[timestamps[i - 1]] == false) {
_timestampRetrieved = timestamps[i - 1];
}
}
if (_timestampRetrieved > 0) {
return (true, getMyValuesByTimestamp(_timestampRetrieved), _timestampRetrieved);
}
}
return (false, 0, 0);
}
/*Getters*/
/**
* @dev Getter function for the value based on the timestamp specified
* @param _timestamp to retreive value from
*/
function getMyValuesByTimestamp(uint256 _timestamp) public view returns (uint256 value) {
return valuesByTimestamp[_timestamp];
}
/**
* @dev Getter function for the number of RequestIds associated with a timestamp, based on the timestamp specified
* @param _timestamp to retreive number of requestIds
* @return uint count of number of values for the spedified timestamp
*/
function getNumberOfValuesPerTimestamp(uint256 _timestamp) external view returns (uint256) {
return requestIdsIncluded[_timestamp].length;
}
/**
* @dev Checks to if a value exists for the specifived timestamp
* @param _timestamp to verify
* @return ture if it exists
*/
function getIsValue(uint256 _timestamp) public view returns (bool) {
return isValue[_timestamp];
}
/**
* @dev Getter function for latest value available
* @return latest value available
*/
function getCurrentValue() external view returns (uint256) {
require(timestamps.length > 0, "Timestamps' length is 0");
return getMyValuesByTimestamp(timestamps[timestamps.length - 1]);
}
/**
* @dev Getter function for the timestamps available
* @return uint array of timestamps available
*/
function getTimestamps() external view returns (uint256[] memory) {
return timestamps;
}
/**
* @dev Getter function for the requests Ids' from Tellor associated with this price feed
* @return uint array of requests Ids'
*/
function getRequestIds() external view returns (uint256[] memory) {
return requestIds;
}
/**
* @dev Getter function for the requests Ids' from Tellor associated with this price feed
* at the specified timestamp. This only gets populated after a dispute is initiated and the
* function getTellorValues is ran.
* @param _timestamp to retreive the requestIds
* @return uint array of requests Ids' included in the calcluation of the value
*/
function getRequestIdsIncluded(uint256 _timestamp) external view returns (uint256[] memory) {
return requestIdsIncluded[_timestamp];
}
/**
* @dev Getter function for the number of disputed values
* @return uint count of number of values for the spedified timestamp
*/
function getNumberOfDisputedValues() external view returns (uint256) {
return disputedValuesArray.length;
}
/**
* @dev Getter function for all disputed values
* @return the array with all values under dispute
*/
function getDisputedValues() external view returns (uint256[] memory) {
return disputedValuesArray;
}
/**
* @dev This checks if the value for the specified timestamp is under dispute
* @param _timestamp to check if it is under dispute
* @return true if it is under dispute
*/
function isDisputed(uint256 _timestamp) external view returns (bool) {
return disputedValues[_timestamp];
}
/**
* @dev Getter function for the dispute value by index
* @return the value
*/
function getDisputedValueByIndex(uint256 _index) external view returns (uint256) {
return disputedValuesArray[_index];
}
}
|
Getter function for the number of RequestIds associated with a timestamp, based on the timestamp specified _timestamp to retreive number of requestIds return uint count of number of values for the spedified timestamp/
|
function getNumberOfValuesPerTimestamp(uint256 _timestamp) external view returns (uint256) {
return requestIdsIncluded[_timestamp].length;
}
| 12,965,509 |
./full_match/4/0xDcfB36e1D0B47FCa2Dc18036E3BDc5Ce26D71e1e/sources/tenderly/project/Treasury.sol
|
owner can withdraw ERC20 token to desired address _token uint _destination address _amount uint/
|
function withdraw(
address _token,
address _destination,
uint _amount
) external onlyOwner {
require(_destination != address(0), "dest = zero address");
IERC20(_token).safeTransfer(_destination, _amount);
emit Withdraw(_token, _destination, _amount);
}
| 12,497,986 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
import "./comm/Ownable.sol";
import "./comm/SafeMath.sol";
import "./comm/IERC20.sol";
import "./comm/SafeERC20.sol";
import "./comm/ReentrancyGuard.sol";
interface IStrategy {
function sharesTotal() external view returns(uint256);
function wantTotal() external view returns(uint256);
function getTotal() external view returns(uint256, uint256);
function deposit(uint256 amount_) external returns(uint256);
function withdraw(address user_, uint256 amount_, uint256 feeRate_) external returns(uint256);
}
interface IStrategyBNB {
function deposit(uint256 amount_) external payable returns(uint256);
}
interface IVeMobox {
function booster(address user_, uint256 totalShare_, uint256 wantShare_, address strategy_) external view returns(uint256);
}
interface IMoMoMinter {
function addBox(address to_, uint256 amount_) external;
}
interface IKeyToken {
function mint(address dest_, uint256 amount_) external;
}
contract MoboxFarm is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Staked(address indexed user, uint256 indexed pIndex, uint256 amount);
event Withdrawn(address indexed user, uint256 indexed pIndex, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardRateChange(uint256 newRate);
event AllocPointChange(uint256 indexed poolIndex, uint256 allocPoint, uint256 totalAllocPoint);
struct UserInfo {
uint128 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of KEYs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.workingBalance * pool.rewardPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `rewardPerShare` (and `lastRewardTime`) gets updated
// 2. User receives the pending reward sent to his/her address
// 3. User's `workingBalance` gets updated
// 4. User's `rewardDebt` gets updated
uint128 workingBalance; // Key, workingBalance = wantShares * mining bonus
uint128 wantShares; // How many wantShares the user has get by LP Token provider.
uint64 gracePeriod; // timestamp of that users can receive the staked LP/Token without deducting the transcation fee
uint64 lastDepositBlock; // the blocknumber of the user's last deposit
}
struct PoolInfo {
address wantToken; // Address of LP token/token contract
uint32 allocPoint; // 1x = 100, 0.5x = 50
uint64 lastRewardTime; // Last unixtimestamp that CAKEs distribution occurs.
uint128 rewardPerShare; // Accumulated KEYs per share, times 1e12. See below
uint128 workingSupply; // Total mining points
address strategy; // Strategy
}
address constant public BNB = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;
address public keyToken;
address public momoMinter; // The contract for openning momo chests
address public rewardMgr; // 'Key' mining rate management
address public veMobox; // 'veCrv', mining weight
address public rewardHelper; // If the user encounters a situation where there is not enough gas to receive the reward, the 'rewardHelper' can send the user's unclaimed 'Key' to the user
uint256 public rewardRate; // rewardRate per second for minning
uint256 public rewardStart; // reward start time
uint256 public totalAllocPoint; // total allocPoint for all pools
PoolInfo[] public poolInfoArray;
mapping (uint256 => mapping (address => UserInfo)) _userInfoMap;
mapping (address => uint256) public rewardStore; // Store rewards that the users did not withdraw
function init(address key_, address rewardMgr_) external onlyOwner {
require(keyToken == address(0) && rewardMgr == address(0), "only set once");
require(key_ != address(0) && rewardMgr_ != address(0), "invalid param");
keyToken = key_;
rewardMgr = rewardMgr_;
IERC20(keyToken).safeApprove(rewardMgr_, uint256(-1));
// Discard the first pool
if (poolInfoArray.length == 0) {
poolInfoArray.push(PoolInfo(address(0), 0, 0, 0, 0, address(0)));
}
emit RewardRateChange(0);
}
function setRewardHelper(address addr_) external onlyOwner {
require(addr_ != address(0), "invalid param");
rewardHelper = addr_;
}
function setMoMoMinter(address addr_) external nonReentrant onlyOwner {
require(keyToken != address(0) && addr_ != address(0), "invalid param");
if (momoMinter != address(0)) {
require(IERC20(keyToken).approve(momoMinter, 0), "approve fail");
}
momoMinter = addr_;
// When the user exchanges the key for the box, 'momoMinter' will burn the specified number of keys. This method can be used to save gas, see 'getChestBox'
IERC20(keyToken).safeApprove(momoMinter, uint256(-1));
}
modifier onlyRewardMgr() {
require(_msgSender() == rewardMgr, "not rewardMgr");
_;
}
// Add a new lp to the pool. Can only be called by the rewardMgr
function addPool(address wantToken_, uint256 allocPoint_, address strategy_) external nonReentrant onlyRewardMgr {
require(allocPoint_ <= 10000 && strategy_ != address(0), "invalid param");
// solium-disable-next-line
if (block.timestamp > rewardStart) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(allocPoint_);
uint256 poolIndex = poolInfoArray.length;
poolInfoArray.push(PoolInfo({
wantToken: wantToken_,
allocPoint: SafeMathExt.safe32(allocPoint_),
lastRewardTime: uint64(block.timestamp),
rewardPerShare: 0,
workingSupply: 0,
strategy: strategy_
}));
if (wantToken_ != BNB) {
IERC20(wantToken_).safeApprove(strategy_, uint256(-1));
}
emit AllocPointChange(poolIndex, allocPoint_, totalAllocPoint);
}
function setPool(uint256 pIndex_, address wantToken_, uint256 allocPoint_) external nonReentrant onlyRewardMgr {
PoolInfo storage pool = poolInfoArray[pIndex_];
// wantToken_ For verification only
require(wantToken_ != address(0) && pool.wantToken == wantToken_, "invalid pool");
require(allocPoint_ >= 0 && allocPoint_ <= 10000, "invalid param");
massUpdatePools();
totalAllocPoint = totalAllocPoint.sub(uint256(pool.allocPoint)).add(allocPoint_);
pool.allocPoint = SafeMathExt.safe32(allocPoint_);
emit AllocPointChange(pIndex_, allocPoint_, totalAllocPoint);
}
function getMaxPoolIndex() external view returns(uint256) {
return poolInfoArray.length.sub(1);
}
function initReward(uint256 rewardRate_, uint256 rewardStart_) external onlyRewardMgr {
require(rewardStart == 0, "only set once");
// solium-disable-next-line
uint256 tmNow = block.timestamp;
require(rewardRate_ > 0 && rewardRate_ <= 2e18 && rewardStart_ > tmNow, "invalid param");
rewardStart = rewardStart_;
rewardRate = rewardRate_;
emit RewardRateChange(rewardRate);
}
function changeRewardRate(uint256 rewardRate_) external onlyRewardMgr {
require(rewardRate_ > 0 && rewardRate_ <= 2e18, "invalid param");
// solium-disable-next-line
if (block.timestamp > rewardStart) {
massUpdatePools();
}
rewardRate = rewardRate_;
emit RewardRateChange(rewardRate);
}
function setVeMobox(address veMobox_) external onlyRewardMgr {
require(veMobox == address(0), "only set once");
veMobox = veMobox_;
}
function massUpdatePools() public {
uint256 length = poolInfoArray.length;
for (uint256 poolIndex = 0; poolIndex < length; ++poolIndex) {
updatePool(poolIndex);
}
}
function updatePool(uint256 pIndex_) public {
PoolInfo storage pool = poolInfoArray[pIndex_];
// solium-disable-next-line
uint256 blockTimeStamp = block.timestamp;
if (pIndex_ <= 0 || blockTimeStamp <= rewardStart || blockTimeStamp <= pool.lastRewardTime) {
return;
}
if (pool.workingSupply == 0) {
pool.lastRewardTime = SafeMathExt.safe64(blockTimeStamp);
return;
}
uint256 rewardTime = blockTimeStamp.sub(Math.max(uint256(pool.lastRewardTime), rewardStart));
uint256 keyReward = rewardTime.mul(rewardRate).mul(uint256(pool.allocPoint)).div(totalAllocPoint);
IKeyToken(keyToken).mint(address(this), keyReward);
pool.rewardPerShare = SafeMathExt.safe128(
uint256(pool.rewardPerShare).add(keyReward.mul(1e12).div(uint256(pool.workingSupply)))
);
pool.lastRewardTime = SafeMathExt.safe64(blockTimeStamp);
}
// View function to see pending KEYs on frontend.
function pendingKey(uint256 pIndex_, address user_) external view returns(uint256) {
// solium-disable-next-line
uint256 blockTimeStamp = block.timestamp;
if (pIndex_ <= 0 || blockTimeStamp <= rewardStart) {
return 0;
}
PoolInfo storage pool = poolInfoArray[pIndex_];
if (blockTimeStamp < pool.lastRewardTime) {
return 0;
}
UserInfo storage user = _userInfoMap[pIndex_][user_];
if (pool.workingSupply == 0 || user.workingBalance == 0) {
return 0;
}
uint256 rewardPerShare = uint256(pool.rewardPerShare);
uint256 rewardTime = blockTimeStamp.sub(Math.max(uint256(pool.lastRewardTime), rewardStart));
rewardPerShare = rewardPerShare.add(
rewardTime.mul(rewardRate).mul(uint256(pool.allocPoint)).div(totalAllocPoint).mul(1e12).div(uint256(pool.workingSupply))
);
return uint256(user.workingBalance).mul(rewardPerShare).div(1e12).sub(user.rewardDebt);
}
function getUserInfo(uint256 pIndex_, address user_)
external
view
returns(
address wantToken,
uint256 wantShares,
uint256 wantAmount,
uint256 workingBalance,
uint256 gracePeriod
)
{
if (pIndex_ > 0) {
PoolInfo storage pool = poolInfoArray[pIndex_];
UserInfo storage user = _userInfoMap[pIndex_][user_];
wantToken = pool.wantToken;
wantShares = uint256(user.wantShares);
workingBalance = uint256(user.workingBalance);
gracePeriod = uint256(user.gracePeriod);
uint256 wantTotal;
uint256 shareTotal;
(wantTotal, shareTotal) = IStrategy(pool.strategy).getTotal();
if (shareTotal > 0) {
wantAmount = wantShares.mul(wantTotal).div(shareTotal);
} else {
wantAmount = 0;
}
}
}
function _boostWorkingBalance(address strategy_, address user_, uint256 sharesUser_) internal view returns(uint256) {
if (veMobox == address(0)) {
return 100;
}
uint256 sharesTotal = IStrategy(strategy_).sharesTotal();
return IVeMobox(veMobox).booster(user_, sharesTotal, sharesUser_, strategy_);
}
function _calcGracePeriod(uint256 gracePeriod, uint256 shareNew, uint256 shareAdd) internal view returns(uint256) {
uint256 blockTime = block.timestamp;
if (gracePeriod == 0) {
// solium-disable-next-line
return blockTime.add(180 days);
}
uint256 depositSec;
// solium-disable-next-line
if (blockTime >= gracePeriod) {
depositSec = 180 days;
return blockTime.add(depositSec.mul(shareAdd).div(shareNew));
} else {
// solium-disable-next-line
depositSec = uint256(180 days).sub(gracePeriod.sub(blockTime));
return gracePeriod.add(depositSec.mul(shareAdd).div(shareNew));
}
}
function _calcFeeRateByGracePeriod(uint256 gracePeriod) internal view returns(uint256) {
// solium-disable-next-line
if (block.timestamp >= gracePeriod) {
return 0;
}
// solium-disable-next-line
uint256 leftSec = gracePeriod.sub(block.timestamp);
if (leftSec < 90 days) {
return 10; // 0.1%
} else if (leftSec < 150 days) {
return 20; // 0.2%
} else if (leftSec < 166 days) {
return 30; // 0.3%
} else if (leftSec < 173 days) {
return 40; // 0.4%
} else {
return 50; // 0.5%
}
}
function _depositFor(uint256 pIndex_, address lpFrom_, address lpFor_, uint256 amount_) internal {
require(pIndex_ > 0 && amount_ > 0, "invalid param");
updatePool(pIndex_);
PoolInfo storage pool = poolInfoArray[pIndex_];
UserInfo storage user = _userInfoMap[pIndex_][lpFor_];
if (pool.wantToken != BNB) {
IERC20(pool.wantToken).safeTransferFrom(lpFrom_, address(this), amount_);
}
uint256 workingBalance = uint256(user.workingBalance);
if (workingBalance > 0) {
uint256 pending = workingBalance.mul(uint256(pool.rewardPerShare)).div(1e12).sub(uint256(user.rewardDebt));
if (pending > 0) {
rewardStore[lpFor_] = pending.add(rewardStore[lpFor_]);
}
}
// The return value of 'deposit' is the latest 'share' value
uint256 wantSharesOld = uint256(user.wantShares);
uint256 shareAdd;
if (pool.wantToken == BNB) {
shareAdd = IStrategyBNB(pool.strategy).deposit{value: amount_}(amount_);
} else {
shareAdd = IStrategy(pool.strategy).deposit(amount_);
}
user.wantShares = SafeMathExt.safe128(wantSharesOld.add(shareAdd));
uint256 boost = _boostWorkingBalance(pool.strategy, lpFor_, uint256(user.wantShares));
require(boost >= 100 && boost <= 300, "invalid boost");
uint256 oldWorkingBalance = uint256(user.workingBalance);
uint256 newWorkingBalance = uint256(user.wantShares).mul(boost).div(100);
user.workingBalance = SafeMathExt.safe128(newWorkingBalance);
pool.workingSupply = SafeMathExt.safe128(uint256(pool.workingSupply).sub(oldWorkingBalance).add(newWorkingBalance));
user.rewardDebt = SafeMathExt.safe128(newWorkingBalance.mul(uint256(pool.rewardPerShare)).div(1e12));
user.gracePeriod = SafeMathExt.safe64(_calcGracePeriod(user.gracePeriod, uint256(user.wantShares), shareAdd));
user.lastDepositBlock = SafeMathExt.safe64(block.number);
emit Staked(lpFor_, pIndex_, amount_);
}
// Deposit LP tokens/BEP20 tokens to MOBOXFarm for KEY allocation.
function deposit(uint256 pIndex_, uint256 amount_) external nonReentrant {
_depositFor(pIndex_, msg.sender, msg.sender, amount_);
}
// Deposit BNB to MOBOXFarm for KEY allocation.
function deposit(uint256 pIndex_) external payable nonReentrant {
_depositFor(pIndex_, msg.sender, msg.sender, msg.value);
}
// Deposit LP tokens/BEP20 tokens to MOBOXFarm for KEY allocation.
function depositFor(address lpFor_, uint256 pIndex_, uint256 amount_) external nonReentrant {
_depositFor(pIndex_, msg.sender, lpFor_, amount_);
}
// Deposit BNB to MOBOXFarm for KEY allocation.
function depositFor(address lpFor_, uint256 pIndex_) external payable nonReentrant {
_depositFor(pIndex_, msg.sender, lpFor_, msg.value);
}
// Stake CAKE tokens to MoboxFarm
function withdraw(uint256 pIndex_, uint256 amount_) external nonReentrant {
require(pIndex_ > 0 || amount_ > 0, "invalid param");
updatePool(pIndex_);
PoolInfo storage pool = poolInfoArray[pIndex_];
UserInfo storage user = _userInfoMap[pIndex_][msg.sender];
uint256 wantShares = uint256(user.wantShares);
require(wantShares > 0, "insufficient wantShares");
require(block.number > uint256(user.lastDepositBlock).add(2), "withdraw in 3 blocks");
uint256[2] memory shareTotals; // 0: wantTotal, 1: shareTotal
(shareTotals[0], shareTotals[1]) = IStrategy(pool.strategy).getTotal();
require(shareTotals[1] >= wantShares, "invalid share");
uint256 pending = uint256(user.workingBalance).mul(uint256(pool.rewardPerShare)).div(1e12).sub(uint256(user.rewardDebt));
uint256 wantWithdraw = wantShares.mul(shareTotals[0]).div(shareTotals[1]);
if (wantWithdraw > amount_) {
wantWithdraw = amount_;
}
require(wantWithdraw > 0, "insufficient wantAmount");
uint256 feeRate = _calcFeeRateByGracePeriod(uint256(user.gracePeriod));
uint256 shareSub = IStrategy(pool.strategy).withdraw(msg.sender, wantWithdraw, feeRate);
user.wantShares = SafeMathExt.safe128(uint256(user.wantShares).sub(shareSub));
uint256 boost = _boostWorkingBalance(pool.strategy, msg.sender, uint256(user.wantShares));
require(boost >= 100 && boost <= 300, "invalid boost");
uint256 oldWorkingBalance = uint256(user.workingBalance);
uint256 newWorkingBalance = uint256(user.wantShares).mul(boost).div(100);
user.workingBalance = SafeMathExt.safe128(newWorkingBalance);
// Set 'rewardDebt' first and then increase 'rewardStore'
user.rewardDebt = SafeMathExt.safe128(newWorkingBalance.mul(uint256(pool.rewardPerShare)).div(1e12));
if (pending > 0) {
rewardStore[msg.sender] = pending.add(rewardStore[msg.sender]);
}
// If user withdraws all the LPs, then gracePeriod is cleared
if (user.wantShares == 0) {
user.gracePeriod = 0;
}
pool.workingSupply = SafeMathExt.safe128(uint256(pool.workingSupply).sub(oldWorkingBalance).add(newWorkingBalance));
emit Staked(msg.sender, pIndex_, amount_);
}
function getReward(uint256[] memory pIndexArray_) external nonReentrant {
_getRward(pIndexArray_, msg.sender);
uint256 keyAmount = rewardStore[msg.sender];
if (keyAmount > 0) {
rewardStore[msg.sender] = 0;
IERC20(keyToken).safeTransfer(msg.sender, keyAmount);
emit RewardPaid(msg.sender, keyAmount);
}
}
function updateRewardByVeMobox(uint256 poolIndex_, address user_) external {
require(msg.sender == veMobox, "invalid caller");
require(poolIndex_ > 0 && poolIndex_ < poolInfoArray.length, "invalid param");
uint256[] memory pIndexArray = new uint256[](1);
pIndexArray[0] = poolIndex_;
_getRward(pIndexArray, user_);
}
function getRewardFor(uint256[] memory pIndexArray_, address user_) external {
require(msg.sender == rewardHelper, "not helper");
_getRward(pIndexArray_, user_);
uint256 keyAmount = rewardStore[user_];
if (keyAmount > 0) {
rewardStore[user_] = 0;
IERC20(keyToken).safeTransfer(user_, keyAmount);
emit RewardPaid(user_, keyAmount);
}
}
function _getRward(uint256[] memory pIndexArray_, address user_) internal {
require(pIndexArray_.length > 0 && user_ != address(0), "invalid param");
uint256 poolIndex;
uint256 keyAmount = rewardStore[user_];
for (uint256 i = 0; i < pIndexArray_.length; ++i) {
poolIndex = pIndexArray_[i];
UserInfo storage user = _userInfoMap[poolIndex][user_];
if (user.workingBalance <= 0) {
continue;
}
updatePool(poolIndex);
PoolInfo storage pool = poolInfoArray[poolIndex];
uint256 workingBalance = uint256(user.workingBalance);
uint256 pending = workingBalance.mul(uint256(pool.rewardPerShare)).div(1e12).sub(uint256(user.rewardDebt));
// Need to check the change of boost rate
if (veMobox != address(0)) {
uint256 boost = _boostWorkingBalance(pool.strategy, user_, uint256(user.wantShares));
require(boost >= 100 && boost <= 300, "invalid boost");
uint256 oldWorkingBalance = workingBalance;
uint256 newWorkingBalance = uint256(user.wantShares).mul(boost).div(100);
if (oldWorkingBalance != newWorkingBalance) {
user.workingBalance = SafeMathExt.safe128(newWorkingBalance);
pool.workingSupply = SafeMathExt.safe128(uint256(pool.workingSupply).sub(oldWorkingBalance).add(newWorkingBalance));
workingBalance = newWorkingBalance;
}
}
user.rewardDebt = SafeMathExt.safe128(workingBalance.mul(uint256(pool.rewardPerShare)).div(1e12));
keyAmount = keyAmount.add(pending);
}
rewardStore[user_] = keyAmount;
}
function getChestBox(uint256[] memory pIndexArray_, uint256 boxAmount_) external nonReentrant {
require(boxAmount_ > 0 && boxAmount_ < 10000000 && momoMinter != address(0), "invalid param");
if (rewardStore[msg.sender] < boxAmount_.mul(1e18)) {
_getRward(pIndexArray_, msg.sender);
}
uint256 keyAmount = rewardStore[msg.sender];
uint256 needKey = boxAmount_.mul(1e18);
if (keyAmount >= needKey) {
rewardStore[msg.sender] = keyAmount.sub(needKey);
IMoMoMinter(momoMinter).addBox(msg.sender, boxAmount_);
emit RewardPaid(msg.sender, needKey);
}
}
}
|
solium-disable-next-line
|
function changeRewardRate(uint256 rewardRate_) external onlyRewardMgr {
require(rewardRate_ > 0 && rewardRate_ <= 2e18, "invalid param");
if (block.timestamp > rewardStart) {
massUpdatePools();
}
rewardRate = rewardRate_;
emit RewardRateChange(rewardRate);
}
| 5,348,553 |
./full_match/5/0x14E961a404B2eC4800939a1d5E9806A622bC3F02/sources/contracts/Crowdfunder.sol
|
is everything okay?
|
function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256){
Campaign storage campaign = campaigns[numberOfCampaigns];
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future.");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
| 11,609,372 |
./partial_match/1/0x2Ec62769e99b382fC6308e840762a039f6507845/sources/ERC20Token.sol
|
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). account The account whose tokens will be burnt. value The amount that will be burnt./
|
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(value));
}
| 3,927,095 |
//Address: 0xc2dc0c3054dB1740a9153B5D54911dB728672EAa
//Contract name: ZminePrivateSale
//Balance: 0 Ether
//Verification Date: 4/2/2018
//Transacion Count: 192
// CODE STARTS HERE
pragma solidity 0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Authorizable
* @dev The Authorizable contract has authorized addresses, and provides basic authorization control
* functions, this simplifies the implementation of "multiple user permissions".
*/
contract Authorizable is Ownable {
mapping(address => bool) public authorized;
event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization);
/**
* @dev The Authorizable constructor sets the first `authorized` of the contract to the sender
* account.
*/
function Authorizable() public {
authorize(msg.sender);
}
/**
* @dev Throws if called by any account other than the authorized.
*/
modifier onlyAuthorized() {
require(authorized[msg.sender]);
_;
}
/**
* @dev Allows
* @param _address The address to change authorization.
*/
function authorize(address _address) public onlyOwner {
require(!authorized[_address]);
emit AuthorizationSet(_address, true);
authorized[_address] = true;
}
/**
* @dev Disallows
* @param _address The address to change authorization.
*/
function deauthorize(address _address) public onlyOwner {
require(authorized[_address]);
emit AuthorizationSet(_address, false);
authorized[_address] = false;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title PrivateSaleExchangeRate interface
*/
contract PrivateSaleExchangeRate {
uint256 public rate;
uint256 public timestamp;
event UpdateUsdEthRate(uint _rate);
function updateUsdEthRate(uint _rate) public;
function getTokenAmount(uint256 _weiAmount) public view returns (uint256);
}
/**
* @title Whitelist interface
*/
contract Whitelist {
mapping(address => bool) whitelisted;
event AddToWhitelist(address _beneficiary);
event RemoveFromWhitelist(address _beneficiary);
function isWhitelisted(address _address) public view returns (bool);
function addToWhitelist(address _beneficiary) public;
function removeFromWhitelist(address _beneficiary) public;
}
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
// Crowdsale
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
PrivateSaleExchangeRate public rate;
// Amount of wei raised
uint256 public weiRaised;
// Amount of wei raised (token)
uint256 public tokenRaised;
/**
* 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(PrivateSaleExchangeRate _rate, address _wallet, ERC20 _token) public {
require(_rate.rate() > 0);
require(_token != address(0));
require(_wallet != address(0));
rate = _rate;
token = _token;
wallet = _wallet;
}
// -----------------------------------------
// 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;
// calculate token amount to be created
uint256 tokenAmount = _getTokenAmount(weiAmount);
_preValidatePurchase(_beneficiary, weiAmount, tokenAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
tokenRaised = tokenRaised.add(tokenAmount);
_processPurchase(_beneficiary, tokenAmount);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// 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, uint256 _tokenAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount > 0);
require(_tokenAmount > 0);
}
/**
* @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 {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _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 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 {
// optional override
}
/**
* @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 rate.getTokenAmount(_weiAmount);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_closingTime >= now);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is opened.
* @return Whether crowdsale period has elapsed
*/
function hasOpening() public view returns (bool) {
return (now >= openingTime && now <= closingTime);
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
}
}
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
address public tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
function AllowanceCrowdsale(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
/**
* @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);
}
}
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public minWei;
uint256 public capToken;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _capToken Max amount of token to be contributed
*/
function CappedCrowdsale(uint256 _capToken, uint256 _minWei) public {
require(_minWei > 0);
require(_capToken > 0);
minWei = _minWei;
capToken = _capToken;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
if(tokenRaised >= capToken) return true;
uint256 minTokens = rate.getTokenAmount(minWei);
if(capToken - tokenRaised <= minTokens) return true;
return false;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
require(_weiAmount >= minWei);
require(tokenRaised.add(_tokenAmount) <= capToken);
}
}
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract WhitelistedCrowdsale is Crowdsale {
using SafeMath for uint256;
// Only KYC investor allowed to buy the token
Whitelist public whitelist;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _whitelist whitelist contract
*/
function WhitelistedCrowdsale(Whitelist _whitelist) public {
whitelist = _whitelist;
}
function isWhitelisted(address _address) public view returns (bool) {
return whitelist.isWhitelisted(_address);
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
require(whitelist.isWhitelisted(_beneficiary));
}
}
/**
* @title ClaimedCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract ClaimCrowdsale is Crowdsale, Authorizable {
using SafeMath for uint256;
uint256 divider;
event ClaimToken(address indexed claimant, address indexed beneficiary, uint256 claimAmount);
// Claim remain amount of token
//addressIndices not use index 0
address[] public addressIndices;
// get amount of claim token
mapping(address => uint256) mapAddressToToken;
//get index of addressIndices if = 0 >> not found
mapping(address => uint256) mapAddressToIndex;
// Amount of wei waiting for claim (token)
uint256 public waitingForClaimTokens;
/**
* @dev Constructor, takes token wallet address.
*/
function ClaimCrowdsale(uint256 _divider) public {
require(_divider > 0);
divider = _divider;
addressIndices.push(address(0));
}
/**
* @dev Claim remained token after closed time
*/
function claim(address _beneficiary) public onlyAuthorized {
require(_beneficiary != address(0));
require(mapAddressToToken[_beneficiary] > 0);
// remove from list
uint indexToBeDeleted = mapAddressToIndex[_beneficiary];
require(indexToBeDeleted != 0);
uint arrayLength = addressIndices.length;
// if index to be deleted is not the last index, swap position.
if (indexToBeDeleted < arrayLength-1) {
// swap
addressIndices[indexToBeDeleted] = addressIndices[arrayLength-1];
mapAddressToIndex[addressIndices[indexToBeDeleted]] = indexToBeDeleted;
}
// we can now reduce the array length by 1
addressIndices.length--;
mapAddressToIndex[_beneficiary] = 0;
// deliver token
uint256 _claimAmount = mapAddressToToken[_beneficiary];
mapAddressToToken[_beneficiary] = 0;
waitingForClaimTokens = waitingForClaimTokens.sub(_claimAmount);
emit ClaimToken(msg.sender, _beneficiary, _claimAmount);
_deliverTokens(_beneficiary, _claimAmount);
}
function checkClaimTokenByIndex(uint index) public view returns (uint256){
require(index >= 0);
require(index < addressIndices.length);
return checkClaimTokenByAddress(addressIndices[index]);
}
function checkClaimTokenByAddress(address _beneficiary) public view returns (uint256){
require(_beneficiary != address(0));
return mapAddressToToken[_beneficiary];
}
function countClaimBackers() public view returns (uint256) {
return addressIndices.length-1;
}
function _addToClaimList(address _beneficiary, uint256 _claimAmount) internal {
require(_beneficiary != address(0));
require(_claimAmount > 0);
if(mapAddressToToken[_beneficiary] == 0){
addressIndices.push(_beneficiary);
mapAddressToIndex[_beneficiary] = addressIndices.length-1;
}
waitingForClaimTokens = waitingForClaimTokens.add(_claimAmount);
mapAddressToToken[_beneficiary] = mapAddressToToken[_beneficiary].add(_claimAmount);
}
/**
* @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 {
// To protect our private-sale investors who transfered eth via wallet from exchange.
// Instead of send all tokens amount back, the private-sale contract will send back in small portion of tokens (ppm).
// The full amount of tokens will be send later after the investor has confirmed received amount to us.
uint256 tokenSampleAmount = _tokenAmount.div(divider);
_addToClaimList(_beneficiary, _tokenAmount.sub(tokenSampleAmount));
_deliverTokens(_beneficiary, tokenSampleAmount);
}
}
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
// ZMINE
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
/**
* @title ZminePrivateSale
*/
contract ZminePrivateSale is ClaimCrowdsale
, AllowanceCrowdsale
, CappedCrowdsale
, TimedCrowdsale
, WhitelistedCrowdsale {
using SafeMath for uint256;
/**
* @param _rate Number of token units a buyer gets per wei
* @param _whitelist Allowd address of buyer
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function ZminePrivateSale(PrivateSaleExchangeRate _rate
, Whitelist _whitelist
, uint256 _capToken
, uint256 _minWei
, uint256 _openingTime
, uint256 _closingTime
, address _wallet
, address _tokenWallet
, ERC20 _token
) public
Crowdsale(_rate, _wallet, _token)
ClaimCrowdsale(1000000)
AllowanceCrowdsale(_tokenWallet)
CappedCrowdsale(_capToken, _minWei)
TimedCrowdsale(_openingTime, _closingTime)
WhitelistedCrowdsale(_whitelist)
{
}
function calculateTokenAmount(uint256 _weiAmount) public view returns (uint256) {
return rate.getTokenAmount(_weiAmount);
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokenForSale() public view returns (uint256) {
uint256 allowanceTokenLeft = (token.allowance(tokenWallet, this)).sub(waitingForClaimTokens);
uint256 balanceTokenLeft = (token.balanceOf(tokenWallet)).sub(waitingForClaimTokens);
if(allowanceTokenLeft < balanceTokenLeft) return allowanceTokenLeft;
return balanceTokenLeft;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
require(remainingTokenForSale().sub(_tokenAmount) >= 0);
}
}
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
|
Constructor, takes maximum amount of wei accepted in the crowdsale. _capToken Max amount of token to be contributed/
|
function CappedCrowdsale(uint256 _capToken, uint256 _minWei) public {
require(_minWei > 0);
require(_capToken > 0);
minWei = _minWei;
capToken = _capToken;
}
| 2,529,128 |
./partial_match/1/0x3a4F11cb49Ea0096a7E3B08C4dE19186dbFD71Da/sources/BINANCE.sol
|
Updates `owner` s allowance for `spender` based on spent `amount`. Does not update the allowance amount in case of infinite allowance. Revert if not enough allowance is available. Might emit an {Approval} event./
|
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
| 2,643,594 |
./full_match/80001/0x154E60D979B28FAa17fEfF30fb272892419e3b93/sources/fir.sol
|
--------------NUMBER OF PENDING APPROVALS---------------
|
function calculatePendingApprovals() public{
delete pendingApprovals;
for (uint256 i=1 ; i<nextId ;i++){
if (Complaints[i].valid == true && Complaints[i].isApproved == false){
pendingApprovals.push(Complaints[i].id);
}
}
}
| 9,438,548 |
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
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.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: contracts/EpochTokenLocker.sol
pragma solidity ^0.5.0;
/** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/
contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
}
// File: @gnosis.pm/solidity-data-structures/contracts/libraries/IdToAddressBiMap.sol
pragma solidity ^0.5.0;
library IdToAddressBiMap {
struct Data {
mapping(uint16 => address) idToAddress;
mapping(address => uint16) addressToId;
}
function hasId(Data storage self, uint16 id) public view returns (bool) {
return self.idToAddress[id + 1] != address(0);
}
function hasAddress(Data storage self, address addr) public view returns (bool) {
return self.addressToId[addr] != 0;
}
function getAddressAt(Data storage self, uint16 id) public view returns (address) {
require(hasId(self, id), "Must have ID to get Address");
return self.idToAddress[id + 1];
}
function getId(Data storage self, address addr) public view returns (uint16) {
require(hasAddress(self, addr), "Must have Address to get ID");
return self.addressToId[addr] - 1;
}
function insert(Data storage self, uint16 id, address addr) public returns (bool) {
// Ensure bijectivity of the mappings
if (self.addressToId[addr] != 0 || self.idToAddress[id + 1] != address(0)) {
return false;
}
self.idToAddress[id + 1] = addr;
self.addressToId[addr] = id + 1;
return true;
}
}
// File: @gnosis.pm/solidity-data-structures/contracts/libraries/IterableAppendOnlySet.sol
pragma solidity ^0.5.0;
library IterableAppendOnlySet {
struct Data {
mapping(address => address) nextMap;
address last;
}
function insert(Data storage self, address value) public returns (bool) {
if (contains(self, value)) {
return false;
}
self.nextMap[self.last] = value;
self.last = value;
return true;
}
function contains(Data storage self, address value) public view returns (bool) {
require(value != address(0), "Inserting address(0) is not supported");
return self.nextMap[value] != address(0) || (self.last == value);
}
function first(Data storage self) public view returns (address) {
require(self.last != address(0), "Trying to get first from empty set");
return self.nextMap[address(0)];
}
function next(Data storage self, address value) public view returns (address) {
require(contains(self, value), "Trying to get next of non-existent element");
require(value != self.last, "Trying to get next of last element");
return self.nextMap[value];
}
function size(Data storage self) public view returns (uint256) {
if (self.last == address(0)) {
return 0;
}
uint256 count = 1;
address current = first(self);
while (current != self.last) {
current = next(self, current);
count++;
}
return count;
}
}
// File: @gnosis.pm/util-contracts/contracts/Math.sol
pragma solidity ^0.5.2;
/// @title Math library - Allows calculation of logarithmic and exponential functions
/// @author Alan Lu - <[email protected]>
/// @author Stefan George - <[email protected]>
library GnosisMath {
/*
* Constants
*/
// This is equal to 1 in our calculations
uint public constant ONE = 0x10000000000000000;
uint public constant LN2 = 0xb17217f7d1cf79ac;
uint public constant LOG2_E = 0x171547652b82fe177;
/*
* Public functions
*/
/// @dev Returns natural exponential function value of given x
/// @param x x
/// @return e**x
function exp(int x) public pure returns (uint) {
// revert if x is > MAX_POWER, where
// MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE))
require(x <= 2454971259878909886679);
// return 0 if exp(x) is tiny, using
// MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE))
if (x < -818323753292969962227) return 0;
// Transform so that e^x -> 2^x
x = x * int(ONE) / int(LN2);
// 2^x = 2^whole(x) * 2^frac(x)
// ^^^^^^^^^^ is a bit shift
// so Taylor expand on z = frac(x)
int shift;
uint z;
if (x >= 0) {
shift = x / int(ONE);
z = uint(x % int(ONE));
} else {
shift = x / int(ONE) - 1;
z = ONE - uint(-x % int(ONE));
}
// 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ...
//
// Can generate the z coefficients using mpmath and the following lines
// >>> from mpmath import mp
// >>> mp.dps = 100
// >>> ONE = 0x10000000000000000
// >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7)))
// 0xb17217f7d1cf79ab
// 0x3d7f7bff058b1d50
// 0xe35846b82505fc5
// 0x276556df749cee5
// 0x5761ff9e299cc4
// 0xa184897c363c3
uint zpow = z;
uint result = ONE;
result += 0xb17217f7d1cf79ab * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x3d7f7bff058b1d50 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe35846b82505fc5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x276556df749cee5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x5761ff9e299cc4 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xa184897c363c3 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xffe5fe2c4586 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x162c0223a5c8 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1b5253d395e * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e4cf5158b * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e8cac735 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1c3bd650 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1816193 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x131496 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe1b7 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x9c7 * zpow / ONE;
if (shift >= 0) {
if (result >> (256 - shift) > 0) return (2 ** 256 - 1);
return result << shift;
} else return result >> (-shift);
}
/// @dev Returns natural logarithm value of given x
/// @param x x
/// @return ln(x)
function ln(uint x) public pure returns (int) {
require(x > 0);
// binary search for floor(log2(x))
int ilog2 = floorLog2(x);
int z;
if (ilog2 < 0) z = int(x << uint(-ilog2));
else z = int(x >> uint(ilog2));
// z = x * 2^-⌊log₂x⌋
// so 1 <= z < 2
// and ln z = ln x - ⌊log₂x⌋/log₂e
// so just compute ln z using artanh series
// and calculate ln x from that
int term = (z - int(ONE)) * int(ONE) / (z + int(ONE));
int halflnz = term;
int termpow = term * term / int(ONE) * term / int(ONE);
halflnz += termpow / 3;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 5;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 7;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 9;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 11;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 13;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 15;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 17;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 19;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 21;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 23;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 25;
return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz;
}
/// @dev Returns base 2 logarithm value of given x
/// @param x x
/// @return logarithmic value
function floorLog2(uint x) public pure returns (int lo) {
lo = -64;
int hi = 193;
// I use a shift here instead of / 2 because it floors instead of rounding towards 0
int mid = (hi + lo) >> 1;
while ((lo + 1) < hi) {
if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid;
else lo = mid;
mid = (hi + lo) >> 1;
}
}
/// @dev Returns maximum of an array
/// @param nums Numbers to look through
/// @return Maximum number
function max(int[] memory nums) public pure returns (int maxNum) {
require(nums.length > 0);
maxNum = -2 ** 255;
for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i];
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b) internal pure returns (bool) {
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b) internal pure returns (bool) {
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b) internal pure returns (uint) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b) internal pure returns (uint) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b) internal pure returns (uint) {
require(safeToMul(a, b));
return a * b;
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(int a, int b) internal pure returns (bool) {
return (b >= 0 && a + b >= a) || (b < 0 && a + b < a);
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(int a, int b) internal pure returns (bool) {
return (b >= 0 && a - b <= a) || (b < 0 && a - b > a);
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(int a, int b) internal pure returns (bool) {
return (b == 0) || (a * b / b == a);
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(int a, int b) internal pure returns (int) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(int a, int b) internal pure returns (int) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(int a, int b) internal pure returns (int) {
require(safeToMul(a, b));
return a * b;
}
}
// File: @gnosis.pm/util-contracts/contracts/Token.sol
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
pragma solidity ^0.5.2;
/// @title Abstract token contract - Functions to be implemented by token contracts
contract Token {
/*
* Events
*/
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
/*
* Public functions
*/
function transfer(address to, uint value) public returns (bool);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
function balanceOf(address owner) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function totalSupply() public view returns (uint);
}
// File: @gnosis.pm/util-contracts/contracts/Proxy.sol
pragma solidity ^0.5.2;
/// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy.
/// @author Alan Lu - <[email protected]>
contract Proxied {
address public masterCopy;
}
/// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <[email protected]>
contract Proxy is Proxied {
/// @dev Constructor function sets address of master copy contract.
/// @param _masterCopy Master copy address.
constructor(address _masterCopy) public {
require(_masterCopy != address(0), "The master copy is required");
masterCopy = _masterCopy;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
function() external payable {
address _masterCopy = masterCopy;
assembly {
calldatacopy(0, 0, calldatasize)
let success := delegatecall(not(0), _masterCopy, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch success
case 0 {
revert(0, returndatasize)
}
default {
return(0, returndatasize)
}
}
}
}
// File: @gnosis.pm/util-contracts/contracts/GnosisStandardToken.sol
pragma solidity ^0.5.2;
/**
* Deprecated: Use Open Zeppeling one instead
*/
contract StandardTokenData {
/*
* Storage
*/
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowances;
uint totalTokens;
}
/**
* Deprecated: Use Open Zeppeling one instead
*/
/// @title Standard token contract with overflow protection
contract GnosisStandardToken is Token, StandardTokenData {
using GnosisMath for *;
/*
* Public functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transfer(address to, uint value) public returns (bool) {
if (!balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) {
return false;
}
balances[msg.sender] -= value;
balances[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success
/// @param from Address from where tokens are withdrawn
/// @param to Address to where tokens are sent
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transferFrom(address from, address to, uint value) public returns (bool) {
if (!balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub(
value
) || !balances[to].safeToAdd(value)) {
return false;
}
balances[from] -= value;
allowances[from][msg.sender] -= value;
balances[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Sets approved amount of tokens for spender. Returns success
/// @param spender Address of allowed account
/// @param value Number of approved tokens
/// @return Was approval successful?
function approve(address spender, uint value) public returns (bool) {
allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Returns number of allowed tokens for given address
/// @param owner Address of token owner
/// @param spender Address of token spender
/// @return Remaining allowance for spender
function allowance(address owner, address spender) public view returns (uint) {
return allowances[owner][spender];
}
/// @dev Returns number of tokens owned by given address
/// @param owner Address of token owner
/// @return Balance of owner
function balanceOf(address owner) public view returns (uint) {
return balances[owner];
}
/// @dev Returns total supply of tokens
/// @return Total supply
function totalSupply() public view returns (uint) {
return totalTokens;
}
}
// File: @gnosis.pm/owl-token/contracts/TokenOWL.sol
pragma solidity ^0.5.2;
contract TokenOWL is Proxied, GnosisStandardToken {
using GnosisMath for *;
string public constant name = "OWL Token";
string public constant symbol = "OWL";
uint8 public constant decimals = 18;
struct masterCopyCountdownType {
address masterCopy;
uint timeWhenAvailable;
}
masterCopyCountdownType masterCopyCountdown;
address public creator;
address public minter;
event Minted(address indexed to, uint256 amount);
event Burnt(address indexed from, address indexed user, uint256 amount);
modifier onlyCreator() {
// R1
require(msg.sender == creator, "Only the creator can perform the transaction");
_;
}
/// @dev trickers the update process via the proxyMaster for a new address _masterCopy
/// updating is only possible after 30 days
function startMasterCopyCountdown(address _masterCopy) public onlyCreator {
require(address(_masterCopy) != address(0), "The master copy must be a valid address");
// Update masterCopyCountdown
masterCopyCountdown.masterCopy = _masterCopy;
masterCopyCountdown.timeWhenAvailable = now + 30 days;
}
/// @dev executes the update process via the proxyMaster for a new address _masterCopy
function updateMasterCopy() public onlyCreator {
require(address(masterCopyCountdown.masterCopy) != address(0), "The master copy must be a valid address");
require(
block.timestamp >= masterCopyCountdown.timeWhenAvailable,
"It's not possible to update the master copy during the waiting period"
);
// Update masterCopy
masterCopy = masterCopyCountdown.masterCopy;
}
function getMasterCopy() public view returns (address) {
return masterCopy;
}
/// @dev Set minter. Only the creator of this contract can call this.
/// @param newMinter The new address authorized to mint this token
function setMinter(address newMinter) public onlyCreator {
minter = newMinter;
}
/// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this.
/// @param newOwner The new address, which should become the owner
function setNewOwner(address newOwner) public onlyCreator {
creator = newOwner;
}
/// @dev Mints OWL.
/// @param to Address to which the minted token will be given
/// @param amount Amount of OWL to be minted
function mintOWL(address to, uint amount) public {
require(minter != address(0), "The minter must be initialized");
require(msg.sender == minter, "Only the minter can mint OWL");
balances[to] = balances[to].add(amount);
totalTokens = totalTokens.add(amount);
emit Minted(to, amount);
emit Transfer(address(0), to, amount);
}
/// @dev Burns OWL.
/// @param user Address of OWL owner
/// @param amount Amount of OWL to be burnt
function burnOWL(address user, uint amount) public {
allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount);
balances[user] = balances[user].sub(amount);
totalTokens = totalTokens.sub(amount);
emit Burnt(msg.sender, user, amount);
emit Transfer(user, address(0), amount);
}
function getMasterCopyCountdown() public view returns (address, uint) {
return (masterCopyCountdown.masterCopy, masterCopyCountdown.timeWhenAvailable);
}
}
// File: openzeppelin-solidity/contracts/utils/SafeCast.sol
pragma solidity ^0.5.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.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
}
// File: solidity-bytes-utils/contracts/BytesLib.sol
/*
* @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;
library BytesLib {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
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)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
// File: openzeppelin-solidity/contracts/drafts/SignedSafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// File: contracts/libraries/TokenConservation.sol
pragma solidity ^0.5.0;
/** @title Token Conservation
* A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/
library TokenConservation {
using SignedSafeMath for int256;
/** @dev initialize the token conservation data structure
* @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked
*/
function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) {
return new int256[](tokenIdsForPrice.length + 1);
}
/** @dev returns the token imbalance of the fee token
* @param self internal datastructure created by TokenConservation.init()
*/
function feeTokenImbalance(int256[] memory self) internal pure returns (int256) {
return self[0];
}
/** @dev updated token conservation array.
* @param self internal datastructure created by TokenConservation.init()
* @param buyToken id of token whose imbalance should be subtracted from
* @param sellToken id of token whose imbalance should be added to
* @param tokenIdsForPrice sorted list of tokenIds
* @param buyAmount amount to be subtracted at `self[buyTokenIndex]`
* @param sellAmount amount to be added at `self[sellTokenIndex]`
*/
function updateTokenConservation(
int256[] memory self,
uint16 buyToken,
uint16 sellToken,
uint16[] memory tokenIdsForPrice,
uint128 buyAmount,
uint128 sellAmount
) internal pure {
uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice);
uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice);
self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount));
self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount));
}
/** @dev Ensures all array's elements are zero except the first.
* @param self internal datastructure created by TokenConservation.init()
* @return true if all, but first element of self are zero else false
*/
function checkTokenConservation(int256[] memory self) internal pure {
require(self[0] > 0, "Token conservation at 0 must be positive.");
for (uint256 i = 1; i < self.length; i++) {
require(self[i] == 0, "Token conservation does not hold");
}
}
/** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info.
* @param tokenIdsForPrice list of tokenIds
* @return true if tokenIdsForPrice is sorted else false
*/
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) {
for (uint256 i = 1; i < tokenIdsForPrice.length; i++) {
if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) {
return false;
}
}
return true;
}
/** @dev implementation of binary search on sorted list returns token id
* @param tokenId element whose index is to be found
* @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied.
* @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found).
*/
function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) {
// Fee token is not included in tokenIdsForPrice
if (tokenId == 0) {
return 0;
}
// binary search for the other tokens
uint256 leftValue = 0;
uint256 rightValue = tokenIdsForPrice.length - 1;
while (rightValue >= leftValue) {
uint256 middleValue = leftValue + (rightValue - leftValue) / 2;
if (tokenIdsForPrice[middleValue] == tokenId) {
// shifted one to the right to account for fee token at index 0
return middleValue + 1;
} else if (tokenIdsForPrice[middleValue] < tokenId) {
leftValue = middleValue + 1;
} else {
rightValue = middleValue - 1;
}
}
revert("Price not provided for token");
}
}
// File: contracts/BatchExchange.sol
pragma solidity ^0.5.0;
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch
* auction with uniform clearing prices.
* For more information visit: <https://github.com/gnosis/dex-contracts>
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/
contract BatchExchange is EpochTokenLocker {
using SafeCast for uint256;
using SafeMath for uint128;
using BytesLib for bytes32;
using BytesLib for bytes;
using TokenConservation for int256[];
using TokenConservation for uint16[];
using IterableAppendOnlySet for IterableAppendOnlySet.Data;
/** @dev Maximum number of touched orders in auction (used in submitSolution) */
uint256 public constant MAX_TOUCHED_ORDERS = 25;
/** @dev Fee charged for adding a token */
uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether;
/** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */
uint256 public constant AMOUNT_MINIMUM = 10**4;
/** Corresponds to percentage that competing solution must improve on current
* (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR)
*/
uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1%
/** @dev maximum number of tokens that can be listed for exchange */
// solhint-disable-next-line var-name-mixedcase
uint256 public MAX_TOKENS;
/** @dev Current number of tokens listed/available for exchange */
uint16 public numTokens;
/** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */
uint128 public feeDenominator;
/** @dev The feeToken of the exchange will be the OWL Token */
TokenOWL public feeToken;
/** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */
mapping(address => Order[]) public orders;
/** @dev mapping of type tokenId -> curentPrice of tokenId */
mapping(uint16 => uint128) public currentPrices;
/** @dev Sufficient information for current winning auction solution */
SolutionData public latestSolution;
// Iterable set of all users, required to collect auction information
IterableAppendOnlySet.Data private allUsers;
IdToAddressBiMap.Data private registeredTokens;
struct Order {
uint16 buyToken;
uint16 sellToken;
uint32 validFrom; // order is valid from auction collection period: validFrom inclusive
uint32 validUntil; // order is valid till auction collection period: validUntil inclusive
uint128 priceNumerator;
uint128 priceDenominator;
uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount
}
struct TradeData {
address owner;
uint128 volume;
uint16 orderId;
}
struct SolutionData {
uint32 batchId;
TradeData[] trades;
uint16[] tokenIdsForPrice;
address solutionSubmitter;
uint256 feeReward;
uint256 objectiveValue;
}
event OrderPlacement(
address owner,
uint256 index,
uint16 buyToken,
uint16 sellToken,
uint32 validFrom,
uint32 validUntil,
uint128 priceNumerator,
uint128 priceDenominator
);
/** @dev Event emitted when an order is cancelled but still valid in the batch that is
* currently being solved. It remains in storage but will not be tradable in any future
* batch to be solved.
*/
event OrderCancelation(address owner, uint256 id);
/** @dev Event emitted when an order is removed from storage.
*/
event OrderDeletion(address owner, uint256 id);
/** @dev Event emitted when a new trade is settled
*/
event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount);
/** @dev Event emitted when an already exectued trade gets reverted
*/
event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount);
/** @dev Constructor determines exchange parameters
* @param maxTokens The maximum number of tokens that can be listed.
* @param _feeDenominator fee as a proportion is (1 / feeDenominator)
* @param _feeToken Address of ERC20 fee token.
*/
constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public {
// All solutions for the batches must have normalized prices. The following line sets the
// price of OWL to 10**18 for all solutions and hence enforces a normalization.
currentPrices[0] = 1 ether;
MAX_TOKENS = maxTokens;
feeToken = TokenOWL(_feeToken);
// The burn functionallity of OWL requires an approval.
// In the following line the approval is set for all future burn calls.
feeToken.approve(address(this), uint256(-1));
feeDenominator = _feeDenominator;
addToken(_feeToken); // feeToken will always have the token index 0
}
/** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction.
* @param token ERC20 token to be listed.
*
* Requirements:
* - `maxTokens` has not already been reached
* - `token` has not already been added
*/
function addToken(address token) public {
require(numTokens < MAX_TOKENS, "Max tokens reached");
if (numTokens > 0) {
// Only charge fees for tokens other than the fee token itself
feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL);
}
require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered");
numTokens++;
}
/** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId
* @param buyToken id of token to be bought
* @param sellToken id of token to be sold
* @param validUntil batchId represnting order's expiry
* @param buyAmount relative minimum amount of requested buy amount
* @param sellAmount maximum amount of sell token to be exchanged
* @return orderId as index of user's current orders
*
* Emits an {OrderPlacement} event with all relevant order details.
*/
function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount)
public
returns (uint256)
{
return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount);
}
/** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId
* Note that parameters are passed as arrays and the indices correspond to each order.
* @param buyTokens ids of tokens to be bought
* @param sellTokens ids of tokens to be sold
* @param validFroms batchIds representing order's validity start time
* @param validUntils batchIds represnnting order's expiry
* @param buyAmounts relative minimum amount of requested buy amounts
* @param sellAmounts maximum amounts of sell token to be exchanged
* @return `orderIds` an array of indices in which `msg.sender`'s orders are included
*
* Emits an {OrderPlacement} event with all relevant order details.
*/
function placeValidFromOrders(
uint16[] memory buyTokens,
uint16[] memory sellTokens,
uint32[] memory validFroms,
uint32[] memory validUntils,
uint128[] memory buyAmounts,
uint128[] memory sellAmounts
) public returns (uint256[] memory orderIds) {
orderIds = new uint256[](buyTokens.length);
for (uint256 i = 0; i < buyTokens.length; i++) {
orderIds[i] = placeOrderInternal(
buyTokens[i],
sellTokens[i],
validFroms[i],
validUntils[i],
buyAmounts[i],
sellAmounts[i]
);
}
}
/** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently
* being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called
* multiple times (e.g. to eventually free storage once order is expired).
*
* @param ids referencing the index of user's order to be canceled
*
* Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId
*/
function cancelOrders(uint256[] memory ids) public {
for (uint256 i = 0; i < ids.length; i++) {
if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) {
delete orders[msg.sender][ids[i]];
emit OrderDeletion(msg.sender, ids[i]);
} else {
orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1;
emit OrderCancelation(msg.sender, ids[i]);
}
}
}
/** @dev A user facing wrapper to cancel and place new orders in the same transaction.
* @param cancellations ids of orders to be cancelled
* @param buyTokens ids of tokens to be bought in new orders
* @param sellTokens ids of tokens to be sold in new orders
* @param validFroms batchIds representing order's validity start time in new orders
* @param validUntils batchIds represnnting order's expiry in new orders
* @param buyAmounts relative minimum amount of requested buy amounts in new orders
* @param sellAmounts maximum amounts of sell token to be exchanged in new orders
* @return `orderIds` an array of indices in which `msg.sender`'s new orders are included
*
* Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details.
*/
function replaceOrders(
uint256[] memory cancellations,
uint16[] memory buyTokens,
uint16[] memory sellTokens,
uint32[] memory validFroms,
uint32[] memory validUntils,
uint128[] memory buyAmounts,
uint128[] memory sellAmounts
) public returns (uint256[] memory orderIds) {
cancelOrders(cancellations);
return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts);
}
/** @dev a solver facing function called for auction settlement
* @param batchIndex index of auction solution is referring to
* @param owners array of addresses corresponding to touched orders
* @param orderIds array of order ids used in parallel with owners to identify touched order
* @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays
* @param prices list of prices for touched tokens indexed by next parameter
* @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i]
* @return the computed objective value of the solution
*
* Requirements:
* - Solutions for this `batchIndex` are currently being accepted.
* - Claimed objetive value is a great enough improvement on the current winning solution
* - Fee Token price is non-zero
* - `tokenIdsForPrice` is sorted.
* - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`.
* - Each touched order is valid at current `batchIndex`.
* - Each touched order's `executedSellAmount` does not exceed its remaining amount.
* - Limit Price of each touched order is respected.
* - Solution's objective evaluation must be positive.
*
* Sub Requirements: Those nested within other functions
* - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution
* - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought
*/
function submitSolution(
uint32 batchIndex,
uint256 claimedObjectiveValue,
address[] memory owners,
uint16[] memory orderIds,
uint128[] memory buyVolumes,
uint128[] memory prices,
uint16[] memory tokenIdsForPrice
) public returns (uint256) {
require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch");
require(
isObjectiveValueSufficientlyImproved(claimedObjectiveValue),
"Claimed objective doesn't sufficiently improve current solution"
);
require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM");
require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!");
require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId");
require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS");
burnPreviousAuctionFees();
undoCurrentSolution();
updateCurrentPrices(prices, tokenIdsForPrice);
delete latestSolution.trades;
int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice);
uint256 utility = 0;
for (uint256 i = 0; i < owners.length; i++) {
Order memory order = orders[owners[i]][orderIds[i]];
require(checkOrderValidity(order, batchIndex), "Order is invalid");
(uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order);
require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM");
require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM");
tokenConservation.updateTokenConservation(
order.buyToken,
order.sellToken,
tokenIdsForPrice,
executedBuyAmount,
executedSellAmount
);
require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order");
// Ensure executed price is not lower than the order price:
// executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator
require(
executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator),
"limit price not satisfied"
);
// accumulate utility before updateRemainingOrder, but after limitPrice verified!
utility = utility.add(evaluateUtility(executedBuyAmount, order));
updateRemainingOrder(owners[i], orderIds[i], executedSellAmount);
addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount);
emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount);
}
// Perform all subtractions after additions to avoid negative values
for (uint256 i = 0; i < owners.length; i++) {
Order memory order = orders[owners[i]][orderIds[i]];
(, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order);
subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount);
}
uint256 disregardedUtility = 0;
for (uint256 i = 0; i < owners.length; i++) {
disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i]));
}
uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2;
// burntFees ensures direct trades (when available) yield better solutions than longer rings
uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility);
checkAndOverrideObjectiveValue(objectiveValue);
grantRewardToSolutionSubmitter(burntFees);
tokenConservation.checkTokenConservation();
documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice);
return (objectiveValue);
}
/**
* Public View Methods
*/
/** @dev View returning ID of listed tokens
* @param addr address of listed token.
* @return tokenId as stored within the contract.
*/
function tokenAddressToIdMap(address addr) public view returns (uint16) {
return IdToAddressBiMap.getId(registeredTokens, addr);
}
/** @dev View returning address of listed token by ID
* @param id tokenId as stored, via BiMap, within the contract.
* @return address of (listed) token
*/
function tokenIdToAddressMap(uint16 id) public view returns (address) {
return IdToAddressBiMap.getAddressAt(registeredTokens, id);
}
/** @dev View returning a bool attesting whether token was already added
* @param addr address of the token to be checked
* @return bool attesting whether token was already added
*/
function hasToken(address addr) public view returns (bool) {
return IdToAddressBiMap.hasAddress(registeredTokens, addr);
}
/** @dev View returning all byte-encoded sell orders for specified user
* @param user address of user whose orders are being queried
* @return encoded bytes representing all orders
*/
function getEncodedUserOrders(address user) public view returns (bytes memory elements) {
for (uint256 i = 0; i < orders[user].length; i++) {
elements = elements.concat(
encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i])
);
}
return elements;
}
/** @dev View returning all byte-encoded sell orders
* @return encoded bytes representing all orders ordered by (user, index)
*/
function getEncodedOrders() public view returns (bytes memory elements) {
if (allUsers.size() > 0) {
address user = allUsers.first();
bool stop = false;
while (!stop) {
elements = elements.concat(getEncodedUserOrders(user));
if (user == allUsers.last) {
stop = true;
} else {
user = allUsers.next(user);
}
}
}
return elements;
}
function acceptingSolutions(uint32 batchIndex) public view returns (bool) {
return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes;
}
/** @dev gets the objective value of currently winning solution.
* @return objective function evaluation of the currently winning solution, or zero if no solution proposed.
*/
function getCurrentObjectiveValue() public view returns (uint256) {
if (latestSolution.batchId == getCurrentBatchId() - 1) {
return latestSolution.objectiveValue;
} else {
return 0;
}
}
/**
* Private Functions
*/
function placeOrderInternal(
uint16 buyToken,
uint16 sellToken,
uint32 validFrom,
uint32 validUntil,
uint128 buyAmount,
uint128 sellAmount
) private returns (uint256) {
require(buyToken != sellToken, "Exchange tokens not distinct");
require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past");
orders[msg.sender].push(
Order({
buyToken: buyToken,
sellToken: sellToken,
validFrom: validFrom,
validUntil: validUntil,
priceNumerator: buyAmount,
priceDenominator: sellAmount,
usedAmount: 0
})
);
uint256 orderIndex = orders[msg.sender].length - 1;
emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount);
allUsers.insert(msg.sender);
return orderIndex;
}
/** @dev called at the end of submitSolution with a value of tokenConservation / 2
* @param feeReward amount to be rewarded to the solver
*/
function grantRewardToSolutionSubmitter(uint256 feeReward) private {
latestSolution.feeReward = feeReward;
addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward);
}
/** @dev called during solution submission to burn fees from previous auction
*/
function burnPreviousAuctionFees() private {
if (!currentBatchHasSolution()) {
feeToken.burnOWL(address(this), latestSolution.feeReward);
}
}
/** @dev Called from within submitSolution to update the token prices.
* @param prices list of prices for touched tokens only, first price is always fee token price
* @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i]
*/
function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private {
for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) {
currentPrices[latestSolution.tokenIdsForPrice[i]] = 0;
}
for (uint256 i = 0; i < tokenIdsForPrice.length; i++) {
currentPrices[tokenIdsForPrice[i]] = prices[i];
}
}
/** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order
* @param owner order's corresponding user address
* @param orderId index of order in list of owner's orders
* @param executedAmount proportion of order's requested sellAmount that was filled.
*/
function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private {
orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128();
}
/** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one.
* @param owner order's corresponding user address
* @param orderId index of order in list of owner's orders
* @param executedAmount proportion of order's requested sellAmount that was filled.
*/
function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private {
orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128();
}
/** @dev This function writes solution information into contract storage
* @param batchIndex index of referenced auction
* @param owners array of addresses corresponding to touched orders
* @param orderIds array of order ids used in parallel with owners to identify touched order
* @param volumes executed buy amounts for each order identified by index of owner-orderId arrays
* @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i]
*/
function documentTrades(
uint32 batchIndex,
address[] memory owners,
uint16[] memory orderIds,
uint128[] memory volumes,
uint16[] memory tokenIdsForPrice
) private {
latestSolution.batchId = batchIndex;
for (uint256 i = 0; i < owners.length; i++) {
latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]}));
}
latestSolution.tokenIdsForPrice = tokenIdsForPrice;
latestSolution.solutionSubmitter = msg.sender;
}
/** @dev reverts all relevant contract storage relating to an overwritten auction solution.
*/
function undoCurrentSolution() private {
if (currentBatchHasSolution()) {
for (uint256 i = 0; i < latestSolution.trades.length; i++) {
address owner = latestSolution.trades[i].owner;
uint256 orderId = latestSolution.trades[i].orderId;
Order memory order = orders[owner][orderId];
(, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order);
addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount);
}
for (uint256 i = 0; i < latestSolution.trades.length; i++) {
address owner = latestSolution.trades[i].owner;
uint256 orderId = latestSolution.trades[i].orderId;
Order memory order = orders[owner][orderId];
(uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order);
revertRemainingOrder(owner, orderId, sellAmount);
subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount);
emit TradeReversion(owner, orderId, sellAmount, buyAmount);
}
// subtract granted fees:
subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward);
}
}
/** @dev determines if value is better than currently and updates if it is.
* @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value
*/
function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private {
require(
isObjectiveValueSufficientlyImproved(newObjectiveValue),
"New objective doesn't sufficiently improve current solution"
);
latestSolution.objectiveValue = newObjectiveValue;
}
// Private view
/** @dev Evaluates utility of executed trade
* @param execBuy represents proportion of order executed (in terms of buy amount)
* @param order the sell order whose utility is being evaluated
* @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt
*/
function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) {
// Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt
uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken])
.mul(order.priceNumerator);
uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]);
uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div(
order.priceDenominator
);
return roundedUtility.sub(utilityError).toUint128();
}
/** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected)
* @param order the sell order whose disregarded utility is being evaluated
* @param user address of order's owner
* @return disregardedUtility of the order (after it has been applied)
* Note that:
* |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount
* where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi)
* and leftoverSellAmount = order.sellAmt - execSellAmt
* Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order).
* For correctness, we take the minimum of this with the user's token balance.
*/
function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) {
uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken)));
uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator);
uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div(
feeDenominator - 1
);
uint256 limitTerm = 0;
if (limitTermLeft > limitTermRight) {
limitTerm = limitTermLeft.sub(limitTermRight);
}
return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128();
}
/** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included)
* @param executedBuyAmount amount of buyToken executed for purchase in batch auction
* @param buyTokenPrice uniform clearing price of buyToken
* @param sellTokenPrice uniform clearing price of sellToken
* @return executedSellAmount as expressed in Equation (2)
* https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117
* execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken]
* where phi = 1/feeDenominator
* Note that: 1 - phi = (feeDenominator - 1) / feeDenominator
* And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1)
* execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi))
* = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1)
* in order to minimize rounding errors, the order of operations is switched
* = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice
*/
function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice)
private
view
returns (uint128)
{
return
uint256(executedBuyAmount)
.mul(buyTokenPrice)
.div(feeDenominator - 1)
.mul(feeDenominator)
.div(sellTokenPrice)
.toUint128();
}
/** @dev used to determine if solution if first provided in current batch
* @return true if `latestSolution` is storing a solution for current batch, else false
*/
function currentBatchHasSolution() private view returns (bool) {
return latestSolution.batchId == getCurrentBatchId() - 1;
}
// Private view
/** @dev Compute trade execution based on executedBuyAmount and relevant token prices
* @param executedBuyAmount executed buy amount
* @param order contains relevant buy-sell token information
* @return (executedBuyAmount, executedSellAmount)
*/
function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) {
uint128 executedSellAmount = getExecutedSellAmount(
executedBuyAmount,
currentPrices[order.buyToken],
currentPrices[order.sellToken]
);
return (executedBuyAmount, executedSellAmount);
}
/** @dev Checks that the proposed objective value is a significant enough improvement on the latest one
* @param objectiveValue the proposed objective value to check
* @return true if the objectiveValue is a significant enough improvement, false otherwise
*/
function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) {
return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1));
}
// Private pure
/** @dev used to determine if an order is valid for specific auction/batch
* @param order object whose validity is in question
* @param batchIndex auction index of validity
* @return true if order is valid in auction batchIndex else false
*/
function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) {
return order.validFrom <= batchIndex && order.validUntil >= batchIndex;
}
/** @dev computes the remaining sell amount for a given order
* @param order the order for which remaining amount should be calculated
* @return the remaining sell amount
*/
function getRemainingAmount(Order memory order) private pure returns (uint128) {
return order.priceDenominator - order.usedAmount;
}
/** @dev called only by getEncodedOrders and used to pack auction info into bytes
* @param user list of tokenIds
* @param sellTokenBalance user's account balance of sell token
* @param order a sell order
* @return byte encoded, packed, concatenation of relevant order information
*/
function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order)
private
pure
returns (bytes memory element)
{
element = abi.encodePacked(user);
element = element.concat(abi.encodePacked(sellTokenBalance));
element = element.concat(abi.encodePacked(order.buyToken));
element = element.concat(abi.encodePacked(order.sellToken));
element = element.concat(abi.encodePacked(order.validFrom));
element = element.concat(abi.encodePacked(order.validUntil));
element = element.concat(abi.encodePacked(order.priceNumerator));
element = element.concat(abi.encodePacked(order.priceDenominator));
element = element.concat(abi.encodePacked(getRemainingAmount(order)));
return element;
}
/** @dev determines if value is better than currently and updates if it is.
* @param amounts array of values to be verified with AMOUNT_MINIMUM
*/
function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) {
for (uint256 i = 0; i < amounts.length; i++) {
if (amounts[i] < AMOUNT_MINIMUM) {
return false;
}
}
return true;
}
}
|
called during solution submission to burn fees from previous auction/
|
function burnPreviousAuctionFees() private {
if (!currentBatchHasSolution()) {
feeToken.burnOWL(address(this), latestSolution.feeReward);
}
}
| 2,482,018 |
//! The KeyServerSet contract. Owned version with migration support.
//!
//! Copyright 2017 Svyatoslav Nikolsky, Parity Technologies Ltd.
//!
//! Licensed under the Apache License, Version 2.0 (the "License");
//! you may not use this file except in compliance with the License.
//! You may obtain a copy of the License at
//!
//! http://www.apache.org/licenses/LICENSE-2.0
//!
//! Unless required by applicable law or agreed to in writing, software
//! distributed under the License is distributed on an "AS IS" BASIS,
//! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//! See the License for the specific language governing permissions and
//! limitations under the License.
pragma solidity ^0.4.18;
import "./Owned.sol";
import "./KeyServerSet.sol";
/// Single-owned KeyServerSet with migration support.
contract OwnedKeyServerSetWithMigration is Owned, KeyServerSetWithMigration {
struct KeyServer {
/// Index in the keyServersList.
uint8 index;
/// Public key of key server.
bytes publicKey;
/// IP address of key server.
string ip;
}
struct Set {
/// Public keys of all active key servers.
address[] list;
/// Mapping public key => server IP address.
mapping(address => KeyServer) map;
}
/// When new server is added to new set.
event KeyServerAdded(address keyServer);
/// When existing server is removed from new set.
event KeyServerRemoved(address keyServer);
/// When migration is started.
event MigrationStarted();
/// When migration is completed.
event MigrationCompleted();
/// Is initialized.
bool isInitialized;
/// Block at which current
uint256 currentSetChangeBlock;
/// Current key servers set.
Set currentSet;
/// Migration key servers set.
Set migrationSet;
/// New key servers set.
Set newSet;
/// Migration master.
address migrationMaster;
/// Migration id.
bytes32 migrationId;
/// Required migration confirmations.
mapping(address => bool) migrationConfirmations;
modifier notAnEmptyString(string value) {
bytes memory castValue = bytes(value);
require(castValue.length != 0);
_;
}
/// Only if valid public is passed
modifier isValidPublic(bytes keyServerPublic) {
require(checkPublic(keyServerPublic));
_;
}
/// Only run if server is currently on current set.
modifier isOnCurrentSet(address keyServer) {
require(keccak256(currentSet.map[keyServer].ip) != keccak256(""));
_;
}
/// Only run if server is currently on migration set.
modifier isOnMigrationSet(address keyServer) {
require(keccak256(migrationSet.map[keyServer].ip) != keccak256(""));
_;
}
/// Only run if server is currently on new set.
modifier isOnNewSet(address keyServer) {
require(keccak256(newSet.map[keyServer].ip) != keccak256(""));
_;
}
/// Only run if server is currently on new set.
modifier isNotOnNewSet(address keyServer) {
require(keccak256(newSet.map[keyServer].ip) == keccak256(""));
_;
}
/// Only when no active migration process.
modifier noActiveMigration {
require(migrationMaster == address(0));
_;
}
/// Only when migration with given id is in progress.
modifier isActiveMigration(bytes32 id) {
require(migrationId == id);
_;
}
/// Only when migration id is valid.
modifier isValidMigrationId(bytes32 id) {
require(id != bytes32(0));
_;
}
/// Only when migration is required.
modifier whenMigrationRequired {
require(!areEqualSets(currentSet, newSet));
_;
}
/// Only run when sender is potential participant of migration.
modifier isPossibleMigrationParticipant {
require(
keccak256(currentSet.map[msg.sender].ip) != keccak256("") ||
keccak256(newSet.map[msg.sender].ip) != keccak256(""));
_;
}
/// Only run when sender is participant of migration.
modifier isMigrationParticipant(address keyServer) {
require(
keccak256(currentSet.map[keyServer].ip) != keccak256("") ||
keccak256(migrationSet.map[keyServer].ip) != keccak256(""));
_;
}
/// We do not support direct payments.
function() payable public { revert(); }
/// Get number of block when current set has been changed last time.
function getCurrentLastChange() external view returns (uint256) {
return currentSetChangeBlock;
}
/// Get index of given key server in current set.
function getCurrentKeyServerIndex(address keyServer) external view returns (uint8) {
KeyServer storage entry = currentSet.map[keyServer];
require(keccak256(entry.ip) != keccak256(""));
return entry.index;
}
/// Get count of key servers in current set.
function getCurrentKeyServersCount() external view returns (uint8) {
return uint8(currentSet.list.length);
}
/// Get address of key server in current set.
function getCurrentKeyServer(uint8 index) external view returns (address) {
require(index < currentSet.list.length);
return currentSet.list[index];
}
/// Get all current key servers.
function getCurrentKeyServers() external constant returns (address[]) {
return currentSet.list;
}
/// Get current key server public key.
function getCurrentKeyServerPublic(address keyServer) isOnCurrentSet(keyServer) external constant returns (bytes) {
return currentSet.map[keyServer].publicKey;
}
/// Get current key server address.
function getCurrentKeyServerAddress(address keyServer) isOnCurrentSet(keyServer) external constant returns (string) {
return currentSet.map[keyServer].ip;
}
/// Get all migration key servers.
function getMigrationKeyServers() external constant returns (address[]) {
return migrationSet.list;
}
/// Get migration key server public key.
function getMigrationKeyServerPublic(address keyServer) isOnMigrationSet(keyServer) external constant returns (bytes) {
return migrationSet.map[keyServer].publicKey;
}
/// Get migration key server address.
function getMigrationKeyServerAddress(address keyServer) isOnMigrationSet(keyServer) external constant returns (string) {
return migrationSet.map[keyServer].ip;
}
/// Get all new key servers.
function getNewKeyServers() external constant returns (address[]) {
return newSet.list;
}
/// Get new key server public key.
function getNewKeyServerPublic(address keyServer) isOnNewSet(keyServer) external constant returns (bytes) {
return newSet.map[keyServer].publicKey;
}
/// Get new key server address.
function getNewKeyServerAddress(address keyServer) isOnNewSet(keyServer) external constant returns (string) {
return newSet.map[keyServer].ip;
}
/// Get migration id.
function getMigrationId() isValidMigrationId(migrationId) external view returns (bytes32) {
return migrationId;
}
/// Start migration.
function startMigration(bytes32 id) external noActiveMigration isValidMigrationId(id) whenMigrationRequired isPossibleMigrationParticipant {
// migration to empty set is impossible
require (newSet.list.length != 0);
migrationMaster = msg.sender;
migrationId = id;
copySet(migrationSet, newSet);
emit MigrationStarted();
}
/// Confirm migration.
function confirmMigration(bytes32 id) external isValidMigrationId(id) isActiveMigration(id) isOnMigrationSet(msg.sender) {
require(!migrationConfirmations[msg.sender]);
migrationConfirmations[msg.sender] = true;
// check if migration is completed
for (uint j = 0; j < migrationSet.list.length; ++j) {
if (!migrationConfirmations[migrationSet.list[j]]) {
return;
}
}
// migration is completed => delete confirmations
for (uint m = 0; m < migrationSet.list.length; ++m) {
delete migrationConfirmations[migrationSet.list[m]];
}
delete migrationMaster;
// ...and copy migration set to current set
copySet(currentSet, migrationSet);
// ...and also delete entries from migration set
clearSet(migrationSet);
// ...and fire completion event
emit MigrationCompleted();
// ...and update current server set change block
currentSetChangeBlock = block.number;
}
/// Get migration master.
function getMigrationMaster() external constant returns (address) {
return migrationMaster;
}
/// Is migration confirmed.
function isMigrationConfirmed(address keyServer) external view isMigrationParticipant(keyServer) returns (bool) {
return migrationConfirmations[keyServer];
}
/// Complete initialization. Before this function is called, all calls to addKeyServer/removeKeyServer
/// affect both newSet and currentSet.
function completeInitialization() public onlyOwner {
require(!isInitialized);
isInitialized = true;
}
/// Add new key server to set.
function addKeyServer(bytes keyServerPublic, string keyServerIp) public onlyOwner notAnEmptyString(keyServerIp) isValidPublic(keyServerPublic) isNotOnNewSet(computeAddress(keyServerPublic)) {
// append to the new set
address keyServer = appendToSet(newSet, keyServerPublic, keyServerIp);
// also append to current set
if (!isInitialized) {
appendToSet(currentSet, keyServerPublic, keyServerIp);
}
// fire event
emit KeyServerAdded(keyServer);
}
/// Remove key server from set.
function removeKeyServer(address keyServer) public onlyOwner isOnNewSet(keyServer) {
// remove element from the new set
removeFromSet(newSet, keyServer);
// also remove from the current set
if (!isInitialized) {
removeFromSet(currentSet, keyServer);
}
// fire event
emit KeyServerRemoved(keyServer);
}
/// Compute address from public key.
function computeAddress(bytes keyServerPublic) private pure returns (address) {
return address(uint(keccak256(keyServerPublic)) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
}
/// 'Check' public key.
function checkPublic(bytes keyServerPublic) private pure returns (bool) {
return keyServerPublic.length == 64;
}
/// Copy set (assignment operator).
function copySet(Set storage set1, Set storage set2) private {
for (uint i = 0; i < set1.list.length; ++i) {
delete set1.map[set1.list[i]];
}
set1.list = set2.list;
for (uint j = 0; j < set1.list.length; ++j) {
set1.map[set1.list[j]] = set2.map[set1.list[j]];
}
}
/// Clear set.
function clearSet(Set storage set) private {
while (set.list.length > 0) {
address keyServer = set.list[set.list.length - 1];
delete set.list[set.list.length - 1];
set.list.length = set.list.length - 1;
delete set.map[keyServer];
}
}
/// Are two sets equal?
function areEqualSets(Set storage set1, Set storage set2) private view returns (bool) {
for (uint i = 0; i < set1.list.length; ++i) {
if (keccak256(set2.map[set1.list[i]].ip) == keccak256("")) {
return false;
}
}
for (uint j = 0; j < set2.list.length; ++j) {
if (keccak256(set1.map[set2.list[j]].ip) == keccak256("")) {
return false;
}
}
return true;
}
/// Append new key serer to set.
function appendToSet(Set storage set, bytes keyServerPublic, string keyServerIp) private returns (address) {
// we do not support > 256 key servers in the list
require(set.list.length < 256);
address keyServer = computeAddress(keyServerPublic);
set.map[keyServer].index = uint8(set.list.length);
set.map[keyServer].publicKey = keyServerPublic;
set.map[keyServer].ip = keyServerIp;
set.list.push(keyServer);
return keyServer;
}
/// Remove existing key server set.
function removeFromSet(Set storage set, address keyServer) private {
// swap list elements (removedIndex, lastIndex)
uint8 removedIndex = uint8(set.map[keyServer].index);
uint8 lastIndex = uint8(set.list.length) - 1;
address lastKeyServer = set.list[lastIndex];
set.list[removedIndex] = lastKeyServer;
set.map[lastKeyServer].index = removedIndex;
// remove element from list and map
delete set.list[lastIndex];
delete set.map[keyServer];
set.list.length--;
}
}
|
Complete initialization. Before this function is called, all calls to addKeyServer/removeKeyServer affect both newSet and currentSet.
|
function completeInitialization() public onlyOwner {
require(!isInitialized);
isInitialized = true;
}
| 5,401,824 |
pragma solidity ^0.6.12;
// SPDX-License-Identifier: MIT
/*
* @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;
}
}
/**
* @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);
}
/**
* @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;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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");
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev 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;
using Address for address;
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 returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. 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 returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 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");
_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 {
_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 { }
}
// YEARNGLOBAL with Governance.
contract YEARNGLOBAL is ERC20("YEARN GLOBAL", "YG"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
}
contract YGChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of YGs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accYGPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accYGPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. YGs to distribute per block.
uint256 lastRewardBlock; // Last block number that YGs distribution occurs.
uint256 accYGPerShare; // Accumulated YGs per share, times 1e12. See below.
}
// The YG TOKEN!
YEARNGLOBAL public YG;
// Dev address.
address public devaddr;
// Block number when bonus YG period ends.
uint256 public bonusEndBlock;
// YG tokens created per block.
uint256 public YGPerBlock;
// Bonus muliplier for early YG makers.
uint256 public constant BONUS_MULTIPLIER = 1; // no bonus
// No of blocks in a day - 7000
uint256 public constant perDayBlocks = 7000; // no bonus
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when YG mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
YEARNGLOBAL _YG,
address _devaddr,
uint256 _YGPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
YG = _YG;
devaddr = _devaddr;
YGPerBlock = _YGPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accYGPerShare: 0
}));
}
// Update the given pool's YG allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// reward prediction at specific block
function getRewardPerBlock(uint blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return YGPerBlock;
}
}
}
// View function to see pending YGs on frontend.
function pendingYG(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accYGPerShare = pool.accYGPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewardThisBlock = getRewardPerBlock(block.number);
uint256 YGReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint);
accYGPerShare = accYGPerShare.add(YGReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accYGPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 rewardThisBlock = getRewardPerBlock(block.number);
uint256 YGReward = multiplier.mul(rewardThisBlock).mul(pool.allocPoint).div(totalAllocPoint);
YG.mint(devaddr, YGReward.div(24)); // 4%
YG.mint(address(this), YGReward);
pool.accYGPerShare = pool.accYGPerShare.add(YGReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for YG allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accYGPerShare).div(1e12).sub(user.rewardDebt);
safeYGTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accYGPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accYGPerShare).div(1e12).sub(user.rewardDebt);
safeYGTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accYGPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe YG transfer function, just in case if rounding error causes pool to not have enough YGs.
function safeYGTransfer(address _to, uint256 _amount) internal {
uint256 YGBal = YG.balanceOf(address(this));
if (_amount > YGBal) {
YG.transfer(_to, YGBal);
} else {
YG.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Withdraw LP tokens from MasterChef.
|
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accYGPerShare).div(1e12).sub(user.rewardDebt);
safeYGTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accYGPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
| 6,856,753 |
pragma solidity ^0.4.19;
// "Proof of Commitment" fun pre-launch competition for NBAOnline!
// Full details and game smart contract will shortly be able:
// ~~ https://nbaonline.io ~~
// This contest will award some of the keen NBAOnline players
// ALL ETHER DEPOSITED INTO THIS PROMO CAN BE WITHDRAWN BY PLAYER AT ANY
// TIME BUT PRIZES WILL BE DRAWN: SATURDAY 14TH APRIL (LAUNCH)
// AT WHICH POINT ALL ETHER WILL ALSO BE REFUNDED TO PLAYERS
// PRIZES:
// 0.5 ether (top eth deposit)
// 0.35 ether (1 random deposit)
// 0.15 ether (1 random deposit)
contract NBAOnlineLaunchPromotion {
// First Goo Players!
mapping(address => uint256) public deposits;
mapping(address => bool) depositorAlreadyStored;
address[] public depositors;
// To trigger contest end only
address public ownerAddress;
// Flag so can only be awarded once
bool public prizesAwarded = false;
// Ether to be returned to depositor on launch
// 1day = 86400
uint256 public constant LAUNCH_DATE = 1523678400; // Saturday, 14 April 2018 00:00:00 (seconds) ET
// Proof of Commitment contest prizes
uint256 private constant TOP_DEPOSIT_PRIZE = 0.5 ether;
uint256 private constant RANDOM_DEPOSIT_PRIZE1 = 0.35 ether;
uint256 private constant RANDOM_DEPOSIT_PRIZE2 = 0.15 ether;
function NBAOnlineLaunchPromotion() public payable {
require(msg.value == 1 ether); // Owner must provide enough for prizes
ownerAddress = msg.sender;
}
function deposit() external payable {
uint256 existing = deposits[msg.sender];
// Safely store the ether sent
deposits[msg.sender] = SafeMath.add(msg.value, existing);
// Finally store contest details
if (msg.value >= 0.01 ether && !depositorAlreadyStored[msg.sender]) {
depositors.push(msg.sender);
depositorAlreadyStored[msg.sender] = true;
}
}
function refund() external {
// Safely transfer players deposit back
uint256 depositAmount = deposits[msg.sender];
deposits[msg.sender] = 0; // Can't withdraw twice obviously
msg.sender.transfer(depositAmount);
}
function refundPlayer(address depositor) external {
require(msg.sender == ownerAddress);
// Safely transfer back to player
uint256 depositAmount = deposits[depositor];
deposits[depositor] = 0; // Can't withdraw twice obviously
// Sends back to correct depositor
depositor.transfer(depositAmount);
}
function awardPrizes() external {
require(msg.sender == ownerAddress);
require(now >= LAUNCH_DATE);
require(!prizesAwarded);
// Ensure only ran once
prizesAwarded = true;
uint256 highestDeposit;
address highestDepositWinner;
for (uint256 i = 0; i < depositors.length; i++) {
address depositor = depositors[i];
// No tie allowed!
if (deposits[depositor] > highestDeposit) {
highestDeposit = deposits[depositor];
highestDepositWinner = depositor;
}
}
uint256 numContestants = depositors.length;
uint256 seed1 = numContestants + block.timestamp;
uint256 seed2 = seed1 + (numContestants*2);
address randomDepositWinner1 = depositors[randomContestant(numContestants, seed1)];
address randomDepositWinner2 = depositors[randomContestant(numContestants, seed2)];
// Just incase
while(randomDepositWinner2 == randomDepositWinner1) {
seed2++;
randomDepositWinner2 = depositors[randomContestant(numContestants, seed2)];
}
highestDepositWinner.transfer(TOP_DEPOSIT_PRIZE);
randomDepositWinner1.transfer(RANDOM_DEPOSIT_PRIZE1);
randomDepositWinner2.transfer(RANDOM_DEPOSIT_PRIZE2);
}
// Random enough for small contest
function randomContestant(uint256 contestants, uint256 seed) constant internal returns (uint256 result){
return addmod(uint256(block.blockhash(block.number-1)), seed, contestants);
}
}
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;
}
}
|
Ensure only ran once No tie allowed! Just incase
|
function awardPrizes() external {
require(msg.sender == ownerAddress);
require(now >= LAUNCH_DATE);
require(!prizesAwarded);
prizesAwarded = true;
uint256 highestDeposit;
address highestDepositWinner;
for (uint256 i = 0; i < depositors.length; i++) {
address depositor = depositors[i];
if (deposits[depositor] > highestDeposit) {
highestDeposit = deposits[depositor];
highestDepositWinner = depositor;
}
}
uint256 numContestants = depositors.length;
uint256 seed1 = numContestants + block.timestamp;
uint256 seed2 = seed1 + (numContestants*2);
address randomDepositWinner1 = depositors[randomContestant(numContestants, seed1)];
address randomDepositWinner2 = depositors[randomContestant(numContestants, seed2)];
while(randomDepositWinner2 == randomDepositWinner1) {
seed2++;
randomDepositWinner2 = depositors[randomContestant(numContestants, seed2)];
}
highestDepositWinner.transfer(TOP_DEPOSIT_PRIZE);
randomDepositWinner1.transfer(RANDOM_DEPOSIT_PRIZE1);
randomDepositWinner2.transfer(RANDOM_DEPOSIT_PRIZE2);
}
| 10,580,747 |
./full_match/137/0x2733C843Dd7A70dDd0D379841D8bFa8bE18AbD8f/sources/project_/contracts/market/ERC721Listings.sol
|
send fund and tokens, remove listing from storage, and emit event/ Send token to buyer
|
function _purchaseToken(
address erc721Address,
Listing memory listing,
address buyer
) private nonReentrant returns (uint256 fundSpent) {
(
FundReceiver[] memory fundReceivers,
ICollectionRoyaltyReader.RoyaltyAmount[] memory royaltyInfo,
uint256 serviceFee
) = _getFundReceiversOfListing(erc721Address, listing);
fundSpent = _sendFundToReceivers(buyer, fundReceivers);
IERC721(erc721Address).safeTransferFrom(
listing.seller,
buyer,
listing.tokenId
);
_removeListing(erc721Address, listing.tokenId);
emit TokenBought({
erc721Address: erc721Address,
buyer: buyer,
tokenId: listing.tokenId,
listing: listing,
serviceFee: serviceFee,
royaltyInfo: royaltyInfo,
sender: _msgSender()
});
}
| 4,696,892 |
./full_match/1/0x88f9fF5Ab143B0b99a19fDa961E7a1E196577E8c/sources/localhost/RacePool.sol
|
_use = _use.sub(_fee);
|
function _setBankerInfo(
uint256 _tID,
uint256 _id,
uint256 _bID,
uint256 _num,
uint256 _amount,
address _addr,
Result _r
) internal {
RaceUse storage rUse = raceUse[_tID][_id];
BankerInfo storage bInfo = bankerInfo[_bID];
BankerRace storage bRace = bankerRace[_addr][_tID][_id];
uint256 _feeRate = typeInfo[_tID].feeRate;
if(_r != Result.CANCEL && rUse.perAmount > 0 && rUse.needPay > rUse.havePay) {
uint256 _use = _amount.mul(rUse.perAmount).div(multi);
if(_use > _amount) {
_use = _amount;
}
if(rUse.havePay.add(_use) > rUse.needPay) {
_use = rUse.needPay.sub(rUse.havePay);
}
if(rUse.needPay.sub(rUse.havePay).sub(_use) >= 1 &&
bInfo.totalAmount.sub(bInfo.payAmount) >= _use.add(1))
{
_use = _use.add(1);
}
rUse.havePay = rUse.havePay.add(_use);
bInfo.payAmount = bInfo.payAmount.add(_use);
bRace.payAmount = bRace.payAmount.add(_use);
uint256 _use = rUse.perReward.mul(_amount).div(multi);
if(rUse.haveReward.add(_use) > rUse.reward) {
_use = rUse.reward.sub(rUse.haveReward);
}
if(addInfo[_addr][_num].currNum > 0
&& addInfo[_addr][_num].time >= raceInfo[_tID][_id].startTime
&& addInfo[_addr][_num].time <= rUse.settlement)
{
uint256 _fee = _use.mul(_feeRate).div(baseRate);
dao.bankerAmount = dao.bankerAmount.add(_fee);
bRace.feeAmount = _fee;
poolInfo.totalRewards = poolInfo.totalRewards.sub(_fee);
if(address(daoAddr) != address(0)) {
if(_fee > 0) {
_transferDao(address(daoAddr), _fee);
}
}
}
if(rUse.reward.sub(rUse.haveReward).sub(_use) >= 1) {
_use = _use.add((1));
}
rUse.haveReward = rUse.haveReward.add(_use);
bInfo.winAmount = bInfo.winAmount.add(_use).sub(bRace.feeAmount);
bInfo.totalAmount = bInfo.totalAmount.add(_use).sub(bRace.feeAmount);
bRace.num = _num;
bRace.winAmount = bRace.winAmount.add(_use).sub(bRace.feeAmount);
}
}
| 3,094,091 |
pragma solidity ^0.6.6;
/**
* @title MixItemStoreShortId
* @author Jonathan Brown <[email protected]>
* @dev Maintains a bidirectional mapping between 32 byte itemIds and 4 byte shortIds.
*/
contract MixItemStoreShortId {
/**
* @dev Mapping of itemId to shortId.
*/
mapping (bytes32 => bytes4) itemIdShortId;
/**
* @dev Mapping of shortId to itemId.
*/
mapping (bytes4 => bytes32) shortIdItemId;
/**
* @dev A new shortId has been created.
* @param itemId itemId of the item.
* @param shortId shortId of the item
*/
event CreateShortId(bytes32 indexed itemId, bytes32 indexed shortId);
/**
* @dev Revert if the itemId already has a shortId.
* @param itemId itemId of the item.
*/
modifier noShortId(bytes32 itemId) {
require (itemIdShortId[itemId] == 0, "itemId already has a shortId.");
_;
}
/**
* @dev Create a 4 byte shortId for a 32 byte itemId.
* @param itemId itemId of the item.
* @return shortId New 4 byte shortId.
*/
function createShortId(bytes32 itemId) external noShortId(itemId) returns (bytes4 shortId) {
// Find a shortId that hasn't been used before.
bytes32 hash = keccak256(abi.encodePacked(itemId));
shortId = bytes4(hash);
while (shortIdItemId[shortId] != 0) {
hash = keccak256(abi.encodePacked(hash));
shortId = bytes4(hash);
}
// Store the mappings.
itemIdShortId[itemId] = shortId;
shortIdItemId[shortId] = itemId;
// Log the event.
emit CreateShortId(itemId, shortId);
}
/**
* @dev Get itemId for shortId.
* @param shortId to get the itemId for.
* @return The itemId.
*/
function getItemId(bytes4 shortId) external view returns (bytes32) {
return shortIdItemId[shortId];
}
/**
* @dev Get shortId for itemId.
* @param itemId to get the shortId for.
* @return The shortId.
*/
function getShortId(bytes32 itemId) external view returns (bytes4) {
return itemIdShortId[itemId];
}
}
|
Get shortId for itemId. itemId to get the shortId for. return The shortId./
|
function getShortId(bytes32 itemId) external view returns (bytes4) {
return itemIdShortId[itemId];
}
| 12,591,569 |
// 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);
}
|
IFeeDistributor Interface of the `FeeDistributor` contract This interface is used by the `SurplusConverter` contract to send funds to the `FeeDistributor`
|
interface IFeeDistributor {
function burn(address token) external;
}
| 6,009,175 |
//pragma solidity ^0.5.5;
pragma solidity >=0.4.16 <0.9.0;
import './UniswapV2Pair.sol';
//import '../contracts/libraries/UniswapV2Library.sol';
//import '@uniswap/v2-core/contracts/libraries/IUniswapV2Pair.sol';
// I NEED TO GET THESE TWO INTERFACES TO WORK WITH V1
import '../contracts/interfaces/IUniswapV2Callee.sol';
import '../contracts/libraries/TransferHelper.sol';
import '../contracts/interfaces/IUniswapV2Library.sol';
import '../contracts/interfaces/V1/IUniswapV1Factory.sol';
import '../contracts/interfaces/V1/IUniswapV1Exchange.sol';
import '../contracts/interfaces/IUniswapV2Router02.sol';
//import '../contracts/interfaces/IUniswapV2Pair.sol';
import '../contracts/interfaces/IUniswapV2Router01.sol';
import '../contracts/interfaces/IERC20.sol';
import '../contracts/interfaces/IWETH.sol';
//import '../contracts/libraries/UniswapV2LiquidityMathLibrary.sol';
//import '../contracts/libraries/UniswapV2Library.sol';
//import '../contracts/libraries/UniswapV2OracleLibrary.sol';
/*
interface IUniswap{
function swapExactTokensForEth(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to, uint deadline)
external
ensure(deadline) returns (uint[] memory amounts);
function WETH() external pure returns (address);
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {
IUniswapV2Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint 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(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// REMOVEL LIQUIDITY AND WITHDRAW ETH
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
}
}
interface IERC20{
function transferFrom(address sender, address recipient,uint256 amount )
}
interface IWETH{
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// UniswapFactorymustbegiven here
*/
abstract contract Uniswap is IERC20, IUniswapV2Callee, IWETH, IUniswapV2Router02, IUniswapV2Pair,IUniswapV2Library {
address public override (IUniswapV2Pair, IUniswapV2Router01) factory ;
//address public router;
//address public token0;
//address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast;
//SWAPPING TOKENS HERE
address public router2;
address public router1;
address public override WETH;
address public token;
address public pair;
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');
_;
}
IUniswapV2Router01 public router;
IUniswapV1Factory public swapfactory;
//address public factory;
/* constructor(address factory_, IUniswapV2Router01 router_) public {
factory = factory_;
router = router_;
}
*/
constructor ( address _factory, address _router ) {
_factory = msg.sender;
factory =_factory;
router1 =_router;
// uniswap = IUniswap(_uniswap);
swapfactory = IUniswapV1Factory(_factory);
router = IUniswapV2Router01(_router);
WETH = IWETH(IUniswapV2Router01(_router).WETH());
}
function fullswapprocessandswaptokenforeth(uint amountOut, address[] memory path, address to, uint deadline,address tokenA, address tokenB)
external
virtual
payable
ensure(deadline)
returns (uint[] memory amounts)
{
// IUniswapV1Factory.createPair();
// SORT TOKENS
//UniswapV2Library.sortTokens();
// GET PAIRS
//address token0 = IUniswapV2Pair(msg.sender).token0();
//address token1 = IUniswapV2Pair(msg.sender).token1();
// cREATE A SINGLE TOKEN PAIR
// address of the two tokens, wonder why they call it path
path = new address[](2);
// Set the pairs given
//ROUTER'S JOB, ROUTING THE ETH TO THE VARIOUS NETWORKS
address token0;
address token1;
( token0, token1) = IUniswapV2Pair.sortTokens(tokenA, tokenB);
(token0, token1) = IUniswapV2Pair.createPair(tokenA, tokenB);
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
path[0] = IWETH.WETH();
path[1] = token;
require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
uint totalSupply1 = IWETH.totalSupply();
// Total supply of token
uint totalSupply2 = IERC20(path[1]).totalSupply();
//Normally we use this if we were swapping tokens to tokens, we can get the reserves of the tokens
(uint reserveA, uint reserveB) = IUniswapV2Library.getReserves(factory, tokenA, tokenB);
amounts = IUniswapV2Library.getAmountsIn(factory, amountOut, path);
//ON A V2 NETWORK NOT REQUIRING SWITCH BETWEEN V1 AND V2
require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit(amounts[0]);
assert(IWETH(WETH).transfer(IUniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
assert(IWETH(WETH).transferFrom(IUniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]));
IERC20(IWETH(WETH)).approve();
IUniswapV2Router02.swapTokensForExactETH(amounts,0, path, to, deadline);
// _swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
//IF YOU WANT TO CREATE PAIR HERE, BUT IF USSING IN ANOTHER PROJECT YOU HAVE TO USE
// FORPAIR SINCE THE PAIR IS ALREADY IS ALREADY CREATED
function createPair(address tokenA, address tokenB) external returns (address _pair) {
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
pair = _pair;
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
// the pair that is created is then initiated as token0, and 1
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
// emit PairCreated(token0, token1, pair, allPairs.length);
}
/*
// SWAP AND WTHDRAW
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH');
amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, UniswapV2Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapTokensForEth(
address token, uint amountIn, uint amountOutMin,
uint deadline) external {
IERC20(token).transferFrom(msg.sender, address(this), amountIn)
// address of the tokens and eth, wonder why they call it path
address[] memory path = new address[](2);
path[0] = token;
path[1] = uniswap.WETH();
//HAVE TO GET THE FACTORY INFORMATION
uint amountIn = uniswap.getReserves();
uint amountOutMin =
IERC20(token).approve(address(uniswap), amountIn);
uniswap.swapExactTokensForEth(amountIn, amountOutMin, path, msg.sender, deadline);
// removing liquidity
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
address token, uint amountIn, uint amountOutMin,
uint deadline
uint amountIn,
uint amountOutMin
uint amountETHMin
uint _getreserves = uniswap.getReserves(address factory, address tokenA, address tokenB)
uint _amountIn = uniswap.getAmountIn()
uniswap.removeLiquidity(token, ) }
*/
function approve(address spender, uint value) external override (IERC20,IUniswapV2Pair ) returns (bool);
function allowance(address owner, address spender) external override (IERC20,IUniswapV2Pair ) view returns (uint);
function balanceOf(address owner) external override (IERC20,IUniswapV2Pair) view returns (uint);
function decimals() external view override ( IERC20,IUniswapV2Pair) returns (uint256);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external view override ( IUniswapV2Library,IUniswapV2Router01) returns (uint amountIn);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external view override (IUniswapV2Library,IUniswapV2Router01) returns (uint amountOut);
function name() external view override (IERC20,IUniswapV2Pair) returns (bytes32);
function quote(uint amountA, uint reserveA, uint reserveB) external override (IUniswapV2Library,IUniswapV2Router01) view returns (uint amountB);
function symbol() external override (IERC20,IUniswapV2Pair) view returns (bytes32);
function totalSupply() external override (IERC20,IUniswapV2Pair) view returns (uint);
function transfer(address to, uint value) external override (IERC20, IUniswapV2Pair,IWETH) returns (bool);
function transferFrom(address from, address to, uint value) external override (IERC20, IUniswapV2Pair) returns (bool);
}
|
IF YOU WANT TO CREATE PAIR HERE, BUT IF USSING IN ANOTHER PROJECT YOU HAVE TO USE FORPAIR SINCE THE PAIR IS ALREADY IS ALREADY CREATED
|
function createPair(address tokenA, address tokenB) external returns (address _pair) {
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
pair = _pair;
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
getPair[token0][token1] = pair;
allPairs.push(pair);
IUniswapV2Pair(pair).initialize(token0, token1);
}
| 13,105,849 |
./partial_match/1/0x3Fdb3bd1ab409F0CBB2c4d919b2205ac881B99ED/sources/src/governor/GovernorVotesQuorumFraction.sol
|
Returns the quorum numerator at a specific timepoint. See {quorumDenominator}./ If history is empty, fallback to old storage Optimistic search, check the latest checkpoint
|
function quorumNumerator(uint256 timepoint) public view virtual returns (uint256) {
uint256 length = _quorumNumeratorHistory._checkpoints.length;
Checkpoints.Checkpoint224 memory latest = _quorumNumeratorHistory._checkpoints[length - 1];
if (latest._key <= timepoint) {
return latest._value;
}
}
| 9,366,543 |
./full_match/137/0xDCB26075C4F28C03c758653c5a436B50D0EC37Eb/sources/contracts/rewards/RewardsController.sol
|
@inheritdoc IRewardsController
|
function handleUserStakeChanged(
address asset,
address user,
uint oldUserStake,
uint oldTotalStaked
) external {
if (msg.sender != address(solidStakingViewActions)) {
revert NotSolidStaking(msg.sender);
}
_updateAllRewardDistributionsAndUserRewardsForAsset(asset, user, oldUserStake, oldTotalStaked);
}
| 4,718,824 |
pragma solidity ^0.4.24;
/// @author David Li <[email protected]>
/// @dev basic authentication contract
/// @notice tracks list of all users
contract Authentication {
struct User {
bytes32 name;
uint256 created_at;
}
event UserCreated(address indexed _address, bytes32 _name, uint256 _created_at);
event UserUpdated(address indexed _address, bytes32 _name);
event UserDeleted(address indexed _address);
mapping (address => User) private users;
// public array that contains list of all users that have registered
address[] public allUsers;
modifier onlyExistingUser {
// Check if user exists or terminate
require(!(users[msg.sender].name == 0x0));
_;
}
modifier onlyValidName(bytes32 name) {
// Only valid names allowed
require(!(name == 0x0));
_;
}
/// @return username
function login()
public
view
onlyExistingUser
returns (bytes32) {
return (users[msg.sender].name);
}
/// @param name the username to be created.
/// @dev checks if user exists
/// If yes return user name
/// If no, check if name was sent
/// If yes, create and return user
/// @return username of created user
function signup(bytes32 name)
public
payable
onlyValidName(name)
returns (bytes32) {
if (users[msg.sender].name == 0x0)
{
users[msg.sender].name = name;
users[msg.sender].created_at = now;
allUsers.push(msg.sender);
emit UserCreated(msg.sender,name,now);
return (users[msg.sender].name);
}
return (users[msg.sender].name);
}
/// @param name updating username
/// @dev updating user name
/// @return updated username
function update(bytes32 name)
public
payable
onlyValidName(name)
onlyExistingUser
returns (bytes32) {
// Update user name.
if (users[msg.sender].name != 0x0)
{
users[msg.sender].name = name;
emit UserUpdated(msg.sender,name);
return (users[msg.sender].name);
}
}
/// @dev destroy existing username
function destroy ()
public
onlyExistingUser {
delete users[msg.sender];
emit UserDeleted(msg.sender);
}
}
|
destroy existing username
|
function destroy ()
public
onlyExistingUser {
delete users[msg.sender];
emit UserDeleted(msg.sender);
}
| 15,870,667 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol";
import "../interfaces/IUniStrategy.sol";
import "../interfaces/IUnipilot.sol";
import "../interfaces/uniswap/IUniswapLiquidityManager.sol";
import "../oracle/interfaces/IOracle.sol";
import "../libraries/LiquidityReserves.sol";
import "../libraries/FixedPoint128.sol";
import "../libraries/SafeCast.sol";
import "../libraries/LiquidityPositions.sol";
import "../libraries/UserPositions.sol";
import "./PeripheryPayments.sol";
/// @title UniswapLiquidityManager Universal Liquidity Manager of Uniswap V3
/// @notice Universal & Automated liquidity managment contract that handles liquidity of any Uniswap V3 pool
/// @dev Instead of deploying a contract each time when a new vault is created, UniswapLiquidityManager will
/// manage this in a single contract, all of the vaults are managed within one contract with users just paying
/// storage fees when creating a new vault.
/// @dev UniswapLiquidityManager always maintains 2 range orders on Uniswap V3,
/// base order: The main liquidity range -- where the majority of LP capital sits
/// limit order: A single token range -- depending on which token it holds more of after the base order was placed.
/// @dev The vault readjustment function can be called by captains or anyone to ensure
/// the liquidity of each vault remains in the most optimum range, incentive will be provided for readjustment of vault
/// @dev Vault can not be readjust more than two times in 24 hrs,
/// pool is too volatile if it requires readjustment more than 2
/// @dev User can collect fees in 2 ways:
/// 1. Claim fees in tokens with vault fare, 2. Claim all fees in PILOT
contract UniswapLiquidityManager is PeripheryPayments, IUniswapLiquidityManager {
using LowGasSafeMath for uint256;
using SafeCast for uint256;
address private immutable uniswapFactory;
uint128 private constant MAX_UINT128 = type(uint128).max;
uint8 private _unlocked = 1;
/// @dev The token ID position data of the user
mapping(uint256 => Position) private positions;
/// @dev The data of the Unipilot base & range orders
mapping(address => LiquidityPosition) private liquidityPositions;
UnipilotProtocolDetails private unipilotProtocolDetails;
modifier onlyUnipilot() {
_isUnipilot();
_;
}
modifier onlyGovernance() {
_isGovernance();
_;
}
modifier nonReentrant() {
require(_unlocked == 1);
_unlocked = 0;
_;
_unlocked = 1;
}
constructor(UnipilotProtocolDetails memory params, address _uniswapFactory) {
unipilotProtocolDetails = params;
uniswapFactory = _uniswapFactory;
}
function userPositions(uint256 tokenId)
external
view
override
returns (Position memory)
{
return positions[tokenId];
}
function poolPositions(address pool)
external
view
override
returns (LiquidityPosition memory)
{
return liquidityPositions[pool];
}
/// @dev Blacklist/Whitelist swapping for getting pool in range & premium for readjust liquidity
/// @param pool Address of the uniswap v3 pool
/// @param feesInPilot_ Additional premium of a user as an incentive for optimization of vaults.
/// @param managed_ P
function setPoolIncentives(
address pool,
bool feesInPilot_,
bool managed_,
address oracle0,
address oracle1
) external onlyGovernance {
LiquidityPosition storage lp = liquidityPositions[pool];
lp.feesInPilot = feesInPilot_;
lp.managed = managed_;
lp.oracle0 = oracle0;
lp.oracle1 = oracle1;
}
/// @dev Sets the new details for unipilot protocol
function setPilotProtocolDetails(UnipilotProtocolDetails calldata params)
external
onlyGovernance
{
unipilotProtocolDetails = params;
}
/// @notice Returns the status of runnng readjust function, the limit is set to 2 readjusts per day
/// @param pool Address of the pool
/// @return status Pool rebase status
function readjustFrequencyStatus(address pool) public returns (bool status) {
LiquidityPosition storage lp = liquidityPositions[pool];
if (block.timestamp - lp.timestamp > 900) {
// change for mainnet
lp.counter = 0;
lp.status = false;
}
status = lp.status;
}
/// @inheritdoc IUniswapLiquidityManager
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external override {
address sender = msg.sender;
MintCallbackData memory decoded = abi.decode(data, (MintCallbackData));
_verifyCallback(decoded.token0, decoded.token1, decoded.fee);
if (amount0Owed > 0) pay(decoded.token0, decoded.payer, sender, amount0Owed);
if (amount1Owed > 0) pay(decoded.token1, decoded.payer, sender, amount1Owed);
}
/// @inheritdoc IUniswapLiquidityManager
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
address recipient = msg.sender;
SwapCallbackData memory decoded = abi.decode(data, (SwapCallbackData));
_verifyCallback(decoded.token0, decoded.token1, decoded.fee);
if (amount0Delta > 0)
pay(decoded.token0, address(this), recipient, uint256(amount0Delta));
if (amount1Delta > 0)
pay(decoded.token1, address(this), recipient, uint256(amount1Delta));
}
/// @inheritdoc IUniswapLiquidityManager
function getReserves(
address token0,
address token1,
bytes calldata data
)
external
view
override
returns (
uint256 totalAmount0,
uint256 totalAmount1,
uint256 totalLiquidity
)
{
uint24 fee = abi.decode(data, (uint24));
address pool = getPoolAddress(token0, token1, fee);
(totalAmount0, totalAmount1, totalLiquidity) = updatePositionTotalAmounts(pool);
}
/// @notice Returns maximum amount of fees owed to a specific user position
/// @dev Updates the unipilot base & range positions in order to fetch updated amount of user fees
/// @param tokenId The ID of the Unpilot NFT for which tokens will be collected
/// @return fees0 Amount of fees in token0
/// @return fees1 Amount of fees in token1
function getUserFees(uint256 tokenId)
external
returns (uint256 fees0, uint256 fees1)
{
Position memory position = positions[tokenId];
_collectPositionFees(position.pool);
LiquidityPosition memory lp = liquidityPositions[position.pool];
(uint256 tokensOwed0, uint256 tokensOwed1) = UserPositions.getTokensOwedAmount(
position.feeGrowth0,
position.feeGrowth1,
position.liquidity,
lp.feeGrowthGlobal0,
lp.feeGrowthGlobal1
);
fees0 = position.tokensOwed0.add(tokensOwed0);
fees1 = position.tokensOwed1.add(tokensOwed1);
}
/// @inheritdoc IUniswapLiquidityManager
function createPair(
address _token0,
address _token1,
bytes memory data
) external override returns (address _pool) {
(uint24 _fee, uint160 _sqrtPriceX96) = abi.decode(data, (uint24, uint160));
_pool = IUniswapV3Factory(uniswapFactory).createPool(_token0, _token1, _fee);
IUniswapV3Pool(_pool).initialize(_sqrtPriceX96);
emit PoolCreated(_token0, _token1, _pool, _fee, _sqrtPriceX96);
}
/// @inheritdoc IUniswapLiquidityManager
function deposit(
address token0,
address token1,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 shares,
uint256 tokenId,
bool isTokenMinted,
bytes memory data
) external payable override onlyUnipilot {
DepositVars memory b;
b.fee = abi.decode(data, (uint24));
b.pool = getPoolAddress(token0, token1, b.fee);
LiquidityPosition storage poolPosition = liquidityPositions[b.pool];
// updating the feeGrowthGlobal of pool for new user
if (poolPosition.totalLiquidity > 0) _collectPositionFees(b.pool);
(
b.amount0Base,
b.amount1Base,
b.amount0Range,
b.amount1Range
) = _addLiquidityInManager(
AddLiquidityManagerParams({
pool: b.pool,
amount0Desired: amount0Desired,
amount1Desired: amount1Desired,
shares: shares
})
);
if (!isTokenMinted) {
Position storage userPosition = positions[tokenId];
require(b.pool == userPosition.pool);
userPosition.tokensOwed0 += FullMath.mulDiv(
poolPosition.feeGrowthGlobal0 - userPosition.feeGrowth0,
userPosition.liquidity,
FixedPoint128.Q128
);
userPosition.tokensOwed1 += FullMath.mulDiv(
poolPosition.feeGrowthGlobal1 - userPosition.feeGrowth1,
userPosition.liquidity,
FixedPoint128.Q128
);
userPosition.liquidity += shares;
userPosition.feeGrowth0 = poolPosition.feeGrowthGlobal0;
userPosition.feeGrowth1 = poolPosition.feeGrowthGlobal1;
} else {
positions[tokenId] = Position({
nonce: 0,
pool: b.pool,
liquidity: shares,
feeGrowth0: poolPosition.feeGrowthGlobal0,
feeGrowth1: poolPosition.feeGrowthGlobal1,
tokensOwed0: 0,
tokensOwed1: 0
});
}
_checkDustAmount(
b.pool,
(b.amount0Base + b.amount0Range),
(b.amount1Base + b.amount1Range),
amount0Desired,
amount1Desired
);
emit Deposited(b.pool, tokenId, amount0Desired, amount1Desired, shares);
}
/// @inheritdoc IUniswapLiquidityManager
function withdraw(
bool pilotToken,
bool wethToken,
uint256 liquidity,
uint256 tokenId,
bytes memory data
) external payable override onlyUnipilot nonReentrant {
Position storage position = positions[tokenId];
require(liquidity > 0);
require(liquidity <= position.liquidity);
WithdrawVars memory c;
c.recipient = abi.decode(data, (address));
(c.amount0Removed, c.amount1Removed) = _removeLiquidityUniswap(
false,
position.pool,
liquidity
);
(c.userAmount0, c.userAmount1, c.pilotAmount) = _distributeFeesAndLiquidity(
DistributeFeesParams({
pilotToken: pilotToken,
wethToken: wethToken,
pool: position.pool,
recipient: c.recipient,
tokenId: tokenId,
liquidity: liquidity,
amount0Removed: c.amount0Removed,
amount1Removed: c.amount1Removed
})
);
emit Withdrawn(
position.pool,
c.recipient,
tokenId,
c.amount0Removed,
c.amount1Removed
);
}
/// @inheritdoc IUniswapLiquidityManager
function collect(
bool pilotToken,
bool wethToken,
uint256 tokenId,
bytes memory data
) external payable override onlyUnipilot nonReentrant {
Position memory position = positions[tokenId];
require(position.liquidity > 0);
address recipient = abi.decode(data, (address));
_collectPositionFees(position.pool);
_distributeFeesAndLiquidity(
DistributeFeesParams({
pilotToken: pilotToken,
wethToken: wethToken,
pool: position.pool,
recipient: recipient,
tokenId: tokenId,
liquidity: 0,
amount0Removed: 0,
amount1Removed: 0
})
);
}
/// @dev Returns the status of the vault that needs reabsing
function shouldReadjust(
address pool,
int24 baseTickLower,
int24 baseTickUpper
) public view returns (bool readjust) {
(, , , , , , int24 currentTick, int24 tickSpacing) = getPoolDetails(pool);
int24 threshold = IUniStrategy(unipilotProtocolDetails.uniStrategy)
.getReadjustThreshold(pool);
if (
(currentTick < (baseTickLower + threshold)) ||
(currentTick > (baseTickUpper - threshold))
) {
readjust = true;
} else {
readjust = false;
}
}
function getPoolDetails(address pool)
internal
view
returns (
address token0,
address token1,
uint24 fee,
uint16 poolCardinality,
uint128 liquidity,
uint160 sqrtPriceX96,
int24 currentTick,
int24 tickSpacing
)
{
IUniswapV3Pool uniswapPool = IUniswapV3Pool(pool);
token0 = uniswapPool.token0();
token1 = uniswapPool.token1();
fee = uniswapPool.fee();
liquidity = uniswapPool.liquidity();
(sqrtPriceX96, currentTick, , poolCardinality, , , ) = uniswapPool.slot0();
tickSpacing = uniswapPool.tickSpacing();
}
/// @notice burns all positions, collects any fees accrued and mints new base & range positions for vault.
/// @dev This function can be called by anyone, also user gets the tx fees + premium on chain for readjusting the vault
/// @dev Only those vaults are eligible for readjust incentive that have liquidity greater than 100,000 USD through Unipilot,
/// @dev Pools can be readjust 2 times in 24 hrs (more than 2 requirement means pool is too volatile)
/// @dev If all assets are converted in a single token then 2% amount will be swapped from vault total liquidity
/// in order to add in range liquidity rather than waiting for price to come in range
function readjustLiquidity(
address token0,
address token1,
uint24 fee
) external {
// @dev calculating the gas amount at the begining
uint256 initialGas = gasleft();
ReadjustVars memory b;
b.poolAddress = getPoolAddress(token0, token1, fee);
LiquidityPosition storage position = liquidityPositions[b.poolAddress];
require(!readjustFrequencyStatus(b.poolAddress));
require(
shouldReadjust(b.poolAddress, position.baseTickLower, position.baseTickUpper)
);
position.timestamp = block.timestamp;
(, , , , , b.sqrtPriceX96, , ) = getPoolDetails(b.poolAddress);
(b.amount0, b.amount1) = _removeLiquidityUniswap(
true,
b.poolAddress,
position.totalLiquidity
);
if ((b.amount0 == 0 || b.amount1 == 0)) {
(b.zeroForOne, b.amountIn) = b.amount0 > 0
? (true, b.amount0)
: (false, b.amount1);
b.exactSqrtPriceImpact =
(b.sqrtPriceX96 * (unipilotProtocolDetails.swapPriceThreshold / 2)) /
1e6;
b.sqrtPriceLimitX96 = b.zeroForOne
? b.sqrtPriceX96 - b.exactSqrtPriceImpact
: b.sqrtPriceX96 + b.exactSqrtPriceImpact;
b.amountIn = FullMath.mulDiv(
b.amountIn,
unipilotProtocolDetails.swapPercentage,
100
);
(int256 amount0Delta, int256 amount1Delta) = IUniswapV3Pool(b.poolAddress)
.swap(
address(this),
b.zeroForOne,
b.amountIn.toInt256(),
b.sqrtPriceLimitX96,
abi.encode(
(SwapCallbackData({ token0: token0, token1: token1, fee: fee }))
)
);
if (amount1Delta < 1) {
amount1Delta = -amount1Delta;
b.amount0 = b.amount0.sub(uint256(amount0Delta));
b.amount1 = b.amount1.add(uint256(amount1Delta));
} else {
amount0Delta = -amount0Delta;
b.amount0 = b.amount0.add(uint256(amount0Delta));
b.amount1 = b.amount1.sub(uint256(amount1Delta));
}
}
// @dev calculating new ticks for base & range positions
Tick memory ticks;
(
ticks.baseTickLower,
ticks.baseTickUpper,
ticks.bidTickLower,
ticks.bidTickUpper,
ticks.rangeTickLower,
ticks.rangeTickUpper
) = _getTicksFromUniStrategy(b.poolAddress);
(b.baseLiquidity, b.amount0Added, b.amount1Added, ) = _addLiquidityUniswap(
AddLiquidityParams({
token0: token0,
token1: token1,
fee: fee,
tickLower: ticks.baseTickLower,
tickUpper: ticks.baseTickUpper,
amount0Desired: b.amount0,
amount1Desired: b.amount1
})
);
(position.baseLiquidity, position.baseTickLower, position.baseTickUpper) = (
b.baseLiquidity,
ticks.baseTickLower,
ticks.baseTickUpper
);
uint256 amount0Remaining = b.amount0.sub(b.amount0Added);
uint256 amount1Remaining = b.amount1.sub(b.amount1Added);
(uint128 bidLiquidity, , ) = LiquidityReserves.getLiquidityAmounts(
ticks.bidTickLower,
ticks.bidTickUpper,
0,
amount0Remaining,
amount1Remaining,
IUniswapV3Pool(b.poolAddress)
);
(uint128 rangeLiquidity, , ) = LiquidityReserves.getLiquidityAmounts(
ticks.rangeTickLower,
ticks.rangeTickUpper,
0,
amount0Remaining,
amount1Remaining,
IUniswapV3Pool(b.poolAddress)
);
// @dev adding bid or range order on Uniswap depending on which token is left
if (bidLiquidity > rangeLiquidity) {
(, b.amount0Range, b.amount1Range, ) = _addLiquidityUniswap(
AddLiquidityParams({
token0: token0,
token1: token1,
fee: fee,
tickLower: ticks.bidTickLower,
tickUpper: ticks.bidTickUpper,
amount0Desired: amount0Remaining,
amount1Desired: amount1Remaining
})
);
(
position.rangeLiquidity,
position.rangeTickLower,
position.rangeTickUpper
) = (bidLiquidity, ticks.bidTickLower, ticks.bidTickUpper);
} else {
(, b.amount0Range, b.amount1Range, ) = _addLiquidityUniswap(
AddLiquidityParams({
token0: token0,
token1: token1,
fee: fee,
tickLower: ticks.rangeTickLower,
tickUpper: ticks.rangeTickUpper,
amount0Desired: amount0Remaining,
amount1Desired: amount1Remaining
})
);
(
position.rangeLiquidity,
position.rangeTickLower,
position.rangeTickUpper
) = (rangeLiquidity, ticks.rangeTickLower, ticks.rangeTickUpper);
}
position.counter += 1;
if (position.counter == 2) position.status = true;
if (position.managed) {
require(tx.gasprice <= unipilotProtocolDetails.gasPriceLimit);
b.gasUsed = (tx.gasprice.mul(initialGas.sub(gasleft()))).add(
unipilotProtocolDetails.premium
);
b.pilotAmount = IOracle(unipilotProtocolDetails.oracle).ethToAsset(
PILOT,
unipilotProtocolDetails.pilotWethPair,
b.gasUsed
);
_mintPilot(msg.sender, b.pilotAmount);
}
_checkDustAmount(
b.poolAddress,
(b.amount0Added + b.amount0Range),
(b.amount1Added + b.amount1Range),
b.amount0,
b.amount1
);
emit PoolReajusted(
b.poolAddress,
position.baseLiquidity,
position.rangeLiquidity,
position.baseTickLower,
position.baseTickUpper,
position.rangeTickLower,
position.rangeTickUpper
);
}
function emergencyExit(address recipient, bytes[10] memory data)
external
onlyGovernance
{
for (uint256 i = 0; i < data.length; ++i) {
(
address token,
address pool,
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) = abi.decode(data[i], (address, address, int24, int24, uint128));
if (pool != address(0)) {
IUniswapV3Pool(pool).burn(tickLower, tickUpper, liquidity);
IUniswapV3Pool(pool).collect(
recipient,
tickLower,
tickUpper,
MAX_UINT128,
MAX_UINT128
);
}
uint256 balanceToken = IERC20(token).balanceOf(address(this));
if (balanceToken > 0) {
TransferHelper.safeTransfer(token, recipient, balanceToken);
}
}
}
/// @inheritdoc IUniswapLiquidityManager
function updatePositionTotalAmounts(address _pool)
public
view
override
returns (
uint256 amount0,
uint256 amount1,
uint256 totalLiquidity
)
{
LiquidityPosition memory position = liquidityPositions[_pool];
if (position.totalLiquidity > 0) {
return LiquidityPositions.getTotalAmounts(position, _pool);
}
}
function getPoolAddress(
address token0,
address token1,
uint24 fee
) private view returns (address) {
return IUniswapV3Factory(uniswapFactory).getPool(token0, token1, fee);
}
function _isUnipilot() private view {
require(msg.sender == unipilotProtocolDetails.unipilot);
}
function _isGovernance() private view {
require(msg.sender == IUnipilot(unipilotProtocolDetails.unipilot).governance());
}
function _mintPilot(address recipient, uint256 amount) private {
IUnipilot(unipilotProtocolDetails.unipilot).mintPilot(recipient, amount);
}
/// @dev fetches the new ticks for base and range positions
function _getTicksFromUniStrategy(address pool)
private
returns (
int24 baseTickLower,
int24 baseTickUpper,
int24 bidTickLower,
int24 bidTickUpper,
int24 rangeTickLower,
int24 rangeTickUpper
)
{
return IUniStrategy(unipilotProtocolDetails.uniStrategy).getTicks(pool);
}
/// @dev checks the dust amount durnig deposit
function _checkDustAmount(
address pool,
uint256 amount0Added,
uint256 amount1Added,
uint256 amount0Desired,
uint256 amount1Desired
) private {
LiquidityPosition storage poolPosition = liquidityPositions[pool];
uint256 dust0 = amount0Desired.sub(amount0Added);
uint256 dust1 = amount1Desired.sub(amount1Added);
if (dust0 > 0) {
poolPosition.fees0 += dust0;
poolPosition.feeGrowthGlobal0 += FullMath.mulDiv(
dust0,
FixedPoint128.Q128,
poolPosition.totalLiquidity
);
}
if (dust1 > 0) {
poolPosition.fees1 += dust1;
poolPosition.feeGrowthGlobal1 += FullMath.mulDiv(
dust1,
FixedPoint128.Q128,
poolPosition.totalLiquidity
);
}
}
/// @dev Do zero-burns to poke a position on Uniswap so earned fees are
/// updated. Should be called if total amounts needs to include up-to-date
/// fees.
function _updatePosition(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
IUniswapV3Pool pool
) private {
if (liquidity > 0) {
pool.burn(tickLower, tickUpper, 0);
}
}
/// @notice Deposits user liquidity in a range order of Unipilot vault.
/// @dev If the liquidity of vault is out of range then contract will add user liquidity in a range position
/// of the vault, user liquidity gets in range as soon as vault will be rebase again by anyone
/// @param pool Address of the uniswap pool
/// @param amount0 The desired amount of token0 to be spent
/// @param amount1 The desired amount of token1 to be spent,
/// @param shares Amount of shares minted
function _addRangeLiquidity(
address pool,
uint256 amount0,
uint256 amount1,
uint256 shares
) private returns (uint256 amount0Range, uint256 amount1Range) {
RangeLiquidityVars memory b;
(b.token0, b.token1, b.fee, , , , , ) = getPoolDetails(pool);
LiquidityPosition storage position = liquidityPositions[pool];
(b.rangeLiquidity, b.amount0Range, b.amount1Range, ) = _addLiquidityUniswap(
AddLiquidityParams({
token0: b.token0,
token1: b.token1,
fee: b.fee,
tickLower: position.rangeTickLower,
tickUpper: position.rangeTickUpper,
amount0Desired: amount0,
amount1Desired: amount1
})
);
position.rangeLiquidity += b.rangeLiquidity;
position.totalLiquidity += shares;
(amount0Range, amount1Range) = (b.amount0Range, b.amount1Range);
}
/// @dev Deposits liquidity in a range on the UniswapV3 pool.
/// @param params The params necessary to mint a position, encoded as `AddLiquidityParams`
/// @return liquidity Amount of liquidity added in a range on UniswapV3
/// @return amount0 Amount of token0 added in a range
/// @return amount1 Amount of token1 added in a range
/// @return pool Instance of the UniswapV3 pool
function _addLiquidityUniswap(AddLiquidityParams memory params)
private
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1,
IUniswapV3Pool pool
)
{
pool = IUniswapV3Pool(getPoolAddress(params.token0, params.token1, params.fee));
(liquidity, , ) = LiquidityReserves.getLiquidityAmounts(
params.tickLower,
params.tickUpper,
0,
params.amount0Desired,
params.amount1Desired,
pool
);
(amount0, amount1) = pool.mint(
address(this),
params.tickLower,
params.tickUpper,
liquidity,
abi.encode(
(
MintCallbackData({
payer: address(this),
token0: params.token0,
token1: params.token1,
fee: params.fee
})
)
)
);
}
function _removeLiquiditySingle(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 liquiditySharePercentage,
IUniswapV3Pool pool
) private returns (RemoveLiquidity memory removedLiquidity) {
uint256 amount0;
uint256 amount1;
uint128 liquidityRemoved = _uint256ToUint128(
FullMath.mulDiv(liquidity, liquiditySharePercentage, 1e18)
);
if (liquidity > 0) {
(amount0, amount1) = pool.burn(tickLower, tickUpper, liquidityRemoved);
}
(uint256 collect0, uint256 collect1) = pool.collect(
address(this),
tickLower,
tickUpper,
MAX_UINT128,
MAX_UINT128
);
removedLiquidity = RemoveLiquidity(
amount0,
amount1,
liquidityRemoved,
collect0.sub(amount0),
collect1.sub(amount1)
);
}
/// @dev Do zero-burns to poke a position on Uniswap so earned fees & feeGrowthGlobal of vault are updated
function _collectPositionFees(address _pool) private {
LiquidityPosition storage position = liquidityPositions[_pool];
IUniswapV3Pool pool = IUniswapV3Pool(_pool);
_updatePosition(
position.baseTickLower,
position.baseTickUpper,
position.baseLiquidity,
pool
);
_updatePosition(
position.rangeTickLower,
position.rangeTickUpper,
position.rangeLiquidity,
pool
);
(uint256 collect0Base, uint256 collect1Base) = pool.collect(
address(this),
position.baseTickLower,
position.baseTickUpper,
MAX_UINT128,
MAX_UINT128
);
(uint256 collect0Range, uint256 collect1Range) = pool.collect(
address(this),
position.rangeTickLower,
position.rangeTickUpper,
MAX_UINT128,
MAX_UINT128
);
position.fees0 = position.fees0.add((collect0Base.add(collect0Range)));
position.fees1 = position.fees1.add((collect1Base.add(collect1Range)));
position.feeGrowthGlobal0 += FullMath.mulDiv(
collect0Base + collect0Range,
FixedPoint128.Q128,
position.totalLiquidity
);
position.feeGrowthGlobal1 += FullMath.mulDiv(
collect1Base + collect1Range,
FixedPoint128.Q128,
position.totalLiquidity
);
}
/// @notice Increases the amount of liquidity in a base & range positions of the vault, with tokens paid by the sender
/// @param pool Address of the uniswap pool
/// @param amount0Desired The desired amount of token0 to be spent
/// @param amount1Desired The desired amount of token1 to be spent,
/// @param shares Amount of shares minted
function _increaseLiquidity(
address pool,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 shares
)
private
returns (
uint256 amount0Base,
uint256 amount1Base,
uint256 amount0Range,
uint256 amount1Range
)
{
LiquidityPosition storage position = liquidityPositions[pool];
IncreaseParams memory a;
(a.token0, a.token1, a.fee, , , , a.currentTick, ) = getPoolDetails(pool);
if (
a.currentTick < position.baseTickLower ||
a.currentTick > position.baseTickUpper
) {
(amount0Range, amount1Range) = _addRangeLiquidity(
pool,
amount0Desired,
amount1Desired,
shares
);
} else {
uint256 liquidityOffset = a.currentTick >= position.rangeTickLower &&
a.currentTick <= position.rangeTickUpper
? 1
: 0;
(a.baseLiquidity, a.baseAmount0, a.baseAmount1, ) = _addLiquidityUniswap(
AddLiquidityParams({
token0: a.token0,
token1: a.token1,
fee: a.fee,
tickLower: position.baseTickLower,
tickUpper: position.baseTickUpper,
amount0Desired: amount0Desired.sub(liquidityOffset),
amount1Desired: amount1Desired.sub(liquidityOffset)
})
);
(a.rangeLiquidity, a.rangeAmount0, a.rangeAmount1, ) = _addLiquidityUniswap(
AddLiquidityParams({
token0: a.token0,
token1: a.token1,
fee: a.fee,
tickLower: position.rangeTickLower,
tickUpper: position.rangeTickUpper,
amount0Desired: amount0Desired.sub(a.baseAmount0),
amount1Desired: amount1Desired.sub(a.baseAmount1)
})
);
position.baseLiquidity += a.baseLiquidity;
position.rangeLiquidity += a.rangeLiquidity;
position.totalLiquidity += shares;
(amount0Base, amount1Base) = (a.baseAmount0, a.baseAmount1);
(amount0Range, amount1Range) = (a.rangeAmount0, a.rangeAmount1);
}
}
/// @dev Two orders are placed - a base order and a range order. The base
/// order is placed first with as much liquidity as possible. This order
/// should use up all of one token, leaving only the other one. This excess
/// amount is then placed as a single-sided bid or ask order.
function _addLiquidityInManager(AddLiquidityManagerParams memory params)
private
returns (
uint256 amount0Base,
uint256 amount1Base,
uint256 amount0Range,
uint256 amount1Range
)
{
TokenDetails memory tokenDetails;
(
tokenDetails.token0,
tokenDetails.token1,
tokenDetails.fee,
tokenDetails.poolCardinality,
,
,
tokenDetails.currentTick,
) = getPoolDetails(params.pool);
LiquidityPosition storage position = liquidityPositions[params.pool];
if (position.totalLiquidity > 0) {
(amount0Base, amount1Base, amount0Range, amount1Range) = _increaseLiquidity(
params.pool,
params.amount0Desired,
params.amount1Desired,
params.shares
);
} else {
if (tokenDetails.poolCardinality < 80)
IUniswapV3Pool(params.pool).increaseObservationCardinalityNext(80);
// @dev calculate new ticks for base & range order
Tick memory ticks;
(
ticks.baseTickLower,
ticks.baseTickUpper,
ticks.bidTickLower,
ticks.bidTickUpper,
ticks.rangeTickLower,
ticks.rangeTickUpper
) = _getTicksFromUniStrategy(params.pool);
if (position.baseTickLower != 0 && position.baseTickUpper != 0) {
if (
tokenDetails.currentTick < position.baseTickLower ||
tokenDetails.currentTick > position.baseTickUpper
) {
(amount0Range, amount1Range) = _addRangeLiquidity(
params.pool,
params.amount0Desired,
params.amount1Desired,
params.shares
);
}
} else {
(
tokenDetails.baseLiquidity,
tokenDetails.amount0Added,
tokenDetails.amount1Added,
) = _addLiquidityUniswap(
AddLiquidityParams({
token0: tokenDetails.token0,
token1: tokenDetails.token1,
fee: tokenDetails.fee,
tickLower: ticks.baseTickLower,
tickUpper: ticks.baseTickUpper,
amount0Desired: params.amount0Desired,
amount1Desired: params.amount1Desired
})
);
(
position.baseLiquidity,
position.baseTickLower,
position.baseTickUpper
) = (
tokenDetails.baseLiquidity,
ticks.baseTickLower,
ticks.baseTickUpper
);
{
uint256 amount0 = params.amount0Desired.sub(
tokenDetails.amount0Added
);
uint256 amount1 = params.amount1Desired.sub(
tokenDetails.amount1Added
);
(tokenDetails.bidLiquidity, , ) = LiquidityReserves
.getLiquidityAmounts(
ticks.bidTickLower,
ticks.bidTickUpper,
0,
amount0,
amount1,
IUniswapV3Pool(params.pool)
);
(tokenDetails.rangeLiquidity, , ) = LiquidityReserves
.getLiquidityAmounts(
ticks.rangeTickLower,
ticks.rangeTickUpper,
0,
amount0,
amount1,
IUniswapV3Pool(params.pool)
);
// adding bid or range order on Uniswap depending on which token is left
if (tokenDetails.bidLiquidity > tokenDetails.rangeLiquidity) {
(, amount0Range, amount1Range, ) = _addLiquidityUniswap(
AddLiquidityParams({
token0: tokenDetails.token0,
token1: tokenDetails.token1,
fee: tokenDetails.fee,
tickLower: ticks.bidTickLower,
tickUpper: ticks.bidTickUpper,
amount0Desired: amount0,
amount1Desired: amount1
})
);
(
position.rangeLiquidity,
position.rangeTickLower,
position.rangeTickUpper
) = (
tokenDetails.bidLiquidity,
ticks.bidTickLower,
ticks.bidTickUpper
);
(amount0Base, amount1Base) = (
tokenDetails.amount0Added,
tokenDetails.amount1Added
);
} else {
(, amount0Range, amount1Range, ) = _addLiquidityUniswap(
AddLiquidityParams({
token0: tokenDetails.token0,
token1: tokenDetails.token1,
fee: tokenDetails.fee,
tickLower: ticks.rangeTickLower,
tickUpper: ticks.rangeTickUpper,
amount0Desired: amount0,
amount1Desired: amount1
})
);
(
position.rangeLiquidity,
position.rangeTickLower,
position.rangeTickUpper
) = (
tokenDetails.rangeLiquidity,
ticks.rangeTickLower,
ticks.rangeTickUpper
);
(amount0Base, amount1Base) = (
tokenDetails.amount0Added,
tokenDetails.amount1Added
);
}
}
position.totalLiquidity = position.totalLiquidity.add(params.shares);
}
}
}
/// @notice Convert 100% fees of the user in PILOT and transfer it to user
/// @dev token0 & token1 amount of user fees will be transfered to index fund
/// @param _recipient The account that should receive the PILOT,
/// @param _token0 The address of the token0 for a specific pool
/// @param _token1 The address of the token0 for a specific pool
/// @param _tokensOwed0 The uncollected amount of token0 fees to the user position as of the last computation
/// @param _tokensOwed1 The uncollected amount of token1 fees to the user position as of the last computation
function _distributeFeesInPilot(
address _recipient,
address _token0,
address _token1,
uint256 _tokensOwed0,
uint256 _tokensOwed1,
address _oracle0,
address _oracle1
) private returns (uint256 _pilotAmount) {
// if the incoming pair is weth pair then compute the amount
// of PILOT w.r.t alt token amount and the weth amount
uint256 _pilotAmountInitial = _token0 == WETH
? IOracle(unipilotProtocolDetails.oracle).getPilotAmountWethPair(
_token1,
_tokensOwed1,
_tokensOwed0,
_oracle1
)
: IOracle(unipilotProtocolDetails.oracle).getPilotAmountForTokens(
_token0,
_token1,
_tokensOwed0,
_tokensOwed1,
_oracle0,
_oracle1
);
_pilotAmount = FullMath.mulDiv(
_pilotAmountInitial,
unipilotProtocolDetails.userPilotPercentage,
100
);
_mintPilot(_recipient, _pilotAmount);
if (_tokensOwed0 > 0)
TransferHelper.safeTransfer(
_token0,
unipilotProtocolDetails.indexFund,
_tokensOwed0
);
if (_tokensOwed1 > 0)
TransferHelper.safeTransfer(
_token1,
unipilotProtocolDetails.indexFund,
_tokensOwed1
);
}
/// @notice Distribute the maximum amount of fees after calculating the percentage of user & index fund
/// @dev Total fees of user will be distributed in two parts i.e 98% will be transferred to user & remaining 2% to index fund
/// @param wethToken Boolean if the user wants fees in WETH or ETH, always false if it is not weth/alt pair
/// @param _recipient The account that should receive the PILOT,
/// @param _token0 The address of the token0 for a specific pool
/// @param _token1 The address of the token0 for a specific pool
/// @param _tokensOwed0 The uncollected amount of token0 fees to the user position as of the last computation
/// @param _tokensOwed1 The uncollected amount of token1 fees to the user position as of the last computation
function _distributeFeesInTokens(
bool wethToken,
address _recipient,
address _token0,
address _token1,
uint256 _tokensOwed0,
uint256 _tokensOwed1
) private {
(
uint256 _indexAmount0,
uint256 _indexAmount1,
uint256 _userBalance0,
uint256 _userBalance1
) = UserPositions.getUserAndIndexShares(
_tokensOwed0,
_tokensOwed1,
unipilotProtocolDetails.feesPercentageIndexFund
);
if (_tokensOwed0 > 0) {
if (_token0 == WETH && !wethToken) {
IWETH9(WETH).withdraw(_userBalance0);
TransferHelper.safeTransferETH(_recipient, _userBalance0);
} else {
TransferHelper.safeTransfer(_token0, _recipient, _userBalance0);
}
TransferHelper.safeTransfer(
_token0,
unipilotProtocolDetails.indexFund,
_indexAmount0
);
}
if (_tokensOwed1 > 0) {
if (_token1 == WETH && !wethToken) {
IWETH9(WETH).withdraw(_userBalance1);
TransferHelper.safeTransferETH(_recipient, _userBalance1);
} else {
TransferHelper.safeTransfer(_token1, _recipient, _userBalance1);
}
TransferHelper.safeTransfer(
_token1,
unipilotProtocolDetails.indexFund,
_indexAmount1
);
}
}
/// @notice Transfer the amount of liquidity to user which has been removed from base & range position of the vault
/// @param _token0 The address of the token0 for a specific pool
/// @param _token1 The address of the token1 for a specific pool
/// @param wethToken Boolean whether to recieve liquidity in WETH or ETH (only valid for WETH/ALT pairs)
/// @param _recipient The account that should receive the liquidity amounts
/// @param amount0Removed The amount of token0 that has been removed from base & range positions
/// @param amount1Removed The amount of token1 that has been removed from base & range positions
function _transferLiquidity(
address _token0,
address _token1,
bool wethToken,
address _recipient,
uint256 amount0Removed,
uint256 amount1Removed
) private {
if (_token0 == WETH || _token1 == WETH) {
(
address tokenAlt,
uint256 altAmount,
address tokenWeth,
uint256 wethAmount
) = _token0 == WETH
? (_token1, amount1Removed, _token0, amount0Removed)
: (_token0, amount0Removed, _token1, amount1Removed);
if (wethToken) {
if (amount0Removed > 0)
TransferHelper.safeTransfer(tokenWeth, _recipient, wethAmount);
if (amount1Removed > 0)
TransferHelper.safeTransfer(tokenAlt, _recipient, altAmount);
} else {
if (wethAmount > 0) {
IWETH9(WETH).withdraw(wethAmount);
TransferHelper.safeTransferETH(_recipient, wethAmount);
}
if (altAmount > 0)
TransferHelper.safeTransfer(tokenAlt, _recipient, altAmount);
}
} else {
if (amount0Removed > 0)
TransferHelper.safeTransfer(_token0, _recipient, amount0Removed);
if (amount1Removed > 0)
TransferHelper.safeTransfer(_token1, _recipient, amount1Removed);
}
}
function _distributeFeesAndLiquidity(DistributeFeesParams memory params)
private
returns (
uint256 userAmount0,
uint256 userAmount1,
uint256 pilotAmount
)
{
WithdrawTokenOwedParams memory a;
LiquidityPosition storage position = liquidityPositions[params.pool];
Position storage userPosition = positions[params.tokenId];
(a.token0, a.token1, , , , , , ) = getPoolDetails(params.pool);
(a.tokensOwed0, a.tokensOwed1) = UserPositions.getTokensOwedAmount(
userPosition.feeGrowth0,
userPosition.feeGrowth1,
userPosition.liquidity,
position.feeGrowthGlobal0,
position.feeGrowthGlobal1
);
userPosition.tokensOwed0 += a.tokensOwed0;
userPosition.tokensOwed1 += a.tokensOwed1;
userPosition.feeGrowth0 = position.feeGrowthGlobal0;
userPosition.feeGrowth1 = position.feeGrowthGlobal1;
if (position.feesInPilot && params.pilotToken) {
if (a.token0 == WETH || a.token1 == WETH) {
(
address tokenAlt,
uint256 altAmount,
address altOracle,
address tokenWeth,
uint256 wethAmount,
address wethOracle
) = a.token0 == WETH
? (
a.token1,
userPosition.tokensOwed1,
position.oracle1,
a.token0,
userPosition.tokensOwed0,
position.oracle0
)
: (
a.token0,
userPosition.tokensOwed0,
position.oracle0,
a.token1,
userPosition.tokensOwed1,
position.oracle1
);
pilotAmount = _distributeFeesInPilot(
params.recipient,
tokenWeth,
tokenAlt,
wethAmount,
altAmount,
wethOracle,
altOracle
);
} else {
pilotAmount = _distributeFeesInPilot(
params.recipient,
a.token0,
a.token1,
userPosition.tokensOwed0,
userPosition.tokensOwed1,
position.oracle0,
position.oracle1
);
}
} else {
_distributeFeesInTokens(
params.wethToken,
params.recipient,
a.token0,
a.token1,
userPosition.tokensOwed0,
userPosition.tokensOwed1
);
}
_transferLiquidity(
a.token0,
a.token1,
params.wethToken,
params.recipient,
params.amount0Removed,
params.amount1Removed
);
(userAmount0, userAmount1) = (userPosition.tokensOwed0, userPosition.tokensOwed1);
position.fees0 = position.fees0.sub(userPosition.tokensOwed0);
position.fees1 = position.fees1.sub(userPosition.tokensOwed1);
userPosition.tokensOwed0 = 0;
userPosition.tokensOwed1 = 0;
userPosition.liquidity = userPosition.liquidity.sub(params.liquidity);
emit Collect(
params.tokenId,
userAmount0,
userAmount1,
pilotAmount,
params.pool,
params.recipient
);
}
/// @notice Decreases the amount of liquidity (base and range positions) from Uniswap pool and collects all fees in the process.
/// @dev Total liquidity of Unipilot vault won't decrease in readjust because same liquidity amount is added
/// again in Uniswap, total liquidity will only decrease if user is withdrawing his share from vault
/// @param isRebase Boolean for the readjust liquidity function for not decreasing the total liquidity of vault
/// @param pool Address of the Uniswap pool
/// @param liquidity Liquidity amount of vault to remove from Uniswap positions
/// @return amount0Removed The amount of token0 removed from base & range positions
/// @return amount1Removed The amount of token1 removed from base & range positions
function _removeLiquidityUniswap(
bool isRebase,
address pool,
uint256 liquidity
) private returns (uint256 amount0Removed, uint256 amount1Removed) {
LiquidityPosition storage position = liquidityPositions[pool];
IUniswapV3Pool uniswapPool = IUniswapV3Pool(pool);
uint256 liquiditySharePercentage = FullMath.mulDiv(
liquidity,
1e18,
position.totalLiquidity
);
RemoveLiquidity memory bl = _removeLiquiditySingle(
position.baseTickLower,
position.baseTickUpper,
position.baseLiquidity,
liquiditySharePercentage,
uniswapPool
);
RemoveLiquidity memory rl = _removeLiquiditySingle(
position.rangeTickLower,
position.rangeTickUpper,
position.rangeLiquidity,
liquiditySharePercentage,
uniswapPool
);
position.fees0 = position.fees0.add(bl.feesCollected0.add(rl.feesCollected0));
position.fees1 = position.fees1.add(bl.feesCollected1.add(rl.feesCollected1));
position.feeGrowthGlobal0 += FullMath.mulDiv(
bl.feesCollected0 + rl.feesCollected0,
FixedPoint128.Q128,
position.totalLiquidity
);
position.feeGrowthGlobal1 += FullMath.mulDiv(
bl.feesCollected1 + rl.feesCollected1,
FixedPoint128.Q128,
position.totalLiquidity
);
amount0Removed = bl.amount0.add(rl.amount0);
amount1Removed = bl.amount1.add(rl.amount1);
if (!isRebase) {
position.totalLiquidity = position.totalLiquidity.sub(liquidity);
}
position.baseLiquidity = position.baseLiquidity - bl.liquidityRemoved;
position.rangeLiquidity = position.rangeLiquidity - rl.liquidityRemoved;
// @dev reseting the positions to initial state if total liquidity of vault gets zero
/// in order to calculate the amounts correctly from getSharesAndAmounts
if (position.totalLiquidity == 0) {
(position.baseTickLower, position.baseTickUpper) = (0, 0);
(position.rangeTickLower, position.rangeTickUpper) = (0, 0);
}
}
/// @notice Verify that caller should be the address of a valid Uniswap V3 Pool
/// @param token0 The contract address of token0
/// @param token1 The contract address of token1
/// @param fee Fee tier of the pool
function _verifyCallback(
address token0,
address token1,
uint24 fee
) private view {
require(msg.sender == getPoolAddress(token0, token1, fee));
}
function _uint256ToUint128(uint256 value) private pure returns (uint128) {
assert(value <= type(uint128).max);
return uint128(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.7.6;
pragma abicoder v2;
interface IUniStrategy {
struct PoolStrategy {
int24 baseThreshold;
int24 rangeThreshold;
int24 maxTwapDeviation;
int24 readjustThreshold;
uint32 twapDuration;
}
event StrategyUpdated(PoolStrategy oldStrategy, PoolStrategy newStrategy);
event MaxTwapDeviationUpdated(int24 oldDeviation, int24 newDeviation);
event BaseMultiplierUpdated(int24 oldMultiplier, int24 newMultiplier);
event RangeMultiplierUpdated(int24 oldMultiplier, int24 newMultiplier);
event PriceThresholdUpdated(uint24 oldThreshold, uint24 newThreshold);
event SwapPercentageUpdated(uint8 oldPercentage, uint8 newPercentage);
event TwapDurationUpdated(uint32 oldDuration, uint32 newDuration);
function getTicks(address _pool)
external
returns (
int24 baseLower,
int24 baseUpper,
int24 bidLower,
int24 bidUpper,
int24 askLower,
int24 askUpper
);
function getReadjustThreshold(address _pool)
external
view
returns (int24 readjustThreshold);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "./IExchangeManager.sol";
interface IUnipilot {
struct DepositVars {
uint256 totalAmount0;
uint256 totalAmount1;
uint256 totalLiquidity;
uint256 shares;
}
event ExchangeWhitelisted(address newExchange);
event ExchangeStatus(address exchange, bool status);
event GovernanceUpdated(address oldGovernance, address newGovernance);
function governance() external view returns (address);
function mintProxy() external view returns (address);
function mintPilot(address recipient, uint256 amount) external;
function deposit(IExchangeManager.DepositParams memory params, bytes memory data)
external
payable
returns (uint256 amount0Added, uint256 amount1Added);
function createPoolAndDeposit(
IExchangeManager.DepositParams memory params,
bytes[2] calldata data
)
external
payable
returns (
uint256 amount0Added,
uint256 amount1Added,
uint256 mintedTokenId
);
function exchangeManagerWhitelist(address exchange) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
import "./IULMEvents.sol";
interface IUniswapLiquidityManager is IULMEvents {
struct LiquidityPosition {
// base order position
int24 baseTickLower;
int24 baseTickUpper;
uint128 baseLiquidity;
// range order position
int24 rangeTickLower;
int24 rangeTickUpper;
uint128 rangeLiquidity;
// accumulated fees
uint256 fees0;
uint256 fees1;
uint256 feeGrowthGlobal0;
uint256 feeGrowthGlobal1;
// total liquidity
uint256 totalLiquidity;
// pool premiums
bool feesInPilot;
// oracle address for tokens to fetch prices from
address oracle0;
address oracle1;
// rebase
uint256 timestamp;
uint8 counter;
bool status;
bool managed;
}
struct Position {
uint256 nonce;
address pool;
uint256 liquidity;
uint256 feeGrowth0;
uint256 feeGrowth1;
uint256 tokensOwed0;
uint256 tokensOwed1;
}
struct ReadjustVars {
bool zeroForOne;
address poolAddress;
int24 currentTick;
uint160 sqrtPriceX96;
uint160 exactSqrtPriceImpact;
uint160 sqrtPriceLimitX96;
uint128 baseLiquidity;
uint256 amount0;
uint256 amount1;
uint256 amountIn;
uint256 amount0Added;
uint256 amount1Added;
uint256 amount0Range;
uint256 amount1Range;
uint256 currentTimestamp;
uint256 gasUsed;
uint256 pilotAmount;
}
struct VarsEmerency {
address token;
address pool;
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
}
struct WithdrawVars {
address recipient;
uint256 amount0Removed;
uint256 amount1Removed;
uint256 userAmount0;
uint256 userAmount1;
uint256 pilotAmount;
}
struct WithdrawTokenOwedParams {
address token0;
address token1;
uint256 tokensOwed0;
uint256 tokensOwed1;
}
struct MintCallbackData {
address payer;
address token0;
address token1;
uint24 fee;
}
struct UnipilotProtocolDetails {
uint8 swapPercentage;
uint24 swapPriceThreshold;
uint256 premium;
uint256 gasPriceLimit;
uint256 userPilotPercentage;
uint256 feesPercentageIndexFund;
address pilotWethPair;
address oracle;
address indexFund; // 10%
address uniStrategy;
address unipilot;
}
struct SwapCallbackData {
address token0;
address token1;
uint24 fee;
}
struct AddLiquidityParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
}
struct RemoveLiquidity {
uint256 amount0;
uint256 amount1;
uint128 liquidityRemoved;
uint256 feesCollected0;
uint256 feesCollected1;
}
struct Tick {
int24 baseTickLower;
int24 baseTickUpper;
int24 bidTickLower;
int24 bidTickUpper;
int24 rangeTickLower;
int24 rangeTickUpper;
}
struct TokenDetails {
address token0;
address token1;
uint24 fee;
int24 currentTick;
uint16 poolCardinality;
uint128 baseLiquidity;
uint128 bidLiquidity;
uint128 rangeLiquidity;
uint256 amount0Added;
uint256 amount1Added;
}
struct DistributeFeesParams {
bool pilotToken;
bool wethToken;
address pool;
address recipient;
uint256 tokenId;
uint256 liquidity;
uint256 amount0Removed;
uint256 amount1Removed;
}
struct AddLiquidityManagerParams {
address pool;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 shares;
}
struct DepositVars {
uint24 fee;
address pool;
uint256 amount0Base;
uint256 amount1Base;
uint256 amount0Range;
uint256 amount1Range;
}
struct RangeLiquidityVars {
address token0;
address token1;
uint24 fee;
uint128 rangeLiquidity;
uint256 amount0Range;
uint256 amount1Range;
}
struct IncreaseParams {
address token0;
address token1;
uint24 fee;
int24 currentTick;
uint128 baseLiquidity;
uint256 baseAmount0;
uint256 baseAmount1;
uint128 rangeLiquidity;
uint256 rangeAmount0;
uint256 rangeAmount1;
}
/// @notice Pull in tokens from sender. Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay to the pool for the minted liquidity.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
/// @notice Called to `msg.sender` after minting swaping from IUniswapV3Pool#swap.
/// @dev In the implementation you must pay to the pool for swap.
/// @param amount0Delta The amount of token0 due to the pool for the swap
/// @param amount1Delta The amount of token1 due to the pool for the swap
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
/// @notice Returns the user position information associated with a given token ID.
/// @param tokenId The ID of the token that represents the position
/// @return Position
/// - nonce The nonce for permits
/// - pool Address of the uniswap V3 pool
/// - liquidity The liquidity of the position
/// - feeGrowth0 The fee growth of token0 as of the last action on the individual position
/// - feeGrowth1 The fee growth of token1 as of the last action on the individual position
/// - tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// - tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function userPositions(uint256 tokenId) external view returns (Position memory);
/// @notice Returns the vault information of unipilot base & range orders
/// @param pool Address of the Uniswap pool
/// @return LiquidityPosition
/// - baseTickLower The lower tick of the base position
/// - baseTickUpper The upper tick of the base position
/// - baseLiquidity The total liquidity of the base position
/// - rangeTickLower The lower tick of the range position
/// - rangeTickUpper The upper tick of the range position
/// - rangeLiquidity The total liquidity of the range position
/// - fees0 Total amount of fees collected by unipilot positions in terms of token0
/// - fees1 Total amount of fees collected by unipilot positions in terms of token1
/// - feeGrowthGlobal0 The fee growth of token0 collected per unit of liquidity for
/// the entire life of the unipilot vault
/// - feeGrowthGlobal1 The fee growth of token1 collected per unit of liquidity for
/// the entire life of the unipilot vault
/// - totalLiquidity Total amount of liquidity of vault including base & range orders
function poolPositions(address pool) external view returns (LiquidityPosition memory);
/// @notice Calculates the vault's total holdings of token0 and token1 - in
/// other words, how much of each token the vault would hold if it withdrew
/// all its liquidity from Uniswap.
/// @param _pool Address of the uniswap pool
/// @return amount0 Total amount of token0 in vault
/// @return amount1 Total amount of token1 in vault
/// @return totalLiquidity Total liquidity of the vault
function updatePositionTotalAmounts(address _pool)
external
view
returns (
uint256 amount0,
uint256 amount1,
uint256 totalLiquidity
);
/// @notice Calculates the vault's total holdings of TOKEN0 and TOKEN1 - in
/// other words, how much of each token the vault would hold if it withdrew
/// all its liquidity from Uniswap.
/// @dev Updates the position and return the latest reserves & liquidity.
/// @param token0 token0 of the pool
/// @param token0 token1 of the pool
/// @param data any necessary data needed to get reserves
/// @return totalAmount0 Amount of token0 in the pool of unipilot
/// @return totalAmount1 Amount of token1 in the pool of unipilot
/// @return totalLiquidity Total liquidity available in unipilot pool
function getReserves(
address token0,
address token1,
bytes calldata data
)
external
returns (
uint256 totalAmount0,
uint256 totalAmount1,
uint256 totalLiquidity
);
/// @notice Creates a new pool & then initializes the pool
/// @param _token0 The contract address of token0 of the pool
/// @param _token1 The contract address of token1 of the pool
/// @param data Necessary data needed to create pool
/// In data we will provide the `fee` amount of the v3 pool for the specified token pair,
/// also `sqrtPriceX96` The initial square root price of the pool
/// @return _pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address
function createPair(
address _token0,
address _token1,
bytes memory data
) external returns (address _pool);
/// @notice Deposits tokens in proportion to the Unipilot's current ticks, mints them
/// `Unipilot`s NFT.
/// @param token0 The first of the two tokens of the pool, sorted by address
/// @param token1 The second of the two tokens of the pool, sorted by address
/// @param amount0Desired Max amount of token0 to deposit
/// @param amount1Desired Max amount of token1 to deposit
/// @param shares Number of shares minted
/// @param tokenId Token Id of Unipilot
/// @param isTokenMinted Boolean to check the minting of new tokenId of Unipilot
/// @param data Necessary data needed to deposit
function deposit(
address token0,
address token1,
uint256 amount0Desired,
uint256 amount1Desired,
uint256 shares,
uint256 tokenId,
bool isTokenMinted,
bytes memory data
) external payable;
/// @notice withdraws the desired shares from the vault with accumulated user fees and transfers to recipient.
/// @param pilotToken whether to recieve fees in PILOT or not (valid if user is not reciving fees in token0, token1)
/// @param wethToken whether to recieve fees in WETH or ETH (only valid for WETH/ALT pairs)
/// @param liquidity The amount by which liquidity will be withdrawn
/// @param tokenId The ID of the token for which liquidity is being withdrawn
/// @param data Necessary data needed to withdraw liquidity from Unipilot
function withdraw(
bool pilotToken,
bool wethToken,
uint256 liquidity,
uint256 tokenId,
bytes memory data
) external payable;
/// @notice Collects up to a maximum amount of fees owed to a specific user position to the recipient
/// @dev User have both options whether to recieve fees in PILOT or in pool token0 & token1
/// @param pilotToken whether to recieve fees in PILOT or not (valid if user is not reciving fees in token0, token1)
/// @param wethToken whether to recieve fees in WETH or ETH (only valid for WETH/ALT pairs)
/// @param tokenId The ID of the Unpilot NFT for which tokens will be collected
/// @param data Necessary data needed to collect fees from Unipilot
function collect(
bool pilotToken,
bool wethToken,
uint256 tokenId,
bytes memory data
) external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.5;
interface IOracle {
function getPilotAmountForTokens(
address token0,
address token1,
uint256 amount0,
uint256 amount1,
address oracle0,
address oracle1
) external view returns (uint256 total);
function getPilotAmountWethPair(
address tokenAlt,
uint256 altAmount,
uint256 wethAmount,
address altOracle
) external view returns (uint256 amount);
function getPilotAmount(
address token,
uint256 amount,
address pool
) external view returns (uint256 pilotAmount);
function assetToEth(
address token,
address pool,
uint256 amountIn
) external view returns (uint256 ethAmountOut);
function ethToAsset(
address tokenOut,
address pool,
uint256 amountIn
) external view returns (uint256 amountOut);
function getPrice(
address tokenA,
address tokenB,
address pool,
uint256 _amountIn
) external view returns (uint256 amountOut);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "./PositionKey.sol";
import "./LiquidityAmounts.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityReserves {
function getLiquidityAmounts(
int24 tickLower,
int24 tickUpper,
uint128 liquidityDesired,
uint256 amount0Desired,
uint256 amount1Desired,
IUniswapV3Pool pool
)
internal
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower);
uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper);
if (liquidityDesired > 0) {
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
sqrtRatioAX96,
sqrtRatioBX96,
liquidityDesired
);
} else {
liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
sqrtRatioAX96,
sqrtRatioBX96,
amount0Desired,
amount1Desired
);
}
}
function getPositionTokenAmounts(
int24 tickLower,
int24 tickUpper,
IUniswapV3Pool pool,
uint128 liquidity
) internal view returns (uint256 amount0, uint256 amount1) {
(, amount0, amount1) = LiquidityReserves.getLiquidityAmounts(
tickLower,
tickUpper,
liquidity,
0,
0,
pool
);
}
}
// 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.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import "./PositionKey.sol";
import "./LiquidityAmounts.sol";
import "@uniswap/v3-core/contracts/libraries/TickMath.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "../interfaces/uniswap/IUniswapLiquidityManager.sol";
import "./LiquidityReserves.sol";
import "@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol";
// import "./LowGasSafeMath.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityPositions {
using LowGasSafeMath for uint256;
struct Vars {
int24 baseTickLower;
int24 baseTickUpper;
int24 rangeTickLower;
int24 rangeTickUpper;
uint256 fees0;
uint256 fees1;
uint256 totalLiquidity;
uint256 baseAmount0;
uint256 baseAmount1;
uint256 rangeAmount0;
uint256 rangeAmount1;
}
function getTotalAmounts(
IUniswapLiquidityManager.LiquidityPosition memory self,
address pool
)
internal
view
returns (
uint256 amount0,
uint256 amount1,
uint256 totalLiquidity
)
{
IUniswapV3Pool uniswapPool = IUniswapV3Pool(pool);
Vars memory localVars;
(localVars.baseAmount0, localVars.baseAmount1) = LiquidityReserves
.getPositionTokenAmounts(
self.baseTickLower,
self.baseTickUpper,
uniswapPool,
self.baseLiquidity
);
(localVars.rangeAmount0, localVars.rangeAmount1) = LiquidityReserves
.getPositionTokenAmounts(
self.rangeTickLower,
self.rangeTickUpper,
uniswapPool,
self.rangeLiquidity
);
amount0 = localVars.baseAmount0.add(localVars.rangeAmount0);
amount1 = localVars.baseAmount1.add(localVars.rangeAmount1);
totalLiquidity = self.totalLiquidity;
}
function getPoolDetails(address pool)
internal
view
returns (
address token0,
address token1,
uint24 fee,
uint16 poolCardinality,
uint128 liquidity,
uint160 sqrtPriceX96,
int24 currentTick
)
{
IUniswapV3Pool uniswapPool = IUniswapV3Pool(pool);
token0 = uniswapPool.token0();
token1 = uniswapPool.token1();
fee = uniswapPool.fee();
liquidity = uniswapPool.liquidity();
(sqrtPriceX96, currentTick, , poolCardinality, , , ) = uniswapPool.slot0();
}
function shouldReadjust(
address pool,
int24 baseTickLower,
int24 baseTickUpper
) internal view returns (bool readjust) {
int24 tickSpacing = 0;
(, , , , , , int24 currentTick) = getPoolDetails(pool);
int24 threshold = tickSpacing; // will increase thershold for mainnet to 1200
if (
(currentTick < (baseTickLower + threshold)) ||
(currentTick > (baseTickUpper - threshold))
) {
readjust = true;
} else {
readjust = false;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma abicoder v2;
import "@uniswap/v3-core/contracts/libraries/LowGasSafeMath.sol";
import "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import "../interfaces/uniswap/IUniswapLiquidityManager.sol";
import "./FixedPoint128.sol";
// import "./LowGasSafeMath.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library UserPositions {
using LowGasSafeMath for uint256;
function getTokensOwedAmount(
uint256 feeGrowth0,
uint256 feeGrowth1,
uint256 liquidity,
uint256 feeGrowthGlobal0,
uint256 feeGrowthGlobal1
) internal pure returns (uint256 tokensOwed0, uint256 tokensOwed1) {
tokensOwed0 = FullMath.mulDiv(
feeGrowthGlobal0.sub(feeGrowth0),
liquidity,
FixedPoint128.Q128
);
tokensOwed1 = FullMath.mulDiv(
feeGrowthGlobal1.sub(feeGrowth1),
liquidity,
FixedPoint128.Q128
);
}
function getUserAndIndexShares(
uint256 tokensOwed0,
uint256 tokensOwed1,
uint256 feesPercentageIndexFund
)
internal
pure
returns (
uint256 indexAmount0,
uint256 indexAmount1,
uint256 userAmount0,
uint256 userAmount1
)
{
indexAmount0 = FullMath.mulDiv(tokensOwed0, feesPercentageIndexFund, 100);
indexAmount1 = FullMath.mulDiv(tokensOwed1, feesPercentageIndexFund, 100);
userAmount0 = tokensOwed0.sub(indexAmount0);
userAmount1 = tokensOwed1.sub(indexAmount1);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
import "../interfaces/external/IWETH9.sol";
import "../libraries/TransferHelper.sol";
abstract contract PeripheryPayments {
address internal constant PILOT = 0x37C997B35C619C21323F3518B9357914E8B99525;
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
receive() external payable {}
fallback() external payable {}
/// @notice Transfers the full amount of a token held by this contract to recipient (In case of Emergency transfer tokens out of vault)
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) internal {
uint256 balanceToken = IERC20(token).balanceOf(address(this));
require(balanceToken >= amountMinimum, "IT");
if (balanceToken > 0) {
TransferHelper.safeTransfer(token, recipient, balanceToken);
}
}
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) internal {
uint256 balanceWETH9 = IWETH9(WETH).balanceOf(address(this));
require(balanceWETH9 >= amountMinimum, "IW");
if (balanceWETH9 > 0) {
IWETH9(WETH).withdraw(balanceWETH9);
TransferHelper.safeTransferETH(recipient, balanceWETH9);
}
}
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() internal {
if (address(this).balance > 0)
TransferHelper.safeTransferETH(msg.sender, address(this).balance);
}
/// @param token The token to pay
/// @param payer The entity that must pay
/// @param recipient The entity that will receive payment
/// @param value The amount to pay
function pay(
address token,
address payer,
address recipient,
uint256 value
) internal {
if (token == WETH && address(this).balance >= value) {
// pay with WETH9
IWETH9(WETH).deposit{ value: value }(); // wrap only what is needed to pay
IWETH9(WETH).transfer(recipient, value);
} else if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
TransferHelper.safeTransfer(token, recipient, value);
} else {
// pull payment
TransferHelper.safeTransferFrom(token, payer, recipient, value);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.6;
pragma abicoder v2;
/// @notice IExchangeManager is a generalized interface for all the liquidity managers
/// @dev Contains all necessary methods that should be available in liquidity manager contracts
interface IExchangeManager {
struct DepositParams {
address recipient;
address exchangeManagerAddress;
address token0;
address token1;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 tokenId;
}
struct WithdrawParams {
bool pilotToken;
bool wethToken;
address exchangeManagerAddress;
uint256 liquidity;
uint256 tokenId;
}
struct CollectParams {
bool pilotToken;
bool wethToken;
address exchangeManagerAddress;
uint256 tokenId;
}
function createPair(
address _token0,
address _token1,
bytes calldata data
) external;
function deposit(
address token0,
address token1,
uint256 amount0,
uint256 amount1,
uint256 shares,
uint256 tokenId,
bool isTokenMinted,
bytes calldata data
) external payable;
function withdraw(
bool pilotToken,
bool wethToken,
uint256 liquidity,
uint256 tokenId,
bytes calldata data
) external;
function getReserves(
address token0,
address token1,
bytes calldata data
)
external
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
);
function collect(
bool pilotToken,
bool wethToken,
uint256 tokenId,
bytes calldata data
) external payable;
}
pragma solidity >=0.7.6;
interface IULMEvents {
event PoolCreated(
address indexed token0,
address indexed token1,
address indexed pool,
uint24 fee,
uint160 sqrtPriceX96
);
event PoolReajusted(
address pool,
uint128 baseLiquidity,
uint128 rangeLiquidity,
int24 newBaseTickLower,
int24 newBaseTickUpper,
int24 newRangeTickLower,
int24 newRangeTickUpper
);
event Deposited(
address indexed pool,
uint256 tokenId,
uint256 amount0,
uint256 amount1,
uint256 liquidity
);
event Collect(
uint256 tokenId,
uint256 userAmount0,
uint256 userAmount1,
uint256 pilotAmount,
address pool,
address recipient
);
event Withdrawn(
address indexed pool,
address indexed recipient,
uint256 tokenId,
uint256 amount0,
uint256 amount1
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
library PositionKey {
/// @dev Returns the key of the position in the core library
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// 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.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: 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.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: 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 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.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 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 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 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.7.0;
/// @title Optimized overflow and underflow safe math operations
/// @notice Contains methods for doing math operations that revert on overflow or underflow for minimal gas cost
library LowGasSafeMath {
/// @notice Returns x + y, reverts if sum overflows uint256
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
/// @notice Returns x - y, reverts if underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
/// @notice Returns x * y, reverts if overflows
/// @param x The multiplicand
/// @param y The multiplier
/// @return z The product of x and y
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(x == 0 || (z = x * y) / x == y);
}
/// @notice Returns x + y, reverts if overflows or underflows
/// @param x The augend
/// @param y The addend
/// @return z The sum of x and y
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
/// @notice Returns x - y, reverts if overflows or underflows
/// @param x The minuend
/// @param y The subtrahend
/// @return z The difference of x and y
function sub(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x - y) <= x == (y >= 0));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
import "./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-2.0-or-later
pragma solidity >=0.6.0;
// import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/external/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: MIT
pragma solidity =0.7.6;
import "./IERC20Permit.sol";
interface IERC20 is IERC20Permit {
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);
function transfer(address recipient, uint256 amount) external returns (bool);
function mint(address to, uint256 value) external;
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function burn(uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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 IERC20Permit {
/**
* @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);
}
|
checks the dust amount durnig deposit
|
function _checkDustAmount(
address pool,
uint256 amount0Added,
uint256 amount1Added,
uint256 amount0Desired,
uint256 amount1Desired
) private {
LiquidityPosition storage poolPosition = liquidityPositions[pool];
uint256 dust0 = amount0Desired.sub(amount0Added);
uint256 dust1 = amount1Desired.sub(amount1Added);
if (dust0 > 0) {
poolPosition.fees0 += dust0;
poolPosition.feeGrowthGlobal0 += FullMath.mulDiv(
dust0,
FixedPoint128.Q128,
poolPosition.totalLiquidity
);
}
if (dust1 > 0) {
poolPosition.fees1 += dust1;
poolPosition.feeGrowthGlobal1 += FullMath.mulDiv(
dust1,
FixedPoint128.Q128,
poolPosition.totalLiquidity
);
}
}
| 6,967,514 |
/**
*Submitted for verification at Etherscan.io on 2021-09-05
*/
// solhint-disable-next-line
pragma solidity 0.4.26;
// solhint-disable func-order
contract GenePoolInterface {
// signals is gene pool
function isGenePool() public pure returns (bool);
// breeds two parents and returns childs genes
function breed(uint256[2] mother, uint256[2] father, uint256 seed) public view returns (uint256[2]);
// generates (psuedo) random Pepe DNA
function randomDNA(uint256 seed) public pure returns (uint256[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 {
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;
}
}
contract Usernames {
mapping(address => bytes32) public addressToUser;
mapping(bytes32 => address) public userToAddress;
event UserNamed(address indexed user, bytes32 indexed username);
/**
* Claim a username. Frees up a previously used one
* @param _username to claim
*/
function claimUsername(bytes32 _username) external {
require(userToAddress[_username] == address(0));// Username must be free
if (addressToUser[msg.sender] != bytes32(0)) { // If user already has username free it up
userToAddress[addressToUser[msg.sender]] = address(0);
}
//all is well assign username
addressToUser[msg.sender] = _username;
userToAddress[_username] = msg.sender;
emit UserNamed(msg.sender, _username);
}
}
/** @title Beneficiary */
contract Beneficiary is Ownable {
address public beneficiary;
constructor() public {
beneficiary = msg.sender;
}
/**
* @dev Change the beneficiary address
* @param _beneficiary Address of the new beneficiary
*/
function setBeneficiary(address _beneficiary) public onlyOwner {
beneficiary = _beneficiary;
}
}
/** @title Affiliate */
contract Affiliate is Ownable {
mapping(address => bool) public canSetAffiliate;
mapping(address => address) public userToAffiliate;
/** @dev Allows an address to set the affiliate address for a user
* @param _setter The address that should be allowed
*/
function setAffiliateSetter(address _setter) public onlyOwner {
canSetAffiliate[_setter] = true;
}
/**
* @dev Set the affiliate of a user
* @param _user user to set affiliate for
* @param _affiliate address to set
*/
function setAffiliate(address _user, address _affiliate) public {
require(canSetAffiliate[msg.sender]);
if (userToAffiliate[_user] == address(0)) {
userToAffiliate[_user] = _affiliate;
}
}
}
contract ERC721 {
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) public view returns (address owner);
function approve(address _to, uint256 _tokenId) public;
function transferFrom(address _from, address _to, uint256 _tokenId) public returns (bool) ;
function transfer(address _to, uint256 _tokenId) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 tokenId);
// function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl);
}
contract PepeInterface is ERC721{
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) public returns (bool);
function getCozyAgain(uint256 _pepeId) public view returns(uint64);
}
/** @title AuctionBase */
contract AuctionBase is Beneficiary {
mapping(uint256 => PepeAuction) public auctions;//maps pepes to auctions
PepeInterface public pepeContract;
Affiliate public affiliateContract;
uint256 public fee = 37500; //in 1 10000th of a percent so 3.75% at the start
uint256 public constant FEE_DIVIDER = 1000000; //Perhaps needs better name?
struct PepeAuction {
address seller;
uint256 pepeId;
uint64 auctionBegin;
uint64 auctionEnd;
uint256 beginPrice;
uint256 endPrice;
}
event AuctionWon(uint256 indexed pepe, address indexed winner, address indexed seller);
event AuctionStarted(uint256 indexed pepe, address indexed seller);
event AuctionFinalized(uint256 indexed pepe, address indexed seller);
constructor(address _pepeContract, address _affiliateContract) public {
pepeContract = PepeInterface(_pepeContract);
affiliateContract = Affiliate(_affiliateContract);
}
/**
* @dev Return a pepe from a auction that has passed
* @param _pepeId the id of the pepe to save
*/
function savePepe(uint256 _pepeId) external {
// solhint-disable-next-line not-rely-on-time
require(auctions[_pepeId].auctionEnd < now);//auction must have ended
require(pepeContract.transfer(auctions[_pepeId].seller, _pepeId));//transfer pepe back to seller
emit AuctionFinalized(_pepeId, auctions[_pepeId].seller);
delete auctions[_pepeId];//delete auction
}
/**
* @dev change the fee on pepe sales. Can only be lowerred
* @param _fee The new fee to set. Must be lower than current fee
*/
function changeFee(uint256 _fee) external onlyOwner {
require(_fee < fee);//fee can not be raised
fee = _fee;
}
/**
* @dev Start a auction
* @param _pepeId Pepe to sell
* @param _beginPrice Price at which the auction starts
* @param _endPrice Ending price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
require(pepeContract.transferFrom(msg.sender, address(this), _pepeId));
// solhint-disable-next-line not-rely-on-time
require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active
PepeAuction memory auction;
auction.seller = msg.sender;
auction.pepeId = _pepeId;
// solhint-disable-next-line not-rely-on-time
auction.auctionBegin = uint64(now);
// solhint-disable-next-line not-rely-on-time
auction.auctionEnd = uint64(now) + _duration;
require(auction.auctionEnd > auction.auctionBegin);
auction.beginPrice = _beginPrice;
auction.endPrice = _endPrice;
auctions[_pepeId] = auction;
emit AuctionStarted(_pepeId, msg.sender);
}
/**
* @dev directly start a auction from the PepeBase contract
* @param _pepeId Pepe to put on auction
* @param _beginPrice Price at which the auction starts
* @param _endPrice Ending price of the auction
* @param _duration How long the auction should take
* @param _seller The address selling the pepe
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
require(msg.sender == address(pepeContract)); //can only be called by pepeContract
//solhint-disable-next-line not-rely-on-time
require(now > auctions[_pepeId].auctionEnd);//can only start new auction if no other is active
PepeAuction memory auction;
auction.seller = _seller;
auction.pepeId = _pepeId;
// solhint-disable-next-line not-rely-on-time
auction.auctionBegin = uint64(now);
// solhint-disable-next-line not-rely-on-time
auction.auctionEnd = uint64(now) + _duration;
require(auction.auctionEnd > auction.auctionBegin);
auction.beginPrice = _beginPrice;
auction.endPrice = _endPrice;
auctions[_pepeId] = auction;
emit AuctionStarted(_pepeId, _seller);
}
/**
* @dev Calculate the current price of a auction
* @param _pepeId the pepeID to calculate the current price for
* @return currentBid the current price for the auction
*/
function calculateBid(uint256 _pepeId) public view returns(uint256 currentBid) {
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = now - auctions[_pepeId].auctionBegin;
// If auction ended return auction end price.
// solhint-disable-next-line not-rely-on-time
if (now >= auction.auctionEnd) {
return auction.endPrice;
} else {
// Can be negative
int256 priceDifference = int256(auction.endPrice) - int256(auction.beginPrice);
// Always positive
int256 duration = int256(auction.auctionEnd) - int256(auction.auctionBegin);
// As already proven in practice by CryptoKitties:
// timePassed -> 64 bits at most
// priceDifference -> 128 bits at most
// timePassed * priceDifference -> 64 + 128 bits at most
int256 priceChange = priceDifference * int256(timePassed) / duration;
// Will be positive, both operands are less than 256 bits
int256 price = int256(auction.beginPrice) + priceChange;
return uint256(price);
}
}
/**
* @dev collect the fees from the auction
*/
function getFees() public {
beneficiary.transfer(address(this).balance);
}
}
/** @title CozyTimeAuction */
contract RebornCozyTimeAuction is AuctionBase {
// solhint-disable-next-line
constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public {
}
/**
* @dev Start an auction
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuction(_pepeId, _beginPrice, _endPrice, _duration);
}
/**
* @dev Start a auction direclty from the PepeBase smartcontract
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
* @param _seller The address of the seller
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller);
}
/**
* @dev Buy cozy right from the auction
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
*/
// solhint-disable-next-line max-line-length
function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable {
require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
require(now < auction.auctionEnd);// auction must be still going
uint256 price = calculateBid(_pepeId);
require(msg.value >= price);//must send enough ether
uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed?
//Send ETH to seller
auction.seller.transfer(price - totalFee);
//send ETH to beneficiary
address affiliate = affiliateContract.userToAffiliate(_pepeReceiver);
//solhint-disable-next-line
if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate
//nothing just to suppress warning
}
//actual cozytiming
if (_candidateAsFather) {
if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) {
revert();
}
} else {
// Swap around the two pepes, they have no set gender, the user decides what they are.
if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) {
revert();
}
}
//Send pepe to seller of auction
if (!pepeContract.transfer(auction.seller, _pepeId)) {
revert(); //can't complete transfer if this fails
}
if (msg.value > price) { //return ether send to much
_pepeReceiver.transfer(msg.value - price);
}
emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event
delete auctions[_pepeId];//deletes auction
}
/**
* @dev Buy cozytime and pass along affiliate
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
* @param _affiliate Affiliate address to set
*/
//solhint-disable-next-line max-line-length
function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable {
affiliateContract.setAffiliate(_pepeReceiver, _affiliate);
buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver);
}
}
contract Genetic {
// TODO mutations
// maximum number of random mutations per chromatid
uint8 public constant R = 5;
// solhint-disable-next-line function-max-lines
function breed(uint256[2] mother, uint256[2] father, uint256 seed) internal view returns (uint256[2] memOffset) {
// Meiosis I: recombining alleles (Chromosomal crossovers)
// Note about optimization I: no cell duplication,
// producing 2 seeds/eggs per cell is enough, instead of 4 (like humans do)
// Note about optimization II: crossovers happen,
// but only 1 side of the result is computed,
// as the other side will not affect anything.
// solhint-disable-next-line no-inline-assembly
assembly {
// allocate output
// 1) get the pointer to our memory
memOffset := mload(0x40)
// 2) Change the free-memory pointer to keep our memory
// (we will only use 64 bytes: 2 values of 256 bits)
mstore(0x40, add(memOffset, 64))
// Put seed in scratchpad 0
mstore(0x0, seed)
// Also use the timestamp, best we could do to increase randomness
// without increasing costs dramatically. (Trade-off)
mstore(0x20, timestamp)
// Hash it for a universally random bitstring.
let hash := keccak256(0, 64)
// Byzantium VM does not support shift opcodes, will be introduced in Constantinople.
// Soldity itself, in non-assembly, also just uses other opcodes to simulate it.
// Optmizer should take care of inlining, just declare shiftR ourselves here.
// Where possible, better optimization is applied to make it cheaper.
function shiftR(value, offset) -> result {
result := div(value, exp(2, offset))
}
// solhint-disable max-line-length
// m_context << Instruction::SWAP1 << u256(2) << Instruction::EXP << Instruction::SWAP1 << (c_leftSigned ? Instruction::SDIV : Instruction::DIV);
// optimization: although one side consists of multiple chromatids,
// we handle them just as one long chromatid:
// only difference is that a crossover in chromatid i affects chromatid i+1.
// No big deal, order and location is random anyway
function processSide(fatherSrc, motherSrc, rngSrc) -> result {
{
// initial rngSrc bit length: 254 bits
// Run the crossovers
// =====================================================
// Pick some crossovers
// Each crossover is spaced ~64 bits on average.
// To achieve this, we get a random 7 bit number, [0, 128), for each crossover.
// 256 / 64 = 4, we need 4 crossovers,
// and will have 256 / 127 = 2 at least (rounded down).
// Get one bit determining if we should pick DNA from the father,
// or from the mother.
// This changes every crossover. (by swapping father and mother)
{
if eq(and(rngSrc, 0x1), 0) {
// Swap mother and father,
// create a temporary variable (code golf XOR swap costs more in gas)
let temp := fatherSrc
fatherSrc := motherSrc
motherSrc := temp
}
// remove the bit from rng source, 253 rng bits left
rngSrc := shiftR(rngSrc, 1)
}
// Don't push/pop this all the time, we have just enough space on stack.
let mask := 0
// Cap at 4 crossovers, no more than that.
let cap := 0
let crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON)
// remove bits from hash, e.g. 254 - 7 = 247 left.
rngSrc := shiftR(rngSrc, 7)
let crossoverPos := crossoverLen
// optimization: instead of shifting with an opcode we don't have until Constantinople,
// keep track of the a shifted number, updated using multiplications.
let crossoverPosLeading1 := 1
// solhint-disable-next-line no-empty-blocks
for { } and(lt(crossoverPos, 256), lt(cap, 4)) {
crossoverLen := and(rngSrc, 0x7f) // bin: 1111111 (7 bits ON)
// remove bits from hash, e.g. 254 - 7 = 247 left.
rngSrc := shiftR(rngSrc, 7)
crossoverPos := add(crossoverPos, crossoverLen)
cap := add(cap, 1)
} {
// Note: we go from right to left in the bit-string.
// Create a mask for this crossover.
// Example:
// 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.....
// |Prev. data ||Crossover here ||remaining data .......
//
// The crossover part is copied from the mother/father to the child.
// Create the bit-mask
// Create a bitstring that ignores the previous data:
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// First create a leading 1, just before the crossover, like:
// 00000000000010000000000000000000000000000000000000000000000000000000000.....
// Then substract 1, to get a long string of 1s
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// Now do the same for the remain part, and xor it.
// leading 1
// 00000000000000000000000000000010000000000000000000000000000000000000000000000000000000000.....
// sub 1
// 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111.....
// xor with other
// 00000000000001111111111111111111111111111111111111111111111111111111111111111111111111111.....
// 00000000000000000000000000000001111111111111111111111111111111111111111111111111111111111.....
// 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000.....
// Use the final shifted 1 of the previous crossover as the start marker
mask := sub(crossoverPosLeading1, 1)
// update for this crossover, (and will be used as start for next crossover)
crossoverPosLeading1 := mul(1, exp(2, crossoverPos))
mask := xor(mask,
sub(crossoverPosLeading1, 1)
)
// Now add the parent data to the child genotype
// E.g.
// Mask: 00000000000001111111111111111110000000000000000000000000000000000000000000000000000000000....
// Parent: 10010111001000110101011111001010001011100000000000010011000001000100000001011101111000111....
// Child (pre): 00000000000000000000000000000001111110100101111111000011001010000000101010100000110110110....
// Child (post): 00000000000000110101011111001011111110100101111111000011001010000000101010100000110110110....
// To do this, we run: child_post = child_pre | (mask & father)
result := or(result, and(mask, fatherSrc))
// Swap father and mother, next crossover will take a string from the other.
let temp := fatherSrc
fatherSrc := motherSrc
motherSrc := temp
}
// We still have a left-over part that was not copied yet
// E.g., we have something like:
// Father: | xxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxx ....
// Mother: |############ xxxxxxxxxx xxxxxxxxxxxx....
// Child: | xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx....
// The ############ still needs to be applied to the child, also,
// this can be done cheaper than in the loop above,
// as we don't have to swap anything for the next crossover or something.
// At this point we have to assume 4 crossovers ran,
// and that we only have 127 - 1 - (4 * 7) = 98 bits of randomness left.
// We stopped at the bit after the crossoverPos index, see "x":
// 000000000xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.....
// now create a leading 1 at crossoverPos like:
// 000000001000000000000000000000000000000000000000000000000000000000000000000.....
// Sub 1, get the mask for what we had.
// 000000000111111111111111111111111111111111111111111111111111111111111111111.....
// Invert, and we have the final mask:
// 111111111000000000000000000000000000000000000000000000000000000000000000000.....
mask := not(sub(crossoverPosLeading1, 1))
// Apply it to the result
result := or(result, and(mask, fatherSrc))
// Random mutations
// =====================================================
// random mutations
// Put rng source in scratchpad 0
mstore(0x0, rngSrc)
// And some arbitrary padding in scratchpad 1,
// used to create different hashes based on input size changes
mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21)
// Hash it for a universally random bitstring.
// Then reduce the number of 1s by AND-ing it with other *different* hashes.
// Each bit in mutations has a probability of 0.5^5 = 0.03125 = 3.125% to be a 1
let mutations := and(
and(
and(keccak256(0, 32), keccak256(1, 33)),
and(keccak256(2, 34), keccak256(3, 35))
),
keccak256(0, 36)
)
result := xor(result, mutations)
}
}
{
// Get 1 bit of pseudo randomness that will
// determine if side #1 will come from the left, or right side.
// Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on.
let relativeFatherSideLoc := mul(and(hash, 0x1), 0x20) // shift by 5 bits = mul by 2^5=32 (0x20)
// Either 0 or 1, shift it by 5 bits to get either 0x0 or 0x20, cheaper later on.
let relativeMotherSideLoc := mul(and(hash, 0x2), 0x10) // already shifted by 1, mul by 2^4=16 (0x10)
// Now remove the used 2 bits from the hash, 254 bits remaining now.
hash := div(hash, 4)
// Process the side, load the relevant parent data that will be used.
mstore(memOffset, processSide(
mload(add(father, relativeFatherSideLoc)),
mload(add(mother, relativeMotherSideLoc)),
hash
))
// The other side will be the opposite index: 1 -> 0, 0 -> 1
// Apply it to the location,
// which is either 0x20 (For index 1) or 0x0 for index 0.
relativeFatherSideLoc := xor(relativeFatherSideLoc, 0x20)
relativeMotherSideLoc := xor(relativeMotherSideLoc, 0x20)
mstore(0x0, seed)
// Second argument will be inverse,
// resulting in a different second hash.
mstore(0x20, not(timestamp))
// Now create another hash, for the other side
hash := keccak256(0, 64)
// Process the other side
mstore(add(memOffset, 0x20), processSide(
mload(add(father, relativeFatherSideLoc)),
mload(add(mother, relativeMotherSideLoc)),
hash
))
}
}
// Sample input:
// ["0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC","0x4444444455555555555555556666666666666644444444455555555555666666"]
//
// ["0x1111111111112222222223333311111111122222223333333331111112222222","0x7777788888888888999999999999977777777777788888888888999999997777"]
// Expected results (or similar, depends on the seed):
// 0xAAABBBBBBBBCCCCCCCCAAAAAAAAABBBBBBBBBBCCCCCCCCCAABBBBBBBCCCCCCCC < Father side A
// 0x4444444455555555555555556666666666666644444444455555555555666666 < Father side B
// 0x1111111111112222222223333311111111122222223333333331111112222222 < Mother side A
// 0x7777788888888888999999999999977777777777788888888888999999997777 < Mother side B
// xxxxxxxxxxxxxxxxx xxxxxxxxx xx
// 0xAAABBBBBBBBCCCCCD99999999998BBBBBBBBF77778888888888899999999774C < Child side A
// xxx xxxxxxxxxxx
// 0x4441111111112222222223333366666666666222223333333331111112222222 < Child side B
// And then random mutations, for gene pool expansion.
// Each bit is flipped with a 3.125% chance
// Example:
//a2c37edc61dca0ca0b199e098c80fd5a221c2ad03605b4b54332361358745042 < random hash 1
//c217d04b19a83fe497c1cf6e1e10030e455a0812a6949282feec27d67fe2baa7 < random hash 2
//2636a55f38bed26d804c63a13628e21b2d701c902ca37b2b0ca94fada3821364 < random hash 3
//86bb023a85e2da50ac233b946346a53aa070943b0a8e91c56e42ba181729a5f9 < random hash 4
//5d71456a1288ab30ddd4c955384d42e66a09d424bd7743791e3eab8e09aa13f1 < random hash 5
//0000000800800000000000000000000200000000000000000000020000000000 < resulting mutation
//aaabbbbbbbbcccccd99999999998bbbbbbbbf77778888888888899999999774c < original
//aaabbbb3bb3cccccd99999999998bbb9bbbbf7777888888888889b999999774c < mutated (= original XOR mutation)
}
// Generates (psuedo) random Pepe DNA
function randomDNA(uint256 seed) internal pure returns (uint256[2] memOffset) {
// solhint-disable-next-line no-inline-assembly
assembly {
// allocate output
// 1) get the pointer to our memory
memOffset := mload(0x40)
// 2) Change the free-memory pointer to keep our memory
// (we will only use 64 bytes: 2 values of 256 bits)
mstore(0x40, add(memOffset, 64))
// Load the seed into 1st scratchpad memory slot.
// adjacent to the additional value (used to create two distinct hashes)
mstore(0x0, seed)
// In second scratchpad slot:
// The additional value can be any word, as long as the caller uses
// it (second hash needs to be different)
mstore(0x20, 0x434f4c4c454354205045504553204f4e2043525950544f50455045532e494f21)
// // Create first element pointer of array
// mstore(memOffset, add(memOffset, 64)) // pointer 1
// mstore(add(memOffset, 32), add(memOffset, 96)) // pointer 2
// control block to auto-pop the hash.
{
// L * N * 2 * 4 = 4 * 2 * 2 * 4 = 64 bytes, 2x 256 bit hash
// Sha3 is cheaper than sha256, make use of it
let hash := keccak256(0, 64)
// Store first array value
mstore(memOffset, hash)
// Now hash again, but only 32 bytes of input,
// to ignore make the input different than the previous call,
hash := keccak256(0, 32)
mstore(add(memOffset, 32), hash)
}
}
}
}
/** @title CozyTimeAuction */
contract CozyTimeAuction is AuctionBase {
// solhint-disable-next-line
constructor (address _pepeContract, address _affiliateContract) AuctionBase(_pepeContract, _affiliateContract) public {
}
/**
* @dev Start an auction
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
*/
function startAuction(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuction(_pepeId, _beginPrice, _endPrice, _duration);
}
/**
* @dev Start a auction direclty from the PepeBase smartcontract
* @param _pepeId The id of the pepe to start the auction for
* @param _beginPrice Start price of the auction
* @param _endPrice End price of the auction
* @param _duration How long the auction should take
* @param _seller The address of the seller
*/
// solhint-disable-next-line max-line-length
function startAuctionDirect(uint256 _pepeId, uint256 _beginPrice, uint256 _endPrice, uint64 _duration, address _seller) public {
// solhint-disable-next-line not-rely-on-time
require(pepeContract.getCozyAgain(_pepeId) <= now);//need to have this extra check
super.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, _seller);
}
/**
* @dev Buy cozy right from the auction
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
*/
// solhint-disable-next-line max-line-length
function buyCozy(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver) public payable {
require(address(pepeContract) == msg.sender); //caller needs to be the PepeBase contract
PepeAuction storage auction = auctions[_pepeId];
// solhint-disable-next-line not-rely-on-time
require(now < auction.auctionEnd);// auction must be still going
uint256 price = calculateBid(_pepeId);
require(msg.value >= price);//must send enough ether
uint256 totalFee = price * fee / FEE_DIVIDER; //safe math needed?
//Send ETH to seller
auction.seller.transfer(price - totalFee);
//send ETH to beneficiary
address affiliate = affiliateContract.userToAffiliate(_pepeReceiver);
//solhint-disable-next-line
if (affiliate != address(0) && affiliate.send(totalFee / 2)) { //if user has affiliate
//nothing just to suppress warning
}
//actual cozytiming
if (_candidateAsFather) {
if (!pepeContract.cozyTime(auction.pepeId, _cozyCandidate, _pepeReceiver)) {
revert();
}
} else {
// Swap around the two pepes, they have no set gender, the user decides what they are.
if (!pepeContract.cozyTime(_cozyCandidate, auction.pepeId, _pepeReceiver)) {
revert();
}
}
//Send pepe to seller of auction
if (!pepeContract.transfer(auction.seller, _pepeId)) {
revert(); //can't complete transfer if this fails
}
if (msg.value > price) { //return ether send to much
_pepeReceiver.transfer(msg.value - price);
}
emit AuctionWon(_pepeId, _pepeReceiver, auction.seller);//emit event
delete auctions[_pepeId];//deletes auction
}
/**
* @dev Buy cozytime and pass along affiliate
* @param _pepeId Pepe to cozy with
* @param _cozyCandidate the pepe to cozy with
* @param _candidateAsFather Is the _cozyCandidate father?
* @param _pepeReceiver address receiving the pepe after cozy time
* @param _affiliate Affiliate address to set
*/
//solhint-disable-next-line max-line-length
function buyCozyAffiliated(uint256 _pepeId, uint256 _cozyCandidate, bool _candidateAsFather, address _pepeReceiver, address _affiliate) public payable {
affiliateContract.setAffiliate(_pepeReceiver, _affiliate);
buyCozy(_pepeId, _cozyCandidate, _candidateAsFather, _pepeReceiver);
}
}
contract Haltable is Ownable {
uint256 public haltTime; //when the contract was halted
bool public halted;//is the contract halted?
uint256 public haltDuration;
uint256 public maxHaltDuration = 8 weeks;//how long the contract can be halted
modifier stopWhenHalted {
require(!halted);
_;
}
modifier onlyWhenHalted {
require(halted);
_;
}
/**
* @dev Halt the contract for a set time smaller than maxHaltDuration
* @param _duration Duration how long the contract should be halted. Must be smaller than maxHaltDuration
*/
function halt(uint256 _duration) public onlyOwner {
require(haltTime == 0); //cannot halt if it was halted before
require(_duration <= maxHaltDuration);//cannot halt for longer than maxHaltDuration
haltDuration = _duration;
halted = true;
// solhint-disable-next-line not-rely-on-time
haltTime = now;
}
/**
* @dev Unhalt the contract. Can only be called by the owner or when the haltTime has passed
*/
function unhalt() public {
// solhint-disable-next-line
require(now > haltTime + haltDuration || msg.sender == owner);//unhalting is only possible when haltTime has passed or the owner unhalts
halted = false;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
/// @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. This function MUST use 50,000 gas or less. Return of other
/// than the magic value MUST result in the transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _from The sending address
/// @param _tokenId The NFT identifier which is being transfered
/// @param data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4);
}
contract PepeBase is Genetic, Ownable, Usernames, Haltable {
uint32[15] public cozyCoolDowns = [ //determined by generation / 2
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(15 minutes),
uint32(30 minutes),
uint32(45 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
struct Pepe {
address master; //The master of the pepe
uint256[2] genotype; //all genes stored here
uint64 canCozyAgain; //time when pepe can have nice time again
uint64 generation; //what generation?
uint64 father; //father of this pepe
uint64 mother; //mommy of this pepe
uint8 coolDownIndex;
}
mapping(uint256 => bytes32) public pepeNames;
//stores all pepes
Pepe[] public pepes;
bool public implementsERC721 = true; //signal erc721 support
// solhint-disable-next-line const-name-snakecase
string public constant name = "Crypto Pepe";
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "CPEP";
mapping(address => uint256[]) private wallets;
mapping(address => uint256) public balances; //amounts of pepes per address
mapping(uint256 => address) public approved; //pepe index to address approved to transfer
mapping(address => mapping(address => bool)) public approvedForAll;
uint256 public zeroGenPepes; //how many zero gen pepes are mined
uint256 public constant MAX_PREMINE = 100;//how many pepes can be premined
uint256 public constant MAX_ZERO_GEN_PEPES = 1100; //max number of zero gen pepes
address public miner; //address of the miner contract
modifier onlyPepeMaster(uint256 _pepeId) {
require(pepes[_pepeId].master == msg.sender);
_;
}
modifier onlyAllowed(uint256 _tokenId) {
// solhint-disable-next-line max-line-length
require(msg.sender == pepes[_tokenId].master || msg.sender == approved[_tokenId] || approvedForAll[pepes[_tokenId].master][msg.sender]); //check if msg.sender is allowed
_;
}
event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId);
event PepeNamed(uint256 indexed pepeId);
constructor() public {
Pepe memory pepe0 = Pepe({
master: 0x0,
genotype: [uint256(0), uint256(0)],
canCozyAgain: 0,
father: 0,
mother: 0,
generation: 0,
coolDownIndex: 0
});
pepes.push(pepe0);
}
/**
* @dev Internal function that creates a new pepe
* @param _genoType DNA of the new pepe
* @param _mother The ID of the mother
* @param _father The ID of the father
* @param _generation The generation of the new Pepe
* @param _master The owner of this new Pepe
* @return The ID of the newly generated Pepe
*/
// solhint-disable-next-line max-line-length
function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) {
uint8 tempCoolDownIndex;
tempCoolDownIndex = uint8(_generation / 2);
if (_generation > 28) {
tempCoolDownIndex = 14;
}
Pepe memory _pepe = Pepe({
master: _master, //The master of the pepe
genotype: _genoType, //all genes stored here
canCozyAgain: 0, //time when pepe can have nice time again
father: _father, //father of this pepe
mother: _mother, //mommy of this pepe
generation: _generation, //what generation?
coolDownIndex: tempCoolDownIndex
});
if (_generation == 0) {
zeroGenPepes += 1; //count zero gen pepes
}
//push returns the new length, use it to get a new unique id
pepeId = pepes.push(_pepe) - 1;
//add it to the wallet of the master of the new pepe
addToWallet(_master, pepeId);
emit PepeBorn(_mother, _father, pepeId);
emit Transfer(address(0), _master, pepeId);
return pepeId;
}
/**
* @dev Set the miner contract. Can only be called once
* @param _miner Address of the miner contract
*/
function setMiner(address _miner) public onlyOwner {
require(miner == address(0));//can only be set once
miner = _miner;
}
/**
* @dev Mine a new Pepe. Can only be called by the miner contract.
* @param _seed Seed to be used for the generation of the DNA
* @param _receiver Address receiving the newly mined Pepe
* @return The ID of the newly mined Pepe
*/
function minePepe(uint256 _seed, address _receiver) public stopWhenHalted returns(uint256) {
require(msg.sender == miner);//only miner contract can call
require(zeroGenPepes < MAX_ZERO_GEN_PEPES);
return _newPepe(randomDNA(_seed), 0, 0, 0, _receiver);
}
/**
* @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE
* @param _amount Amount of Pepes to premine
*/
function pepePremine(uint256 _amount) public onlyOwner stopWhenHalted {
for (uint i = 0; i < _amount; i++) {
require(zeroGenPepes <= MAX_PREMINE);//can only generate set amount during premine
//create a new pepe
// 1) who's genes are based on hash of the timestamp and the number of pepes
// 2) who has no mother or father
// 3) who is generation zero
// 4) who's master is the manager
// solhint-disable-next-line
_newPepe(randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, pepes.length)))), 0, 0, 0, owner);
}
}
/**
* @dev CozyTime two Pepes together
* @param _mother The mother of the new Pepe
* @param _father The father of the new Pepe
* @param _pepeReceiver Address receiving the new Pepe
* @return If it was a success
*/
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external stopWhenHalted returns (bool) {
//cannot cozyTime with itself
require(_mother != _father);
//caller has to either be master or approved for mother
// solhint-disable-next-line max-line-length
require(pepes[_mother].master == msg.sender || approved[_mother] == msg.sender || approvedForAll[pepes[_mother].master][msg.sender]);
//caller has to either be master or approved for father
// solhint-disable-next-line max-line-length
require(pepes[_father].master == msg.sender || approved[_father] == msg.sender || approvedForAll[pepes[_father].master][msg.sender]);
//require both parents to be ready for cozytime
// solhint-disable-next-line not-rely-on-time
require(now > pepes[_mother].canCozyAgain && now > pepes[_father].canCozyAgain);
//require both mother parents not to be father
require(pepes[_mother].mother != _father && pepes[_mother].father != _father);
//require both father parents not to be mother
require(pepes[_father].mother != _mother && pepes[_father].father != _mother);
Pepe storage father = pepes[_father];
Pepe storage mother = pepes[_mother];
approved[_father] = address(0);
approved[_mother] = address(0);
uint256[2] memory newGenotype = breed(father.genotype, mother.genotype, pepes.length);
uint64 newGeneration;
newGeneration = mother.generation + 1;
if (newGeneration < father.generation + 1) { //if father generation is bigger
newGeneration = father.generation + 1;
}
_handleCoolDown(_mother);
_handleCoolDown(_father);
//sets pepe birth when mother is done
// solhint-disable-next-line max-line-length
pepes[_newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver)].canCozyAgain = mother.canCozyAgain; //_pepeReceiver becomes the master of the pepe
return true;
}
/**
* @dev Internal function to increase the coolDownIndex
* @param _pepeId The id of the Pepe to update the coolDown of
*/
function _handleCoolDown(uint256 _pepeId) internal {
Pepe storage tempPep = pepes[_pepeId];
// solhint-disable-next-line not-rely-on-time
tempPep.canCozyAgain = uint64(now + cozyCoolDowns[tempPep.coolDownIndex]);
if (tempPep.coolDownIndex < 14) {// after every cozy time pepe gets slower
tempPep.coolDownIndex++;
}
}
/**
* @dev Set the name of a Pepe. Can only be set once
* @param _pepeId ID of the pepe to name
* @param _name The name to assign
*/
function setPepeName(uint256 _pepeId, bytes32 _name) public stopWhenHalted onlyPepeMaster(_pepeId) returns(bool) {
require(pepeNames[_pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000);
pepeNames[_pepeId] = _name;
emit PepeNamed(_pepeId);
return true;
}
/**
* @dev Transfer a Pepe to the auction contract and auction it
* @param _pepeId ID of the Pepe to auction
* @param _auction Auction contract address
* @param _beginPrice Price the auction starts at
* @param _endPrice Price the auction ends at
* @param _duration How long the auction should run
*/
// solhint-disable-next-line max-line-length
function transferAndAuction(uint256 _pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public stopWhenHalted onlyPepeMaster(_pepeId) {
_transfer(msg.sender, _auction, _pepeId);//transfer pepe to auction
AuctionBase auction = AuctionBase(_auction);
auction.startAuctionDirect(_pepeId, _beginPrice, _endPrice, _duration, msg.sender);
}
/**
* @dev Approve and buy. Used to buy cozyTime in one call
* @param _pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
*/
// solhint-disable-next-line max-line-length
function approveAndBuy(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) {
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
CozyTimeAuction(_auction).buyCozy.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender); //breeding resets approval
}
/**
* @dev The same as above only pass an extra parameter
* @param _pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
* @param _affiliate Address to set as affiliate
*/
// solhint-disable-next-line max-line-length
function approveAndBuyAffiliated(uint256 _pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public stopWhenHalted payable onlyPepeMaster(_cozyCandidate) {
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
CozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(_pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); //breeding resets approval
}
/**
* @dev get Pepe information
* @param _pepeId ID of the Pepe to get information of
* @return master
* @return genotype
* @return canCozyAgain
* @return generation
* @return father
* @return mother
* @return pepeName
* @return coolDownIndex
*/
// solhint-disable-next-line max-line-length
function getPepe(uint256 _pepeId) public view returns(address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) {
Pepe storage tempPep = pepes[_pepeId];
master = tempPep.master;
genotype = tempPep.genotype;
canCozyAgain = tempPep.canCozyAgain;
generation = tempPep.generation;
father = tempPep.father;
mother = tempPep.mother;
pepeName = pepeNames[_pepeId];
coolDownIndex = tempPep.coolDownIndex;
}
/**
* @dev Get the time when a pepe can cozy again
* @param _pepeId ID of the pepe
* @return Time when the pepe can cozy again
*/
function getCozyAgain(uint256 _pepeId) public view returns(uint64) {
return pepes[_pepeId].canCozyAgain;
}
/**
* ERC721 Compatibility
*
*/
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev Get the total number of Pepes
* @return total Returns the total number of pepes
*/
function totalSupply() public view returns(uint256 total) {
total = pepes.length - balances[address(0)];
return total;
}
/**
* @dev Get the number of pepes owned by an address
* @param _owner Address to get the balance from
* @return balance The number of pepes
*/
function balanceOf(address _owner) external view returns (uint256 balance) {
balance = balances[_owner];
}
/**
* @dev Get the owner of a Pepe
* @param _tokenId the token to get the owner of
* @return _owner the owner of the pepe
*/
function ownerOf(uint256 _tokenId) external view returns (address _owner) {
_owner = pepes[_tokenId].master;
}
/**
* @dev Get the id of an token by its index
* @param _owner The address to look up the tokens of
* @param _index Index to look at
* @return tokenId the ID of the token of the owner at the specified index
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 tokenId) {
//The index must be smaller than the balance,
// to guarantee that there is no leftover token returned.
require(_index < balances[_owner]);
return wallets[_owner][_index];
}
/**
* @dev Private method that ads a token to the wallet
* @param _owner Address of the owner
* @param _tokenId Pepe ID to add
*/
function addToWallet(address _owner, uint256 _tokenId) private {
uint256[] storage wallet = wallets[_owner];
uint256 balance = balances[_owner];
if (balance < wallet.length) {
wallet[balance] = _tokenId;
} else {
wallet.push(_tokenId);
}
//increase owner balance
//overflow is not likely to happen(need very large amount of pepes)
balances[_owner] += 1;
}
/**
* @dev Remove a token from a address's wallet
* @param _owner Address of the owner
* @param _tokenId Token to remove from the wallet
*/
function removeFromWallet(address _owner, uint256 _tokenId) private {
uint256[] storage wallet = wallets[_owner];
uint256 i = 0;
// solhint-disable-next-line no-empty-blocks
for (; wallet[i] != _tokenId; i++) {
// not the pepe we are looking for
}
if (wallet[i] == _tokenId) {
//found it!
uint256 last = balances[_owner] - 1;
if (last > 0) {
//move the last item to this spot, the last will become inaccessible
wallet[i] = wallet[last];
}
//else: no last item to move, the balance is 0, making everything inaccessible.
//only decrease balance if _tokenId was in the wallet
balances[_owner] -= 1;
}
}
/**
* @dev Internal transfer function
* @param _from Address sending the token
* @param _to Address to token is send to
* @param _tokenId ID of the token to send
*/
function _transfer(address _from, address _to, uint256 _tokenId) internal {
pepes[_tokenId].master = _to;
approved[_tokenId] = address(0);//reset approved of pepe on every transfer
//remove the token from the _from wallet
removeFromWallet(_from, _tokenId);
//add the token to the _to wallet
addToWallet(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev transfer a token. Can only be called by the owner of the token
* @param _to Addres to send the token to
* @param _tokenId ID of the token to send
*/
// solhint-disable-next-line no-simple-event-func-name
function transfer(address _to, uint256 _tokenId) public stopWhenHalted
onlyPepeMaster(_tokenId) //check if msg.sender is the master of this pepe
returns(bool)
{
_transfer(msg.sender, _to, _tokenId);//after master modifier invoke internal transfer
return true;
}
/**
* @dev Approve a address to send a token
* @param _to Address to approve
* @param _tokenId Token to set approval for
*/
function approve(address _to, uint256 _tokenId) external stopWhenHalted
onlyPepeMaster(_tokenId)
{
approved[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
/**
* @dev Approve or revoke approval an address for al tokens of a user
* @param _operator Address to (un)approve
* @param _approved Approving or revoking indicator
*/
function setApprovalForAll(address _operator, bool _approved) external stopWhenHalted {
if (_approved) {
approvedForAll[msg.sender][_operator] = true;
} else {
approvedForAll[msg.sender][_operator] = false;
}
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Get approved address for a token
* @param _tokenId Token ID to get the approved address for
* @return The address that is approved for this token
*/
function getApproved(uint256 _tokenId) external view returns (address) {
return approved[_tokenId];
}
/**
* @dev Get if an operator is approved for all tokens of that owner
* @param _owner Owner to check the approval for
* @param _operator Operator to check approval for
* @return Boolean indicating if the operator is approved for that owner
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return approvedForAll[_owner][_operator];
}
/**
* @dev Function to signal support for an interface
* @param interfaceID the ID of the interface to check for
* @return Boolean indicating support
*/
function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
if (interfaceID == 0x80ac58cd || interfaceID == 0x01ffc9a7) { //TODO: add more interfaces the contract supports
return true;
}
return false;
}
/**
* @dev Safe transferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
*/
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external stopWhenHalted {
_safeTransferFromInternal(_from, _to, _tokenId, "");
}
/**
* @dev Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external stopWhenHalted {
_safeTransferFromInternal(_from, _to, _tokenId, _data);
}
/**
* @dev Internal Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function _safeTransferFromInternal(address _from, address _to, uint256 _tokenId, bytes _data) internal onlyAllowed(_tokenId) {
require(pepes[_tokenId].master == _from);//check if from is current owner
require(_to != address(0));//throw on zero address
_transfer(_from, _to, _tokenId); //transfer token
if (isContract(_to)) { //check if is contract
// solhint-disable-next-line max-line-length
require(ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
/**
* @dev TransferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param _tokenId ID of the token to send
* @return If it was successful
*/
// solhint-disable-next-line max-line-length
function transferFrom(address _from, address _to, uint256 _tokenId) public stopWhenHalted onlyAllowed(_tokenId) returns(bool) {
require(pepes[_tokenId].master == _from);//check if _from is really the master.
require(_to != address(0));
_transfer(_from, _to, _tokenId);//handles event, balances and approval reset;
return true;
}
/**
* @dev Utility method to check if an address is a contract
* @param _address Address to check
* @return Boolean indicating if the address is a contract
*/
function isContract(address _address) internal view returns (bool) {
uint size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_address) }
return size > 0;
}
}
contract PepeReborn is Ownable, Usernames {
uint32[15] public cozyCoolDowns = [ // determined by generation / 2
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(15 minutes),
uint32(30 minutes),
uint32(45 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
struct Pepe {
address master; // The master of the pepe
uint256[2] genotype; // all genes stored here
uint64 canCozyAgain; // time when pepe can have nice time again
uint64 generation; // what generation?
uint64 father; // father of this pepe
uint64 mother; // mommy of this pepe
uint8 coolDownIndex;
}
struct UndeadPepeMutable {
address master; // The master of the pepe
// uint256[2] genotype; // all genes stored here
uint64 canCozyAgain; // time when pepe can have nice time again
// uint64 generation; // what generation?
// uint64 father; // father of this pepe
// uint64 mother; // mommy of this pepe
uint8 coolDownIndex;
bool resurrected; // has the pepe been duplicated off the old contract
}
mapping(uint256 => bytes32) public pepeNames;
// stores reborn pepes. index 0 holds pepe 5497
Pepe[] private rebornPepes;
// stores undead pepes. get the mutables from the old contract
mapping(uint256 => UndeadPepeMutable) private undeadPepes;
//address private constant PEPE_UNDEAD_ADDRRESS = 0x84aC94F17622241f313511B629e5E98f489AD6E4;
//address private constant PEPE_AUCTION_SALE_UNDEAD_ADDRESS = 0x28ae3DF366726D248c57b19fa36F6D9c228248BE;
//address private constant COZY_TIME_AUCTION_UNDEAD_ADDRESS = 0xE2C43d2C6D6875c8F24855054d77B5664c7e810f;
address private PEPE_UNDEAD_ADDRRESS;
address private PEPE_AUCTION_SALE_UNDEAD_ADDRESS;
address private COZY_TIME_AUCTION_UNDEAD_ADDRESS;
GenePoolInterface private genePool;
uint256 private constant REBORN_PEPE_0 = 5497;
bool public constant implementsERC721 = true; // signal erc721 support
// solhint-disable-next-line const-name-snakecase
string public constant name = "Crypto Pepe Reborn";
// solhint-disable-next-line const-name-snakecase
string public constant symbol = "CPRE";
// Token Base URI
string public baseTokenURI = "https://api.cryptopepes.lol/getPepe/";
// Contract URI
string private contractUri = "https://cryptopepes.lol/contract-metadata.json";
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private wallets;
// Mapping from token ID to index in owners wallet
mapping(uint256 => uint256) private walletIndex;
mapping(uint256 => address) public approved; // pepe index to address approved to transfer
mapping(address => mapping(address => bool)) public approvedForAll;
uint256 private preminedPepes = 0;
uint256 private constant MAX_PREMINE = 1100;
modifier onlyPepeMaster(uint256 pepeId) {
require(_ownerOf(pepeId) == msg.sender);
_;
}
modifier onlyAllowed(uint256 pepeId) {
address master = _ownerOf(pepeId);
// solhint-disable-next-line max-line-length
require(msg.sender == master || msg.sender == approved[pepeId] || approvedForAll[master][msg.sender]); // check if msg.sender is allowed
_;
}
event PepeBorn(uint256 indexed mother, uint256 indexed father, uint256 indexed pepeId);
event PepeNamed(uint256 indexed pepeId);
constructor(address baseAddress, address saleAddress, address cozyAddress, address genePoolAddress) public {
PEPE_UNDEAD_ADDRRESS = baseAddress;
PEPE_AUCTION_SALE_UNDEAD_ADDRESS = saleAddress;
COZY_TIME_AUCTION_UNDEAD_ADDRESS = cozyAddress;
setGenePool(genePoolAddress);
}
/**
* @dev Internal function that creates a new pepe
* @param _genoType DNA of the new pepe
* @param _mother The ID of the mother
* @param _father The ID of the father
* @param _generation The generation of the new Pepe
* @param _master The owner of this new Pepe
* @return The ID of the newly generated Pepe
*/
// solhint-disable-next-line max-line-length
function _newPepe(uint256[2] _genoType, uint64 _mother, uint64 _father, uint64 _generation, address _master) internal returns (uint256 pepeId) {
uint8 tempCoolDownIndex;
tempCoolDownIndex = uint8(_generation / 2);
if (_generation > 28) {
tempCoolDownIndex = 14;
}
Pepe memory _pepe = Pepe({
master: _master, // The master of the pepe
genotype: _genoType, // all genes stored here
canCozyAgain: 0, // time when pepe can have nice time again
father: _father, // father of this pepe
mother: _mother, // mommy of this pepe
generation: _generation, // what generation?
coolDownIndex: tempCoolDownIndex
});
// push returns the new length, use it to get a new unique id
pepeId = rebornPepes.push(_pepe) + REBORN_PEPE_0 - 1;
// add it to the wallet of the master of the new pepe
addToWallet(_master, pepeId);
emit PepeBorn(_mother, _father, pepeId);
emit Transfer(address(0), _master, pepeId);
return pepeId;
}
/**
* @dev Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE
* @param _amount Amount of Pepes to premine
*/
function pepePremine(uint256 _amount) public onlyOwner {
for (uint i = 0; i < _amount; i++) {
require(preminedPepes < MAX_PREMINE);//can only generate set amount during premine
//create a new pepe
// 1) who's genes are based on hash of the timestamp and the new pepe's id
// 2) who has no mother or father
// 3) who is generation zero
// 4) who's master is the manager
// solhint-disable-next-line
_newPepe(genePool.randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, (REBORN_PEPE_0 + rebornPepes.length))))), 0, 0, 0, owner);
++preminedPepes;
}
}
/*
* @dev CozyTime two Pepes together
* @param _mother The mother of the new Pepe
* @param _father The father of the new Pepe
* @param _pepeReceiver Address receiving the new Pepe
* @return If it was a success
*/
function cozyTime(uint256 _mother, uint256 _father, address _pepeReceiver) external returns (bool) {
// cannot cozyTime with itself
require(_mother != _father);
// ressurect parents if needed
checkResurrected(_mother);
checkResurrected(_father);
// get parents
Pepe memory mother = _getPepe(_mother);
Pepe memory father = _getPepe(_father);
// caller has to either be master or approved for mother
// solhint-disable-next-line max-line-length
require(mother.master == msg.sender || approved[_mother] == msg.sender || approvedForAll[mother.master][msg.sender]);
// caller has to either be master or approved for father
// solhint-disable-next-line max-line-length
require(father.master == msg.sender || approved[_father] == msg.sender || approvedForAll[father.master][msg.sender]);
// require both parents to be ready for cozytime
// solhint-disable-next-line not-rely-on-time
require(now > mother.canCozyAgain && now > father.canCozyAgain);
// require both mother parents not to be father
require(mother.father != _father && mother.mother != _father);
require(father.mother != _mother && father.father != _mother);
approved[_father] = address(0);
approved[_mother] = address(0);
uint256[2] memory newGenotype = genePool.breed(father.genotype, mother.genotype, REBORN_PEPE_0+rebornPepes.length);
uint64 newGeneration;
newGeneration = mother.generation + 1;
if (newGeneration < father.generation + 1) { // if father generation is bigger
newGeneration = father.generation + 1;
}
uint64 motherCanCozyAgain = _handleCoolDown(_mother);
_handleCoolDown(_father);
// birth new pepe
// _pepeReceiver becomes the master of the pepe
uint256 pepeId = _newPepe(newGenotype, uint64(_mother), uint64(_father), newGeneration, _pepeReceiver);
// sets pepe birth when mother is done
// solhint-disable-next-line max-line-length
rebornPepes[rebornPepeIdToIndex(pepeId)].canCozyAgain = motherCanCozyAgain;
return true;
}
/**
* @dev Internal function to increase the coolDownIndex
* @param pepeId The id of the Pepe to update the coolDown of
* @return The time that pepe can cozy again
*/
function _handleCoolDown(uint256 pepeId) internal returns (uint64){
if(pepeId >= REBORN_PEPE_0){
Pepe storage tempPep1 = rebornPepes[pepeId];
// solhint-disable-next-line not-rely-on-time
tempPep1.canCozyAgain = uint64(now + cozyCoolDowns[tempPep1.coolDownIndex]);
if (tempPep1.coolDownIndex < 14) {// after every cozy time pepe gets slower
tempPep1.coolDownIndex++;
}
return tempPep1.canCozyAgain;
}else{
// this function is only called in cozyTime(), pepe has already been resurrected
UndeadPepeMutable storage tempPep2 = undeadPepes[pepeId];
// solhint-disable-next-line not-rely-on-time
tempPep2.canCozyAgain = uint64(now + cozyCoolDowns[tempPep2.coolDownIndex]);
if (tempPep2.coolDownIndex < 14) {// after every cozy time pepe gets slower
tempPep2.coolDownIndex++;
}
return tempPep2.canCozyAgain;
}
}
/**
* @dev Set the name of a Pepe. Can only be set once
* @param pepeId ID of the pepe to name
* @param _name The name to assign
*/
function setPepeName(uint256 pepeId, bytes32 _name) public onlyPepeMaster(pepeId) returns(bool) {
require(pepeNames[pepeId] == 0x0000000000000000000000000000000000000000000000000000000000000000);
pepeNames[pepeId] = _name;
emit PepeNamed(pepeId);
return true;
}
/**
* @dev Transfer a Pepe to the auction contract and auction it
* @param pepeId ID of the Pepe to auction
* @param _auction Auction contract address
* @param _beginPrice Price the auction starts at
* @param _endPrice Price the auction ends at
* @param _duration How long the auction should run
*/
// solhint-disable-next-line max-line-length
function transferAndAuction(uint256 pepeId, address _auction, uint256 _beginPrice, uint256 _endPrice, uint64 _duration) public onlyPepeMaster(pepeId) {
//checkResurrected(pepeId);
_transfer(msg.sender, _auction, pepeId);// transfer pepe to auction
AuctionBase auction = AuctionBase(_auction);
auction.startAuctionDirect(pepeId, _beginPrice, _endPrice, _duration, msg.sender);
}
/**
* @dev Approve and buy. Used to buy cozyTime in one call
* @param pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
*/
// solhint-disable-next-line max-line-length
function approveAndBuy(uint256 pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather) public payable onlyPepeMaster(_cozyCandidate) {
checkResurrected(pepeId);
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
RebornCozyTimeAuction(_auction).buyCozy.value(msg.value)(pepeId, _cozyCandidate, _candidateAsFather, msg.sender); // breeding resets approval
}
/**
* @dev The same as above only pass an extra parameter
* @param pepeId Pepe to cozy with
* @param _auction Address of the auction contract
* @param _cozyCandidate Pepe to approve and cozy with
* @param _candidateAsFather Use the candidate as father or not
* @param _affiliate Address to set as affiliate
*/
// solhint-disable-next-line max-line-length
function approveAndBuyAffiliated(uint256 pepeId, address _auction, uint256 _cozyCandidate, bool _candidateAsFather, address _affiliate) public payable onlyPepeMaster(_cozyCandidate) {
checkResurrected(pepeId);
approved[_cozyCandidate] = _auction;
// solhint-disable-next-line max-line-length
RebornCozyTimeAuction(_auction).buyCozyAffiliated.value(msg.value)(pepeId, _cozyCandidate, _candidateAsFather, msg.sender, _affiliate); // breeding resets approval
}
/**
* @dev Get the time when a pepe can cozy again
* @param pepeId ID of the pepe
* @return Time when the pepe can cozy again
*/
function getCozyAgain(uint256 pepeId) public view returns(uint64) {
return _getPepe(pepeId).canCozyAgain;
}
/**
* ERC721 Compatibility
*
*/
event Approval(address indexed _owner, address indexed _approved, uint256 pepeId);
event Transfer(address indexed _from, address indexed _to, uint256 indexed pepeId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/**
* @dev Get the total number of Pepes
* @return total Returns the total number of pepes
*/
function totalSupply() public view returns(uint256) {
return REBORN_PEPE_0 + rebornPepes.length - 1;
}
/**
* @dev Get the number of pepes owned by an address
* Note that this only includes reborn and resurrected pepes
* Pepes that are still dead are not counted.
* @param _owner Address to get the balance from
* @return balance The number of pepes
*/
function balanceOf(address _owner) external view returns (uint256 balance) {
return wallets[_owner].length;
}
/**
* @dev Get the owner of a Pepe
* Note that this returns pepes from old auctions
* @param pepeId the token to get the owner of
* @return the owner of the pepe
*/
function ownerOf(uint256 pepeId) external view returns (address) {
return _getPepe(pepeId).master;
}
/**
* @dev Get the owner of a Pepe
* Note that this returns pepes from old auctions
* @param pepeId the token to get the owner of
* @return the owner of the pepe
*/
function _ownerOf(uint256 pepeId) internal view returns (address) {
return _getPepe(pepeId).master;
}
/**
* @dev Get the id of an token by its index
* @param _owner The address to look up the tokens of
* @param _index Index to look at
* @return pepeId the ID of the token of the owner at the specified index
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint256 pepeId) {
// The index must be smaller than the balance,
// to guarantee that there is no leftover token returned.
require(_index < wallets[_owner].length);
return wallets[_owner][_index];
}
/**
* @dev Private method that ads a token to the wallet
* @param _owner Address of the owner
* @param pepeId Pepe ID to add
*/
function addToWallet(address _owner, uint256 pepeId) private {
/*
uint256 length = wallets[_owner].length;
wallets[_owner].push(pepeId);
walletIndex[pepeId] = length;
*/
walletIndex[pepeId] = wallets[_owner].length;
wallets[_owner].push(pepeId);
}
/**
* @dev Remove a token from a address's wallet
* @param _owner Address of the owner
* @param pepeId Token to remove from the wallet
*/
function removeFromWallet(address _owner, uint256 pepeId) private {
// walletIndex returns 0 if not initialized to a value
// verify before removing
if(walletIndex[pepeId] == 0 && (wallets[_owner].length == 0 || wallets[_owner][0] != pepeId)) return;
// pop last element from wallet, move it to this index
uint256 tokenIndex = walletIndex[pepeId];
uint256 lastTokenIndex = wallets[_owner].length - 1;
uint256 lastToken = wallets[_owner][lastTokenIndex];
wallets[_owner][tokenIndex] = lastToken;
wallets[_owner].length--;
walletIndex[pepeId] = 0;
walletIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal transfer function
* @param _from Address sending the token
* @param _to Address to token is send to
* @param pepeId ID of the token to send
*/
function _transfer(address _from, address _to, uint256 pepeId) internal {
checkResurrected(pepeId);
if(pepeId >= REBORN_PEPE_0) rebornPepes[rebornPepeIdToIndex(pepeId)].master = _to;
else undeadPepes[pepeId].master = _to;
approved[pepeId] = address(0);//reset approved of pepe on every transfer
//remove the token from the _from wallet
removeFromWallet(_from, pepeId);
//add the token to the _to wallet
addToWallet(_to, pepeId);
emit Transfer(_from, _to, pepeId);
}
/**
* @dev transfer a token. Can only be called by the owner of the token
* @param _to Addres to send the token to
* @param pepeId ID of the token to send
*/
// solhint-disable-next-line no-simple-event-func-name
function transfer(address _to, uint256 pepeId) public onlyPepeMaster(pepeId) returns(bool) {
_transfer(msg.sender, _to, pepeId);//after master modifier invoke internal transfer
return true;
}
/**
* @dev Approve a address to send a token
* @param _to Address to approve
* @param pepeId Token to set approval for
*/
function approve(address _to, uint256 pepeId) external onlyPepeMaster(pepeId) {
approved[pepeId] = _to;
emit Approval(msg.sender, _to, pepeId);
}
/**
* @dev Approve or revoke approval an address for all tokens of a user
* @param _operator Address to (un)approve
* @param _approved Approving or revoking indicator
*/
function setApprovalForAll(address _operator, bool _approved) external {
approvedForAll[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Get approved address for a token
* @param pepeId Token ID to get the approved address for
* @return The address that is approved for this token
*/
function getApproved(uint256 pepeId) external view returns (address) {
return approved[pepeId];
}
/**
* @dev Get if an operator is approved for all tokens of that owner
* @param _owner Owner to check the approval for
* @param _operator Operator to check approval for
* @return Boolean indicating if the operator is approved for that owner
*/
function isApprovedForAll(address _owner, address _operator) external view returns (bool) {
return approvedForAll[_owner][_operator];
}
/**
* @dev Function to signal support for an interface
* @param interfaceID the ID of the interface to check for
* @return Boolean indicating support
*/
function supportsInterface(bytes4 interfaceID) external pure returns (bool) {
if(
interfaceID == 0x01ffc9a7 // ERC 165
|| interfaceID == 0x80ac58cd // ERC 721 base
|| interfaceID == 0x780e9d63 // ERC 721 enumerable
|| interfaceID == 0x4f558e79 // ERC 721 exists
|| interfaceID == 0x5b5e139f // ERC 721 metadata
// TODO: add more interfaces such as
// 0x150b7a02: ERC 721 receiver
) {
return true;
}
return false;
}
/**
* @dev Safe transferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param pepeId ID of the token to send
*/
function safeTransferFrom(address _from, address _to, uint256 pepeId) external {
_safeTransferFromInternal(_from, _to, pepeId, "");
}
/**
* @dev Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param pepeId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function safeTransferFrom(address _from, address _to, uint256 pepeId, bytes _data) external {
_safeTransferFromInternal(_from, _to, pepeId, _data);
}
/**
* @dev Internal Safe transferFrom function with aditional data attribute
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param pepeId ID of the token to send
* @param _data Data to pass along call
*/
// solhint-disable-next-line max-line-length
function _safeTransferFromInternal(address _from, address _to, uint256 pepeId, bytes _data) internal onlyAllowed(pepeId) {
require(_ownerOf(pepeId) == _from);//check if from is current owner
require(_to != address(0));//throw on zero address
_transfer(_from, _to, pepeId); //transfer token
if (isContract(_to)) { //check if is contract
// solhint-disable-next-line max-line-length
require(ERC721TokenReceiver(_to).onERC721Received(_from, pepeId, _data) == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
/**
* @dev TransferFrom function
* @param _from Address currently owning the token
* @param _to Address to send token to
* @param pepeId ID of the token to send
* @return If it was successful
*/
// solhint-disable-next-line max-line-length
function transferFrom(address _from, address _to, uint256 pepeId) public onlyAllowed(pepeId) returns(bool) {
require(_ownerOf(pepeId) == _from);//check if _from is really the master.
require(_to != address(0));
_transfer(_from, _to, pepeId);//handles event, balances and approval reset;
return true;
}
/**
* @dev Utility method to check if an address is a contract
* @param _address Address to check
* @return Boolean indicating if the address is a contract
*/
function isContract(address _address) internal view returns (bool) {
uint size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_address) }
return size > 0;
}
/**
* @dev Returns whether the specified token exists
* @param pepeId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 pepeId) public view returns (bool) {
return 0 < pepeId && pepeId <= (REBORN_PEPE_0 + rebornPepes.length - 1);//this.totalSupply();
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param pepeId uint256 ID of the token to query
*/
function tokenURI(uint256 pepeId) public view returns (string) {
require(exists(pepeId));
return string(abi.encodePacked(baseTokenURI, toString(pepeId)));
}
/**
* @dev Changes the base URI for metadata.
* @param baseURI the new base URI
*/
function setBaseTokenURI(string baseURI) public onlyOwner {
baseTokenURI = baseURI;
}
/**
* @dev Returns the URI for the contract
* @return the uri
*/
function contractURI() public view returns (string) {
return contractUri;
}
/**
* @dev Changes the URI for the contract
* @param uri the new uri
*/
function setContractURI(string uri) public onlyOwner {
contractUri = uri;
}
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
* @param value a number to convert to string
* @return a string representation of the number
*/
function toString(uint256 value) internal pure returns (string memory) {
// Borrowed from Open Zeppelin, which was
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
/**
* @dev get Pepe information
* Returns information as separate variables
* @param pepeId ID of the Pepe to get information of
* @return master
* @return genotype
* @return canCozyAgain
* @return generation
* @return father
* @return mother
* @return pepeName
* @return coolDownIndex
*/
// solhint-disable-next-line max-line-length
function getPepe(uint256 pepeId) public view returns (address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) {
Pepe memory pepe = _getPepe(pepeId);
master = pepe.master;
genotype = pepe.genotype;
canCozyAgain = pepe.canCozyAgain;
generation = pepe.generation;
father = pepe.father;
mother = pepe.mother;
pepeName = pepeNames[pepeId];
coolDownIndex = pepe.coolDownIndex;
}
/**
* @dev get Pepe information
* Returns information as a single Pepe struct
* @param pepeId ID of the Pepe to get information of
* @return pepe info
*/
function _getPepe(uint256 pepeId) internal view returns (Pepe memory) {
if(pepeId >= REBORN_PEPE_0) {
uint256 index = rebornPepeIdToIndex(pepeId);
require(index < rebornPepes.length);
return rebornPepes[index];
}else{
(address master, uint256[2] memory genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, , uint8 coolDownIndex) = _getUndeadPepe(pepeId);
return Pepe({
master: master, // The master of the pepe
genotype: genotype, // all genes stored here
canCozyAgain: canCozyAgain, // time when pepe can have nice time again
father: uint64(father), // father of this pepe
mother: uint64(mother), // mommy of this pepe
generation: generation, // what generation?
coolDownIndex: coolDownIndex
});
}
}
/**
* @dev get undead pepe information
* @param pepeId ID of the Pepe to get information of
* @return master
* @return genotype
* @return canCozyAgain
* @return generation
* @return father
* @return mother
* @return pepeName
* @return coolDownIndex
*/
function _getUndeadPepe(uint256 pepeId) internal view returns (address master, uint256[2] genotype, uint64 canCozyAgain, uint64 generation, uint256 father, uint256 mother, bytes32 pepeName, uint8 coolDownIndex) {
// if undead, pull from old contract
(master, genotype, canCozyAgain, generation, father, mother, pepeName, coolDownIndex) = PepeBase(PEPE_UNDEAD_ADDRRESS).getPepe(pepeId);
if(undeadPepes[pepeId].resurrected){
// if resurrected, pull from undead map
master = undeadPepes[pepeId].master;
canCozyAgain = undeadPepes[pepeId].canCozyAgain;
pepeName = pepeNames[pepeId];
coolDownIndex = undeadPepes[pepeId].coolDownIndex;
}else if(master == PEPE_AUCTION_SALE_UNDEAD_ADDRESS || master == COZY_TIME_AUCTION_UNDEAD_ADDRESS){
// if on auction, return to seller
(master, , , , , ) = AuctionBase(master).auctions(pepeId);
}
}
// Useful for tracking resurrections
event PepeResurrected(uint256 pepeId);
/**
* @dev Checks if the pepe needs to be resurrected from the old contract and if so does.
* @param pepeId ID of the Pepe to check
*/
// solhint-disable-next-line max-line-length
function checkResurrected(uint256 pepeId) public {
if(pepeId >= REBORN_PEPE_0) return;
if(undeadPepes[pepeId].resurrected) return;
(address _master, , uint64 _canCozyAgain, , , , bytes32 _pepeName, uint8 _coolDownIndex) = _getUndeadPepe(pepeId);
undeadPepes[pepeId] = UndeadPepeMutable({
master: _master, // The master of the pepe
canCozyAgain: _canCozyAgain, // time when pepe can have nice time again
coolDownIndex: _coolDownIndex,
resurrected: true
});
if(_pepeName != 0x0000000000000000000000000000000000000000000000000000000000000000) pepeNames[pepeId] = _pepeName;
addToWallet(_master, pepeId);
emit PepeResurrected(pepeId);
}
/**
* @dev Calculates reborn pepe array index
* @param pepeId ID of the pepe to check
* @return array index
*/
function rebornPepeIdToIndex(uint256 pepeId) internal pure returns (uint256) {
require(pepeId >= REBORN_PEPE_0);
return pepeId - REBORN_PEPE_0;
}
/**
* @dev Changes the address of the previous contracts
* This is only a precaution in case I mess up deployment
* @param baseaddr the correct PepeBase address
* @param saleauctionaddr the correct PepeSaleAuction address
* @param cozyauctionaddr the correct CozyTimeAuction address
*/
function setPrevContracts(address baseaddr, address saleauctionaddr, address cozyauctionaddr) public onlyOwner {
PEPE_UNDEAD_ADDRRESS = baseaddr;
PEPE_AUCTION_SALE_UNDEAD_ADDRESS = saleauctionaddr;
COZY_TIME_AUCTION_UNDEAD_ADDRESS = cozyauctionaddr;
}
/**
* @dev Changes the gene pool contract address
* @param genePoolAddress the new pool address
*/
function setGenePool(address genePoolAddress) public onlyOwner {
GenePoolInterface pool = GenePoolInterface(genePoolAddress);
require(pool.isGenePool());
genePool = pool;
}
}
contract GenesisActTwo {
PepeReborn public cpepToken;
address public owner;
uint256 public price = 100000000000000000; // 0.1 eth
uint256 public mined;
modifier onlyOwner() {
require(owner == msg.sender, "not owner");
_;
}
constructor(address _cpepToken, address _owner) {
cpepToken = PepeReborn(_cpepToken);
owner = _owner;
}
function birth(uint256 amount) external payable {
require(msg.value >= amount * price, "insufficient payment");
uint256 startSupply = cpepToken.totalSupply();
cpepToken.pepePremine(amount);
for(uint256 pepeId = startSupply+1; pepeId <= startSupply + amount; ++pepeId) {
cpepToken.transfer(msg.sender, pepeId);
}
mined += amount;
}
function setPrice(uint256 _price) external onlyOwner {
price = _price;
}
function sweep(address recipient, uint256 amount) external onlyOwner {
recipient.transfer(amount);
}
function transferOwnership(address newOwner) external onlyOwner {
cpepToken.transferOwnership(newOwner);
}
}
|
Premine pepes. Can only be called by the owner and is limited to MAX_PREMINE _amount Amount of Pepes to premine/create a new pepe 1) who's genes are based on hash of the timestamp and the new pepe's id 2) who has no mother or father 3) who is generation zero 4) who's master is the manager solhint-disable-next-line
|
function pepePremine(uint256 _amount) public onlyOwner {
for (uint i = 0; i < _amount; i++) {
_newPepe(genePool.randomDNA(uint256(keccak256(abi.encodePacked(block.timestamp, (REBORN_PEPE_0 + rebornPepes.length))))), 0, 0, 0, owner);
++preminedPepes;
}
}
| 10,871,762 |
pragma solidity >=0.4.25 <0.6.0;
pragma experimental ABIEncoderV2;
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Modifiable
* @notice A contract with basic modifiers
*/
contract Modifiable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier notNullAddress(address _address) {
require(_address != address(0));
_;
}
modifier notThisAddress(address _address) {
require(_address != address(this));
_;
}
modifier notNullOrThisAddress(address _address) {
require(_address != address(0));
require(_address != address(this));
_;
}
modifier notSameAddresses(address _address1, address _address2) {
if (_address1 != _address2)
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SelfDestructible
* @notice Contract that allows for self-destruction
*/
contract SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public selfDestructionDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SelfDestructionDisabledEvent(address wallet);
event TriggerSelfDestructionEvent(address wallet);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the address of the destructor role
function destructor()
public
view
returns (address);
/// @notice Disable self-destruction of this contract
/// @dev This operation can not be undone
function disableSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Disable self-destruction
selfDestructionDisabled = true;
// Emit event
emit SelfDestructionDisabledEvent(msg.sender);
}
/// @notice Destroy this contract
function triggerSelfDestruction()
public
{
// Require that sender is the assigned destructor
require(destructor() == msg.sender);
// Require that self-destruction has not been disabled
require(!selfDestructionDisabled);
// Emit event
emit TriggerSelfDestructionEvent(msg.sender);
// Self-destruct and reward destructor
selfdestruct(msg.sender);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Ownable
* @notice A modifiable that has ownership roles
*/
contract Ownable is Modifiable, SelfDestructible {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address public deployer;
address public operator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetDeployerEvent(address oldDeployer, address newDeployer);
event SetOperatorEvent(address oldOperator, address newOperator);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address _deployer) internal notNullOrThisAddress(_deployer) {
deployer = _deployer;
operator = _deployer;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Return the address that is able to initiate self-destruction
function destructor()
public
view
returns (address)
{
return deployer;
}
/// @notice Set the deployer of this contract
/// @param newDeployer The address of the new deployer
function setDeployer(address newDeployer)
public
onlyDeployer
notNullOrThisAddress(newDeployer)
{
if (newDeployer != deployer) {
// Set new deployer
address oldDeployer = deployer;
deployer = newDeployer;
// Emit event
emit SetDeployerEvent(oldDeployer, newDeployer);
}
}
/// @notice Set the operator of this contract
/// @param newOperator The address of the new operator
function setOperator(address newOperator)
public
onlyOperator
notNullOrThisAddress(newOperator)
{
if (newOperator != operator) {
// Set new operator
address oldOperator = operator;
operator = newOperator;
// Emit event
emit SetOperatorEvent(oldOperator, newOperator);
}
}
/// @notice Gauge whether message sender is deployer or not
/// @return true if msg.sender is deployer, else false
function isDeployer()
internal
view
returns (bool)
{
return msg.sender == deployer;
}
/// @notice Gauge whether message sender is operator or not
/// @return true if msg.sender is operator, else false
function isOperator()
internal
view
returns (bool)
{
return msg.sender == operator;
}
/// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on
/// on the other hand
/// @return true if msg.sender is operator, else false
function isDeployerOrOperator()
internal
view
returns (bool)
{
return isDeployer() || isOperator();
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDeployer() {
require(isDeployer());
_;
}
modifier notDeployer() {
require(!isDeployer());
_;
}
modifier onlyOperator() {
require(isOperator());
_;
}
modifier notOperator() {
require(!isOperator());
_;
}
modifier onlyDeployerOrOperator() {
require(isDeployerOrOperator());
_;
}
modifier notDeployerOrOperator() {
require(!isDeployerOrOperator());
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Servable
* @notice An ownable that contains registered services and their actions
*/
contract Servable is Ownable {
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct ServiceInfo {
bool registered;
uint256 activationTimestamp;
mapping(bytes32 => bool) actionsEnabledMap;
bytes32[] actionsList;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => ServiceInfo) internal registeredServicesMap;
uint256 public serviceActivationTimeout;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds);
event RegisterServiceEvent(address service);
event RegisterServiceDeferredEvent(address service, uint256 timeout);
event DeregisterServiceEvent(address service);
event EnableServiceActionEvent(address service, string action);
event DisableServiceActionEvent(address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the service activation timeout
/// @param timeoutInSeconds The set timeout in unit of seconds
function setServiceActivationTimeout(uint256 timeoutInSeconds)
public
onlyDeployer
{
serviceActivationTimeout = timeoutInSeconds;
// Emit event
emit ServiceActivationTimeoutEvent(timeoutInSeconds);
}
/// @notice Register a service contract whose activation is immediate
/// @param service The address of the service contract to be registered
function registerService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, 0);
// Emit event
emit RegisterServiceEvent(service);
}
/// @notice Register a service contract whose activation is deferred by the service activation timeout
/// @param service The address of the service contract to be registered
function registerServiceDeferred(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
_registerService(service, serviceActivationTimeout);
// Emit event
emit RegisterServiceDeferredEvent(service, serviceActivationTimeout);
}
/// @notice Deregister a service contract
/// @param service The address of the service contract to be deregistered
function deregisterService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
registeredServicesMap[service].registered = false;
// Emit event
emit DeregisterServiceEvent(service);
}
/// @notice Enable a named action in an already registered service contract
/// @param service The address of the registered service contract
/// @param action The name of the action to be enabled
function enableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(registeredServicesMap[service].registered);
bytes32 actionHash = hashString(action);
require(!registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = true;
registeredServicesMap[service].actionsList.push(actionHash);
// Emit event
emit EnableServiceActionEvent(service, action);
}
/// @notice Enable a named action in a service contract
/// @param service The address of the service contract
/// @param action The name of the action to be disabled
function disableServiceAction(address service, string memory action)
public
onlyDeployer
notNullOrThisAddress(service)
{
bytes32 actionHash = hashString(action);
require(registeredServicesMap[service].actionsEnabledMap[actionHash]);
registeredServicesMap[service].actionsEnabledMap[actionHash] = false;
// Emit event
emit DisableServiceActionEvent(service, action);
}
/// @notice Gauge whether a service contract is registered
/// @param service The address of the service contract
/// @return true if service is registered, else false
function isRegisteredService(address service)
public
view
returns (bool)
{
return registeredServicesMap[service].registered;
}
/// @notice Gauge whether a service contract is registered and active
/// @param service The address of the service contract
/// @return true if service is registered and activate, else false
function isRegisteredActiveService(address service)
public
view
returns (bool)
{
return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp;
}
/// @notice Gauge whether a service contract action is enabled which implies also registered and active
/// @param service The address of the service contract
/// @param action The name of action
function isEnabledServiceAction(address service, string memory action)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash];
}
//
// Internal functions
// -----------------------------------------------------------------------------------------------------------------
function hashString(string memory _string)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _registerService(address service, uint256 timeout)
private
{
if (!registeredServicesMap[service].registered) {
registeredServicesMap[service].registered = true;
registeredServicesMap[service].activationTimestamp = block.timestamp + timeout;
}
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyActiveService() {
require(isRegisteredActiveService(msg.sender));
_;
}
modifier onlyEnabledServiceAction(string memory action) {
require(isEnabledServiceAction(msg.sender, action));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathIntLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathIntLib {
int256 constant INT256_MIN = int256((uint256(1) << 255));
int256 constant INT256_MAX = int256(~((uint256(1) << 255)));
//
//Functions below accept positive and negative integers and result must not overflow.
//
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != INT256_MIN || b != - 1);
return a / b;
}
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a != - 1 || b != INT256_MIN);
// overflow
require(b != - 1 || a != INT256_MIN);
// overflow
int256 c = a * b;
require((b == 0) || (c / b == a));
return c;
}
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
require((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
//
//Functions below only accept positive integers and result must be greater or equal to zero too.
//
function div_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b > 0);
return a / b;
}
function mul_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a * b;
require(a == 0 || c / a == b);
require(c >= 0);
return c;
}
function sub_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0 && b <= a);
return a - b;
}
function add_nn(int256 a, int256 b)
internal
pure
returns (int256)
{
require(a >= 0 && b >= 0);
int256 c = a + b;
require(c >= a);
return c;
}
//
//Conversion and validation functions.
//
function abs(int256 a)
public
pure
returns (int256)
{
return a < 0 ? neg(a) : a;
}
function neg(int256 a)
public
pure
returns (int256)
{
return mul(a, - 1);
}
function toNonZeroInt256(uint256 a)
public
pure
returns (int256)
{
require(a > 0 && a < (uint256(1) << 255));
return int256(a);
}
function toInt256(uint256 a)
public
pure
returns (int256)
{
require(a >= 0 && a < (uint256(1) << 255));
return int256(a);
}
function toUInt256(int256 a)
public
pure
returns (uint256)
{
require(a >= 0);
return uint256(a);
}
function isNonZeroPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a > 0);
}
function isPositiveInt256(int256 a)
public
pure
returns (bool)
{
return (a >= 0);
}
function isNonZeroNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a < 0);
}
function isNegativeInt256(int256 a)
public
pure
returns (bool)
{
return (a <= 0);
}
//
//Clamping functions.
//
function clamp(int256 a, int256 min, int256 max)
public
pure
returns (int256)
{
if (a < min)
return min;
return (a > max) ? max : a;
}
function clampMin(int256 a, int256 min)
public
pure
returns (int256)
{
return (a < min) ? min : a;
}
function clampMax(int256 a, int256 max)
public
pure
returns (int256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbUintsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
uint256 value;
}
struct BlockNumbUints {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbUints storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (uint256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbUints storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbUints storage self, uint256 blockNumber, uint256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbUintsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbUints storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbUints storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbUints storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbUintsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbIntsLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
int256 value;
}
struct BlockNumbInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbInts storage self)
internal
view
returns (int256)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbInts storage self, uint256 blockNumber, int256 value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbIntsLib.sol:62]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbIntsLib.sol:92]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library ConstantsLib {
// Get the fraction that represents the entirety, equivalent of 100%
function PARTS_PER()
public
pure
returns (int256)
{
return 1e18;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbDisdIntsLib {
using SafeMathIntLib for int256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Discount {
int256 tier;
int256 value;
}
struct Entry {
uint256 blockNumber;
int256 nominal;
Discount[] discounts;
}
struct BlockNumbDisdInts {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentNominalValue(BlockNumbDisdInts storage self)
internal
view
returns (int256)
{
return nominalValueAt(self, block.number);
}
function currentDiscountedValue(BlockNumbDisdInts storage self, int256 tier)
internal
view
returns (int256)
{
return discountedValueAt(self, block.number, tier);
}
function currentEntry(BlockNumbDisdInts storage self)
internal
view
returns (Entry memory)
{
return entryAt(self, block.number);
}
function nominalValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (int256)
{
return entryAt(self, _blockNumber).nominal;
}
function discountedValueAt(BlockNumbDisdInts storage self, uint256 _blockNumber, int256 tier)
internal
view
returns (int256)
{
Entry memory entry = entryAt(self, _blockNumber);
if (0 < entry.discounts.length) {
uint256 index = indexByTier(entry.discounts, tier);
if (0 < index)
return entry.nominal.mul(
ConstantsLib.PARTS_PER().sub(entry.discounts[index - 1].value)
).div(
ConstantsLib.PARTS_PER()
);
else
return entry.nominal;
} else
return entry.nominal;
}
function entryAt(BlockNumbDisdInts storage self, uint256 _blockNumber)
internal
view
returns (Entry memory)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addNominalEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbDisdIntsLib.sol:101]"
);
self.entries.length++;
Entry storage entry = self.entries[self.entries.length - 1];
entry.blockNumber = blockNumber;
entry.nominal = nominal;
}
function addDiscountedEntry(BlockNumbDisdInts storage self, uint256 blockNumber, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
internal
{
require(discountTiers.length == discountValues.length, "Parameter array lengths mismatch [BlockNumbDisdIntsLib.sol:118]");
addNominalEntry(self, blockNumber, nominal);
Entry storage entry = self.entries[self.entries.length - 1];
for (uint256 i = 0; i < discountTiers.length; i++)
entry.discounts.push(Discount(discountTiers[i], discountValues[i]));
}
function count(BlockNumbDisdInts storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbDisdInts storage self)
internal
view
returns (Entry[] memory)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbDisdInts storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbDisdIntsLib.sol:148]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
/// @dev The index returned here is 1-based
function indexByTier(Discount[] memory discounts, int256 tier)
internal
pure
returns (uint256)
{
require(0 < discounts.length, "No discounts found [BlockNumbDisdIntsLib.sol:161]");
for (uint256 i = discounts.length; i > 0; i--)
if (tier >= discounts[i - 1].tier)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title MonetaryTypesLib
* @dev Monetary data types
*/
library MonetaryTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currency {
address ct;
uint256 id;
}
struct Figure {
int256 amount;
Currency currency;
}
struct NoncedAmount {
uint256 nonce;
int256 amount;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbReferenceCurrenciesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Currency currency;
}
struct BlockNumbReferenceCurrencies {
mapping(address => mapping(uint256 => Entry[])) entriesByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return currencyAt(self, referenceCurrency, block.number);
}
function currentEntry(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry storage)
{
return entryAt(self, referenceCurrency, block.number);
}
function currencyAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Currency storage)
{
return entryAt(self, referenceCurrency, _blockNumber).currency;
}
function entryAt(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency,
uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][indexByBlockNumber(self, referenceCurrency, _blockNumber)];
}
function addEntry(BlockNumbReferenceCurrencies storage self, uint256 blockNumber,
MonetaryTypesLib.Currency memory referenceCurrency, MonetaryTypesLib.Currency memory currency)
internal
{
require(
0 == self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length ||
blockNumber > self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1].blockNumber,
"Later entry found for currency [BlockNumbReferenceCurrenciesLib.sol:67]"
);
self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].push(Entry(blockNumber, currency));
}
function count(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (uint256)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length;
}
function entriesByCurrency(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency)
internal
view
returns (Entry[] storage)
{
return self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id];
}
function indexByBlockNumber(BlockNumbReferenceCurrencies storage self, MonetaryTypesLib.Currency memory referenceCurrency, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length, "No entries found for currency [BlockNumbReferenceCurrenciesLib.sol:97]");
for (uint256 i = self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id].length - 1; i >= 0; i--)
if (blockNumber >= self.entriesByCurrency[referenceCurrency.ct][referenceCurrency.id][i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BlockNumbFiguresLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Entry {
uint256 blockNumber;
MonetaryTypesLib.Figure value;
}
struct BlockNumbFigures {
Entry[] entries;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function currentValue(BlockNumbFigures storage self)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return valueAt(self, block.number);
}
function currentEntry(BlockNumbFigures storage self)
internal
view
returns (Entry storage)
{
return entryAt(self, block.number);
}
function valueAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (MonetaryTypesLib.Figure storage)
{
return entryAt(self, _blockNumber).value;
}
function entryAt(BlockNumbFigures storage self, uint256 _blockNumber)
internal
view
returns (Entry storage)
{
return self.entries[indexByBlockNumber(self, _blockNumber)];
}
function addEntry(BlockNumbFigures storage self, uint256 blockNumber, MonetaryTypesLib.Figure memory value)
internal
{
require(
0 == self.entries.length ||
blockNumber > self.entries[self.entries.length - 1].blockNumber,
"Later entry found [BlockNumbFiguresLib.sol:65]"
);
self.entries.push(Entry(blockNumber, value));
}
function count(BlockNumbFigures storage self)
internal
view
returns (uint256)
{
return self.entries.length;
}
function entries(BlockNumbFigures storage self)
internal
view
returns (Entry[] storage)
{
return self.entries;
}
function indexByBlockNumber(BlockNumbFigures storage self, uint256 blockNumber)
internal
view
returns (uint256)
{
require(0 < self.entries.length, "No entries found [BlockNumbFiguresLib.sol:95]");
for (uint256 i = self.entries.length - 1; i >= 0; i--)
if (blockNumber >= self.entries[i].blockNumber)
return i;
revert();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Configuration
* @notice An oracle for configurations values
*/
contract Configuration is Modifiable, Ownable, Servable {
using SafeMathIntLib for int256;
using BlockNumbUintsLib for BlockNumbUintsLib.BlockNumbUints;
using BlockNumbIntsLib for BlockNumbIntsLib.BlockNumbInts;
using BlockNumbDisdIntsLib for BlockNumbDisdIntsLib.BlockNumbDisdInts;
using BlockNumbReferenceCurrenciesLib for BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies;
using BlockNumbFiguresLib for BlockNumbFiguresLib.BlockNumbFigures;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public OPERATIONAL_MODE_ACTION = "operational_mode";
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum OperationalMode {Normal, Exit}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
OperationalMode public operationalMode = OperationalMode.Normal;
BlockNumbUintsLib.BlockNumbUints private updateDelayBlocksByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private confirmationBlocksByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeMakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private tradeTakerFeeByBlockNumber;
BlockNumbDisdIntsLib.BlockNumbDisdInts private paymentFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbDisdIntsLib.BlockNumbDisdInts)) private currencyPaymentFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeMakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private tradeTakerMinimumFeeByBlockNumber;
BlockNumbIntsLib.BlockNumbInts private paymentMinimumFeeByBlockNumber;
mapping(address => mapping(uint256 => BlockNumbIntsLib.BlockNumbInts)) private currencyPaymentMinimumFeeByBlockNumber;
BlockNumbReferenceCurrenciesLib.BlockNumbReferenceCurrencies private feeCurrencyByCurrencyBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletLockTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private cancelOrderChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private settlementChallengeTimeoutByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private fraudStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private walletSettlementStakeFractionByBlockNumber;
BlockNumbUintsLib.BlockNumbUints private operatorSettlementStakeFractionByBlockNumber;
BlockNumbFiguresLib.BlockNumbFigures private operatorSettlementStakeByBlockNumber;
uint256 public earliestSettlementBlockNumber;
bool public earliestSettlementBlockNumberUpdateDisabled;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetOperationalModeExitEvent();
event SetUpdateDelayBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetConfirmationBlocksEvent(uint256 fromBlockNumber, uint256 newBlocks);
event SetTradeMakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetTradeTakerFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetPaymentFeeEvent(uint256 fromBlockNumber, int256 nominal, int256[] discountTiers, int256[] discountValues);
event SetCurrencyPaymentFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] discountTiers, int256[] discountValues);
event SetTradeMakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetTradeTakerMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetPaymentMinimumFeeEvent(uint256 fromBlockNumber, int256 nominal);
event SetCurrencyPaymentMinimumFeeEvent(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal);
event SetFeeCurrencyEvent(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId);
event SetWalletLockTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetCancelOrderChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetSettlementChallengeTimeoutEvent(uint256 fromBlockNumber, uint256 timeoutInSeconds);
event SetWalletSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetOperatorSettlementStakeEvent(uint256 fromBlockNumber, int256 stakeAmount, address stakeCurrencyCt,
uint256 stakeCurrencyId);
event SetFraudStakeFractionEvent(uint256 fromBlockNumber, uint256 stakeFraction);
event SetEarliestSettlementBlockNumberEvent(uint256 earliestSettlementBlockNumber);
event DisableEarliestSettlementBlockNumberUpdateEvent();
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
updateDelayBlocksByBlockNumber.addEntry(block.number, 0);
}
//
// Public functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set operational mode to Exit
/// @dev Once operational mode is set to Exit it may not be set back to Normal
function setOperationalModeExit()
public
onlyEnabledServiceAction(OPERATIONAL_MODE_ACTION)
{
operationalMode = OperationalMode.Exit;
emit SetOperationalModeExitEvent();
}
/// @notice Return true if operational mode is Normal
function isOperationalModeNormal()
public
view
returns (bool)
{
return OperationalMode.Normal == operationalMode;
}
/// @notice Return true if operational mode is Exit
function isOperationalModeExit()
public
view
returns (bool)
{
return OperationalMode.Exit == operationalMode;
}
/// @notice Get the current value of update delay blocks
/// @return The value of update delay blocks
function updateDelayBlocks()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of update delay blocks values
/// @return The count of update delay blocks values
function updateDelayBlocksCount()
public
view
returns (uint256)
{
return updateDelayBlocksByBlockNumber.count();
}
/// @notice Set the number of update delay blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newUpdateDelayBlocks The new update delay blocks value
function setUpdateDelayBlocks(uint256 fromBlockNumber, uint256 newUpdateDelayBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
updateDelayBlocksByBlockNumber.addEntry(fromBlockNumber, newUpdateDelayBlocks);
emit SetUpdateDelayBlocksEvent(fromBlockNumber, newUpdateDelayBlocks);
}
/// @notice Get the current value of confirmation blocks
/// @return The value of confirmation blocks
function confirmationBlocks()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.currentValue();
}
/// @notice Get the count of confirmation blocks values
/// @return The count of confirmation blocks values
function confirmationBlocksCount()
public
view
returns (uint256)
{
return confirmationBlocksByBlockNumber.count();
}
/// @notice Set the number of confirmation blocks
/// @param fromBlockNumber Block number from which the update applies
/// @param newConfirmationBlocks The new confirmation blocks value
function setConfirmationBlocks(uint256 fromBlockNumber, uint256 newConfirmationBlocks)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
confirmationBlocksByBlockNumber.addEntry(fromBlockNumber, newConfirmationBlocks);
emit SetConfirmationBlocksEvent(fromBlockNumber, newConfirmationBlocks);
}
/// @notice Get number of trade maker fee block number tiers
function tradeMakerFeesCount()
public
view
returns (uint256)
{
return tradeMakerFeeByBlockNumber.count();
}
/// @notice Get trade maker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeMakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeMakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade maker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeMakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeMakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of trade taker fee block number tiers
function tradeTakerFeesCount()
public
view
returns (uint256)
{
return tradeTakerFeeByBlockNumber.count();
}
/// @notice Get trade taker relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function tradeTakerFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return tradeTakerFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set trade taker nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setTradeTakerFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetTradeTakerFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers
function paymentFeesCount()
public
view
returns (uint256)
{
return paymentFeeByBlockNumber.count();
}
/// @notice Get payment relative fee at given block number, possibly discounted by discount tier value
/// @param blockNumber The concerned block number
/// @param discountTier The concerned discount tier
function paymentFee(uint256 blockNumber, int256 discountTier)
public
view
returns (int256)
{
return paymentFeeByBlockNumber.discountedValueAt(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setPaymentFee(uint256 fromBlockNumber, int256 nominal, int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentFeeByBlockNumber.addDiscountedEntry(fromBlockNumber, nominal, discountTiers, discountValues);
emit SetPaymentFeeEvent(fromBlockNumber, nominal, discountTiers, discountValues);
}
/// @notice Get number of payment fee block number tiers of given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment relative fee for given currency at given block number, possibly discounted by
/// discount tier value
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param discountTier The concerned discount tier
function currencyPaymentFee(uint256 blockNumber, address currencyCt, uint256 currencyId, int256 discountTier)
public
view
returns (int256)
{
if (0 < currencyPaymentFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentFeeByBlockNumber[currencyCt][currencyId].discountedValueAt(
blockNumber, discountTier
);
else
return paymentFee(blockNumber, discountTier);
}
/// @notice Set payment nominal relative fee and discount tiers and values for given currency at given
/// block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Nominal relative fee
/// @param nominal Discount tier levels
/// @param nominal Discount values
function setCurrencyPaymentFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal,
int256[] memory discountTiers, int256[] memory discountValues)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentFeeByBlockNumber[currencyCt][currencyId].addDiscountedEntry(
fromBlockNumber, nominal, discountTiers, discountValues
);
emit SetCurrencyPaymentFeeEvent(
fromBlockNumber, currencyCt, currencyId, nominal, discountTiers, discountValues
);
}
/// @notice Get number of minimum trade maker fee block number tiers
function tradeMakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeMakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade maker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeMakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeMakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade maker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeMakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeMakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeMakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum trade taker fee block number tiers
function tradeTakerMinimumFeesCount()
public
view
returns (uint256)
{
return tradeTakerMinimumFeeByBlockNumber.count();
}
/// @notice Get trade taker minimum relative fee at given block number
/// @param blockNumber The concerned block number
function tradeTakerMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return tradeTakerMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set trade taker minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setTradeTakerMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
tradeTakerMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetTradeTakerMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers
function paymentMinimumFeesCount()
public
view
returns (uint256)
{
return paymentMinimumFeeByBlockNumber.count();
}
/// @notice Get payment minimum relative fee at given block number
/// @param blockNumber The concerned block number
function paymentMinimumFee(uint256 blockNumber)
public
view
returns (int256)
{
return paymentMinimumFeeByBlockNumber.valueAt(blockNumber);
}
/// @notice Set payment minimum relative fee at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param nominal Minimum relative fee
function setPaymentMinimumFee(uint256 fromBlockNumber, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
paymentMinimumFeeByBlockNumber.addEntry(fromBlockNumber, nominal);
emit SetPaymentMinimumFeeEvent(fromBlockNumber, nominal);
}
/// @notice Get number of minimum payment fee block number tiers for given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFeesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count();
}
/// @notice Get payment minimum relative fee for given currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function currencyPaymentMinimumFee(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
if (0 < currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].count())
return currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].valueAt(blockNumber);
else
return paymentMinimumFee(blockNumber);
}
/// @notice Set payment minimum relative fee for given currency at given block number tier
/// @param fromBlockNumber Block number from which the update applies
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param nominal Minimum relative fee
function setCurrencyPaymentMinimumFee(uint256 fromBlockNumber, address currencyCt, uint256 currencyId, int256 nominal)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
currencyPaymentMinimumFeeByBlockNumber[currencyCt][currencyId].addEntry(fromBlockNumber, nominal);
emit SetCurrencyPaymentMinimumFeeEvent(fromBlockNumber, currencyCt, currencyId, nominal);
}
/// @notice Get number of fee currencies for the given reference currency
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrenciesCount(address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return feeCurrencyByCurrencyBlockNumber.count(MonetaryTypesLib.Currency(currencyCt, currencyId));
}
/// @notice Get the fee currency for the given reference currency at given block number
/// @param blockNumber The concerned block number
/// @param currencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned reference currency (0 for ETH and ERC20)
function feeCurrency(uint256 blockNumber, address currencyCt, uint256 currencyId)
public
view
returns (address ct, uint256 id)
{
MonetaryTypesLib.Currency storage _feeCurrency = feeCurrencyByCurrencyBlockNumber.currencyAt(
MonetaryTypesLib.Currency(currencyCt, currencyId), blockNumber
);
ct = _feeCurrency.ct;
id = _feeCurrency.id;
}
/// @notice Set the fee currency for the given reference currency at given block number
/// @param fromBlockNumber Block number from which the update applies
/// @param referenceCurrencyCt The address of the concerned reference currency contract (address(0) == ETH)
/// @param referenceCurrencyId The ID of the concerned reference currency (0 for ETH and ERC20)
/// @param feeCurrencyCt The address of the concerned fee currency contract (address(0) == ETH)
/// @param feeCurrencyId The ID of the concerned fee currency (0 for ETH and ERC20)
function setFeeCurrency(uint256 fromBlockNumber, address referenceCurrencyCt, uint256 referenceCurrencyId,
address feeCurrencyCt, uint256 feeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
feeCurrencyByCurrencyBlockNumber.addEntry(
fromBlockNumber,
MonetaryTypesLib.Currency(referenceCurrencyCt, referenceCurrencyId),
MonetaryTypesLib.Currency(feeCurrencyCt, feeCurrencyId)
);
emit SetFeeCurrencyEvent(fromBlockNumber, referenceCurrencyCt, referenceCurrencyId,
feeCurrencyCt, feeCurrencyId);
}
/// @notice Get the current value of wallet lock timeout
/// @return The value of wallet lock timeout
function walletLockTimeout()
public
view
returns (uint256)
{
return walletLockTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of wallet lock
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setWalletLockTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletLockTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetWalletLockTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of cancel order challenge timeout
/// @return The value of cancel order challenge timeout
function cancelOrderChallengeTimeout()
public
view
returns (uint256)
{
return cancelOrderChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of cancel order challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setCancelOrderChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
cancelOrderChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetCancelOrderChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of settlement challenge timeout
/// @return The value of settlement challenge timeout
function settlementChallengeTimeout()
public
view
returns (uint256)
{
return settlementChallengeTimeoutByBlockNumber.currentValue();
}
/// @notice Set timeout of settlement challenges
/// @param fromBlockNumber Block number from which the update applies
/// @param timeoutInSeconds Timeout duration in seconds
function setSettlementChallengeTimeout(uint256 fromBlockNumber, uint256 timeoutInSeconds)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
settlementChallengeTimeoutByBlockNumber.addEntry(fromBlockNumber, timeoutInSeconds);
emit SetSettlementChallengeTimeoutEvent(fromBlockNumber, timeoutInSeconds);
}
/// @notice Get the current value of fraud stake fraction
/// @return The value of fraud stake fraction
function fraudStakeFraction()
public
view
returns (uint256)
{
return fraudStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in fraud challenge
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setFraudStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
fraudStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetFraudStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of wallet settlement stake fraction
/// @return The value of wallet settlement stake fraction
function walletSettlementStakeFraction()
public
view
returns (uint256)
{
return walletSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by wallet
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setWalletSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
walletSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetWalletSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake fraction
/// @return The value of operator settlement stake fraction
function operatorSettlementStakeFraction()
public
view
returns (uint256)
{
return operatorSettlementStakeFractionByBlockNumber.currentValue();
}
/// @notice Set fraction of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeFraction The fraction gained
function setOperatorSettlementStakeFraction(uint256 fromBlockNumber, uint256 stakeFraction)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
operatorSettlementStakeFractionByBlockNumber.addEntry(fromBlockNumber, stakeFraction);
emit SetOperatorSettlementStakeFractionEvent(fromBlockNumber, stakeFraction);
}
/// @notice Get the current value of operator settlement stake
/// @return The value of operator settlement stake
function operatorSettlementStake()
public
view
returns (int256 amount, address currencyCt, uint256 currencyId)
{
MonetaryTypesLib.Figure storage stake = operatorSettlementStakeByBlockNumber.currentValue();
amount = stake.amount;
currencyCt = stake.currency.ct;
currencyId = stake.currency.id;
}
/// @notice Set figure of security bond that will be gained from successfully challenging
/// in settlement challenge triggered by operator
/// @param fromBlockNumber Block number from which the update applies
/// @param stakeAmount The amount gained
/// @param stakeCurrencyCt The address of currency gained
/// @param stakeCurrencyId The ID of currency gained
function setOperatorSettlementStake(uint256 fromBlockNumber, int256 stakeAmount,
address stakeCurrencyCt, uint256 stakeCurrencyId)
public
onlyOperator
onlyDelayedBlockNumber(fromBlockNumber)
{
MonetaryTypesLib.Figure memory stake = MonetaryTypesLib.Figure(stakeAmount, MonetaryTypesLib.Currency(stakeCurrencyCt, stakeCurrencyId));
operatorSettlementStakeByBlockNumber.addEntry(fromBlockNumber, stake);
emit SetOperatorSettlementStakeEvent(fromBlockNumber, stakeAmount, stakeCurrencyCt, stakeCurrencyId);
}
/// @notice Set the block number of the earliest settlement initiation
/// @param _earliestSettlementBlockNumber The block number of the earliest settlement
function setEarliestSettlementBlockNumber(uint256 _earliestSettlementBlockNumber)
public
onlyOperator
{
require(!earliestSettlementBlockNumberUpdateDisabled, "Earliest settlement block number update disabled [Configuration.sol:715]");
earliestSettlementBlockNumber = _earliestSettlementBlockNumber;
emit SetEarliestSettlementBlockNumberEvent(earliestSettlementBlockNumber);
}
/// @notice Disable further updates to the earliest settlement block number
/// @dev This operation can not be undone
function disableEarliestSettlementBlockNumberUpdate()
public
onlyOperator
{
earliestSettlementBlockNumberUpdateDisabled = true;
emit DisableEarliestSettlementBlockNumberUpdateEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyDelayedBlockNumber(uint256 blockNumber) {
require(
0 == updateDelayBlocksByBlockNumber.count() ||
blockNumber >= block.number + updateDelayBlocksByBlockNumber.currentValue(),
"Block number not sufficiently delayed [Configuration.sol:735]"
);
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Benefactor
* @notice An ownable that has a client fund property
*/
contract Configurable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Configuration public configuration;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetConfigurationEvent(Configuration oldConfiguration, Configuration newConfiguration);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the configuration contract
/// @param newConfiguration The (address of) Configuration contract instance
function setConfiguration(Configuration newConfiguration)
public
onlyDeployer
notNullAddress(address(newConfiguration))
notSameAddresses(address(newConfiguration), address(configuration))
{
// Set new configuration
Configuration oldConfiguration = configuration;
configuration = newConfiguration;
// Emit event
emit SetConfigurationEvent(oldConfiguration, newConfiguration);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier configurationInitialized() {
require(address(configuration) != address(0), "Configuration not initialized [Configurable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title ConfigurableOperational
* @notice A configurable with modifiers for operational mode state validation
*/
contract ConfigurableOperational is Configurable {
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyOperationalModeNormal() {
require(configuration.isOperationalModeNormal(), "Operational mode is not normal [ConfigurableOperational.sol:22]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS based on Open-Zeppelin's SafeMath library
*/
/**
* @title SafeMathUintLib
* @dev Math operations with safety checks that throw on error
*/
library SafeMathUintLib {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
assert(c >= a);
return c;
}
//
//Clamping functions.
//
function clamp(uint256 a, uint256 min, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : ((a < min) ? min : a);
}
function clampMin(uint256 a, uint256 min)
public
pure
returns (uint256)
{
return (a < min) ? min : a;
}
function clampMax(uint256 a, uint256 max)
public
pure
returns (uint256)
{
return (a > max) ? max : a;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library CurrenciesLib {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Currencies {
MonetaryTypesLib.Currency[] currencies;
mapping(address => mapping(uint256 => uint256)) indexByCurrency;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function add(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
if (0 == self.indexByCurrency[currencyCt][currencyId]) {
self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId));
self.indexByCurrency[currencyCt][currencyId] = self.currencies.length;
}
}
function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId)
internal
{
// Index is 1-based
uint256 index = self.indexByCurrency[currencyCt][currencyId];
if (0 < index)
removeByIndex(self, index - 1);
}
function removeByIndex(Currencies storage self, uint256 index)
internal
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:51]");
address currencyCt = self.currencies[index].ct;
uint256 currencyId = self.currencies[index].id;
if (index < self.currencies.length - 1) {
self.currencies[index] = self.currencies[self.currencies.length - 1];
self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1;
}
self.currencies.length--;
self.indexByCurrency[currencyCt][currencyId] = 0;
}
function count(Currencies storage self)
internal
view
returns (uint256)
{
return self.currencies.length;
}
function has(Currencies storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 != self.indexByCurrency[currencyCt][currencyId];
}
function getByIndex(Currencies storage self, uint256 index)
internal
view
returns (MonetaryTypesLib.Currency memory)
{
require(index < self.currencies.length, "Index out of bounds [CurrenciesLib.sol:85]");
return self.currencies[index];
}
function getByIndices(Currencies storage self, uint256 low, uint256 up)
internal
view
returns (MonetaryTypesLib.Currency[] memory)
{
require(0 < self.currencies.length, "No currencies found [CurrenciesLib.sol:94]");
require(low <= up, "Bounds parameters mismatch [CurrenciesLib.sol:95]");
up = up.clampMax(self.currencies.length - 1);
MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_currencies[i - low] = self.currencies[i];
return _currencies;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library FungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256 amount;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256)) amountByCurrency;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256)
{
return self.amountByCurrency[currencyCt][currencyId];
}
function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber);
return amount;
}
function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = amount;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub(_from, amount, currencyCt, currencyId);
add(_to, amount, currencyCt, currencyId);
}
function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount);
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.amountByCurrency[currencyCt][currencyId], block.number)
);
updateCurrencies(self, currencyCt, currencyId);
}
function transfer_nn(Balance storage _from, Balance storage _to, int256 amount,
address currencyCt, uint256 currencyId)
internal
{
sub_nn(_from, amount, currencyCt, currencyId);
add_nn(_to, amount, currencyCt, currencyId);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.amount, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (0, 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.amount, record.blockNumber);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library NonFungibleBalanceLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Record {
int256[] ids;
uint256 blockNumber;
}
struct Balance {
mapping(address => mapping(uint256 => int256[])) idsByCurrency;
mapping(address => mapping(uint256 => mapping(int256 => uint256))) idIndexById;
mapping(address => mapping(uint256 => Record[])) recordsByCurrency;
CurrenciesLib.Currencies inUseCurrencies;
CurrenciesLib.Currencies everUsedCurrencies;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function get(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory)
{
return self.idsByCurrency[currencyCt][currencyId];
}
function getByIndices(Balance storage self, address currencyCt, uint256 currencyId, uint256 indexLow, uint256 indexUp)
internal
view
returns (int256[] memory)
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length)
return new int256[](0);
indexUp = indexUp.clampMax(self.idsByCurrency[currencyCt][currencyId].length - 1);
int256[] memory idsByCurrency = new int256[](indexUp - indexLow + 1);
for (uint256 i = indexLow; i < indexUp; i++)
idsByCurrency[i - indexLow] = self.idsByCurrency[currencyCt][currencyId][i];
return idsByCurrency;
}
function idsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.idsByCurrency[currencyCt][currencyId].length;
}
function hasId(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return 0 < self.idIndexById[currencyCt][currencyId][id];
}
function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (int256[] memory, uint256)
{
uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber);
return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (new int256[](0), 0);
}
function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][index];
return (record.ids, record.blockNumber);
}
function lastRecord(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (int256[] memory, uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return (new int256[](0), 0);
Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1];
return (record.ids, record.blockNumber);
}
function recordsCount(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.recordsByCurrency[currencyCt][currencyId].length;
}
function set(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
{
int256[] memory ids = new int256[](1);
ids[0] = id;
set(self, ids, currencyCt, currencyId);
}
function set(Balance storage self, int256[] memory ids, address currencyCt, uint256 currencyId)
internal
{
uint256 i;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId] = ids;
for (i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = i + 1;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function reset(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
for (uint256 i = 0; i < self.idsByCurrency[currencyCt][currencyId].length; i++)
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][i]] = 0;
self.idsByCurrency[currencyCt][currencyId].length = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
}
function add(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
if (0 < self.idIndexById[currencyCt][currencyId][id])
return false;
self.idsByCurrency[currencyCt][currencyId].push(id);
self.idIndexById[currencyCt][currencyId][id] = self.idsByCurrency[currencyCt][currencyId].length;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function sub(Balance storage self, int256 id, address currencyCt, uint256 currencyId)
internal
returns (bool)
{
uint256 index = self.idIndexById[currencyCt][currencyId][id];
if (0 == index)
return false;
if (index < self.idsByCurrency[currencyCt][currencyId].length) {
self.idsByCurrency[currencyCt][currencyId][index - 1] = self.idsByCurrency[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId].length - 1];
self.idIndexById[currencyCt][currencyId][self.idsByCurrency[currencyCt][currencyId][index - 1]] = index;
}
self.idsByCurrency[currencyCt][currencyId].length--;
self.idIndexById[currencyCt][currencyId][id] = 0;
self.recordsByCurrency[currencyCt][currencyId].push(
Record(self.idsByCurrency[currencyCt][currencyId], block.number)
);
updateInUseCurrencies(self, currencyCt, currencyId);
return true;
}
function transfer(Balance storage _from, Balance storage _to, int256 id,
address currencyCt, uint256 currencyId)
internal
returns (bool)
{
return sub(_from, id, currencyCt, currencyId) && add(_to, id, currencyCt, currencyId);
}
function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.inUseCurrencies.has(currencyCt, currencyId);
}
function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId)
internal
view
returns (bool)
{
return self.everUsedCurrencies.has(currencyCt, currencyId);
}
function updateInUseCurrencies(Balance storage self, address currencyCt, uint256 currencyId)
internal
{
if (0 == self.idsByCurrency[currencyCt][currencyId].length && self.inUseCurrencies.has(currencyCt, currencyId))
self.inUseCurrencies.removeByCurrency(currencyCt, currencyId);
else if (!self.inUseCurrencies.has(currencyCt, currencyId)) {
self.inUseCurrencies.add(currencyCt, currencyId);
self.everUsedCurrencies.add(currencyCt, currencyId);
}
}
function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber)
internal
view
returns (uint256)
{
if (0 == self.recordsByCurrency[currencyCt][currencyId].length)
return 0;
for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--)
if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber)
return i;
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Balance tracker
* @notice An ownable to track balances of generic types
*/
contract BalanceTracker is Ownable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using NonFungibleBalanceLib for NonFungibleBalanceLib.Balance;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public DEPOSITED_BALANCE_TYPE = "deposited";
string constant public SETTLED_BALANCE_TYPE = "settled";
string constant public STAGED_BALANCE_TYPE = "staged";
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct Wallet {
mapping(bytes32 => FungibleBalanceLib.Balance) fungibleBalanceByType;
mapping(bytes32 => NonFungibleBalanceLib.Balance) nonFungibleBalanceByType;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bytes32 public depositedBalanceType;
bytes32 public settledBalanceType;
bytes32 public stagedBalanceType;
bytes32[] public _allBalanceTypes;
bytes32[] public _activeBalanceTypes;
bytes32[] public trackedBalanceTypes;
mapping(bytes32 => bool) public trackedBalanceTypeMap;
mapping(address => Wallet) private walletMap;
address[] public trackedWallets;
mapping(address => uint256) public trackedWalletIndexByWallet;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
depositedBalanceType = keccak256(abi.encodePacked(DEPOSITED_BALANCE_TYPE));
settledBalanceType = keccak256(abi.encodePacked(SETTLED_BALANCE_TYPE));
stagedBalanceType = keccak256(abi.encodePacked(STAGED_BALANCE_TYPE));
_allBalanceTypes.push(settledBalanceType);
_allBalanceTypes.push(depositedBalanceType);
_allBalanceTypes.push(stagedBalanceType);
_activeBalanceTypes.push(settledBalanceType);
_activeBalanceTypes.push(depositedBalanceType);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the fungible balance (amount) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function get(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return walletMap[wallet].fungibleBalanceByType[_type].get(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance (IDs) of the given wallet, type, currency and index range
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param indexLow The lower index of IDs
/// @param indexUp The upper index of IDs
/// @return The stored balance
function getByIndices(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 indexLow, uint256 indexUp)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].getByIndices(
currencyCt, currencyId, indexLow, indexUp
);
}
/// @notice Get all the non-fungible balance (IDs) of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The stored balance
function getAll(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].get(
currencyCt, currencyId
);
}
/// @notice Get the count of non-fungible IDs of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of IDs
function idsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].idsCount(
currencyCt, currencyId
);
}
/// @notice Gauge whether the ID is included in the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param id The ID of the concerned unit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if ID is included, else false
function hasId(address wallet, bytes32 _type, int256 id, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].hasId(
id, currencyCt, currencyId
);
}
/// @notice Set the balance of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if setting fungible balance, else false
function set(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId, bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].set(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Set the non-fungible balance IDs of the given wallet, type and currency to the given value
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param ids The ids of non-fungible) to set
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function setIds(address wallet, bytes32 _type, int256[] memory ids, address currencyCt, uint256 currencyId)
public
onlyActiveService
{
// Update the balance
walletMap[wallet].nonFungibleBalanceByType[_type].set(
ids, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Add the given value to the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to add
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if adding fungible balance, else false
function add(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].add(
value, currencyCt, currencyId
);
// Update balance type hashes
_updateTrackedBalanceTypes(_type);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Subtract the given value from the balance of the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param value The value (amount of fungible, id of non-fungible) to subtract
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param fungible True if subtracting fungible balance, else false
function sub(address wallet, bytes32 _type, int256 value, address currencyCt, uint256 currencyId,
bool fungible)
public
onlyActiveService
{
// Update the balance
if (fungible)
walletMap[wallet].fungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
else
walletMap[wallet].nonFungibleBalanceByType[_type].sub(
value, currencyCt, currencyId
);
// Update tracked wallets
_updateTrackedWallets(wallet);
}
/// @notice Gauge whether this tracker has in-use data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasInUseCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasInUseCurrency(currencyCt, currencyId);
}
/// @notice Gauge whether this tracker has ever-used data for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if data is stored, else false
function hasEverUsedCurrency(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return walletMap[wallet].fungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId)
|| walletMap[wallet].nonFungibleBalanceByType[_type].hasEverUsedCurrency(currencyCt, currencyId);
}
/// @notice Get the count of fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function fungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the fungible balance record for the given wallet, type, currency
/// log entry index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function fungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function fungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256 amount, uint256 blockNumber)
{
return walletMap[wallet].fungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of non-fungible balance records for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The count of balance log entries
function nonFungibleRecordsCount(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordsCount(currencyCt, currencyId);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and record index
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param index The concerned record index
/// @return The balance record
function nonFungibleRecordByIndex(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 index)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByIndex(currencyCt, currencyId, index);
}
/// @notice Get the non-fungible balance record for the given wallet, type, currency
/// and block number
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param _blockNumber The concerned block number
/// @return The balance record
function nonFungibleRecordByBlockNumber(address wallet, bytes32 _type, address currencyCt, uint256 currencyId,
uint256 _blockNumber)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].recordByBlockNumber(currencyCt, currencyId, _blockNumber);
}
/// @notice Get the last (most recent) non-fungible balance record for the given wallet, type and currency
/// @param wallet The address of the concerned wallet
/// @param _type The balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The last log entry
function lastNonFungibleRecord(address wallet, bytes32 _type, address currencyCt, uint256 currencyId)
public
view
returns (int256[] memory ids, uint256 blockNumber)
{
return walletMap[wallet].nonFungibleBalanceByType[_type].lastRecord(currencyCt, currencyId);
}
/// @notice Get the count of tracked balance types
/// @return The count of tracked balance types
function trackedBalanceTypesCount()
public
view
returns (uint256)
{
return trackedBalanceTypes.length;
}
/// @notice Get the count of tracked wallets
/// @return The count of tracked wallets
function trackedWalletsCount()
public
view
returns (uint256)
{
return trackedWallets.length;
}
/// @notice Get the default full set of balance types
/// @return The set of all balance types
function allBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _allBalanceTypes;
}
/// @notice Get the default set of active balance types
/// @return The set of active balance types
function activeBalanceTypes()
public
view
returns (bytes32[] memory)
{
return _activeBalanceTypes;
}
/// @notice Get the subset of tracked wallets in the given index range
/// @param low The lower index
/// @param up The upper index
/// @return The subset of tracked wallets
function trackedWalletsByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < trackedWallets.length, "No tracked wallets found [BalanceTracker.sol:473]");
require(low <= up, "Bounds parameters mismatch [BalanceTracker.sol:474]");
up = up.clampMax(trackedWallets.length - 1);
address[] memory _trackedWallets = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_trackedWallets[i - low] = trackedWallets[i];
return _trackedWallets;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _updateTrackedBalanceTypes(bytes32 _type)
private
{
if (!trackedBalanceTypeMap[_type]) {
trackedBalanceTypeMap[_type] = true;
trackedBalanceTypes.push(_type);
}
}
function _updateTrackedWallets(address wallet)
private
{
if (0 == trackedWalletIndexByWallet[wallet]) {
trackedWallets.push(wallet);
trackedWalletIndexByWallet[wallet] = trackedWallets.length;
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title BalanceTrackable
* @notice An ownable that has a balance tracker property
*/
contract BalanceTrackable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
BalanceTracker public balanceTracker;
bool public balanceTrackerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetBalanceTrackerEvent(BalanceTracker oldBalanceTracker, BalanceTracker newBalanceTracker);
event FreezeBalanceTrackerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the balance tracker contract
/// @param newBalanceTracker The (address of) BalanceTracker contract instance
function setBalanceTracker(BalanceTracker newBalanceTracker)
public
onlyDeployer
notNullAddress(address(newBalanceTracker))
notSameAddresses(address(newBalanceTracker), address(balanceTracker))
{
// Require that this contract has not been frozen
require(!balanceTrackerFrozen, "Balance tracker frozen [BalanceTrackable.sol:43]");
// Update fields
BalanceTracker oldBalanceTracker = balanceTracker;
balanceTracker = newBalanceTracker;
// Emit event
emit SetBalanceTrackerEvent(oldBalanceTracker, newBalanceTracker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeBalanceTracker()
public
onlyDeployer
{
balanceTrackerFrozen = true;
// Emit event
emit FreezeBalanceTrackerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier balanceTrackerInitialized() {
require(address(balanceTracker) != address(0), "Balance tracker not initialized [BalanceTrackable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AuthorizableServable
* @notice A servable that may be authorized and unauthorized
*/
contract AuthorizableServable is Servable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
bool public initialServiceAuthorizationDisabled;
mapping(address => bool) public initialServiceAuthorizedMap;
mapping(address => mapping(address => bool)) public initialServiceWalletUnauthorizedMap;
mapping(address => mapping(address => bool)) public serviceWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletAuthorizedMap;
mapping(address => mapping(bytes32 => mapping(address => bool))) public serviceActionWalletTouchedMap;
mapping(address => mapping(address => bytes32[])) public serviceWalletActionList;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AuthorizeInitialServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceEvent(address wallet, address service);
event AuthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
event UnauthorizeRegisteredServiceEvent(address wallet, address service);
event UnauthorizeRegisteredServiceActionEvent(address wallet, address service, string action);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Add service to initial whitelist of services
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeInitialService(address service)
public
onlyDeployer
notNullOrThisAddress(service)
{
require(!initialServiceAuthorizationDisabled);
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Enable all actions for given wallet
initialServiceAuthorizedMap[service] = true;
// Emit event
emit AuthorizeInitialServiceEvent(msg.sender, service);
}
/// @notice Disable further initial authorization of services
/// @dev This operation can not be undone
function disableInitialServiceAuthorization()
public
onlyDeployer
{
initialServiceAuthorizationDisabled = true;
}
/// @notice Authorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function authorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// Ensure service is not initial. Initial services are not authorized per action.
require(!initialServiceAuthorizedMap[service]);
// Enable all actions for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = true;
// Emit event
emit AuthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Unauthorize the given registered service by enabling all of actions
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
function unauthorizeRegisteredService(address service)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
// Ensure service is registered
require(registeredServicesMap[service].registered);
// If initial service then disable it
if (initialServiceAuthorizedMap[service])
initialServiceWalletUnauthorizedMap[service][msg.sender] = true;
// Else disable all actions for given wallet
else {
serviceWalletAuthorizedMap[service][msg.sender] = false;
for (uint256 i = 0; i < serviceWalletActionList[service][msg.sender].length; i++)
serviceActionWalletAuthorizedMap[service][serviceWalletActionList[service][msg.sender][i]][msg.sender] = true;
}
// Emit event
emit UnauthorizeRegisteredServiceEvent(msg.sender, service);
}
/// @notice Gauge whether the given service is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param wallet The address of the concerned wallet
/// @return true if service is authorized for the given wallet, else false
function isAuthorizedRegisteredService(address service, address wallet)
public
view
returns (bool)
{
return isRegisteredActiveService(service) &&
(isInitialServiceAuthorizedForWallet(service, wallet) || serviceWalletAuthorizedMap[service][wallet]);
}
/// @notice Authorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function authorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service action is registered
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial
require(!initialServiceAuthorizedMap[service]);
// Enable service action for given wallet
serviceWalletAuthorizedMap[service][msg.sender] = false;
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = true;
if (!serviceActionWalletTouchedMap[service][actionHash][msg.sender]) {
serviceActionWalletTouchedMap[service][actionHash][msg.sender] = true;
serviceWalletActionList[service][msg.sender].push(actionHash);
}
// Emit event
emit AuthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Unauthorize the given registered service action
/// @dev The service must be registered already
/// @param service The address of the concerned registered service
/// @param action The concerned service action
function unauthorizeRegisteredServiceAction(address service, string memory action)
public
notNullOrThisAddress(service)
{
require(msg.sender != service);
bytes32 actionHash = hashString(action);
// Ensure service is registered and action enabled
require(registeredServicesMap[service].registered && registeredServicesMap[service].actionsEnabledMap[actionHash]);
// Ensure service is not initial as it can not be unauthorized per action
require(!initialServiceAuthorizedMap[service]);
// Disable service action for given wallet
serviceActionWalletAuthorizedMap[service][actionHash][msg.sender] = false;
// Emit event
emit UnauthorizeRegisteredServiceActionEvent(msg.sender, service, action);
}
/// @notice Gauge whether the given service action is authorized for the given wallet
/// @param service The address of the concerned registered service
/// @param action The concerned service action
/// @param wallet The address of the concerned wallet
/// @return true if service action is authorized for the given wallet, else false
function isAuthorizedRegisteredServiceAction(address service, string memory action, address wallet)
public
view
returns (bool)
{
bytes32 actionHash = hashString(action);
return isEnabledServiceAction(service, action) &&
(
isInitialServiceAuthorizedForWallet(service, wallet) ||
serviceWalletAuthorizedMap[service][wallet] ||
serviceActionWalletAuthorizedMap[service][actionHash][wallet]
);
}
function isInitialServiceAuthorizedForWallet(address service, address wallet)
private
view
returns (bool)
{
return initialServiceAuthorizedMap[service] ? !initialServiceWalletUnauthorizedMap[service][wallet] : false;
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier onlyAuthorizedService(address wallet) {
require(isAuthorizedRegisteredService(msg.sender, wallet));
_;
}
modifier onlyAuthorizedServiceAction(string memory action, address wallet) {
require(isAuthorizedRegisteredServiceAction(msg.sender, action, wallet));
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Wallet locker
* @notice An ownable to lock and unlock wallets' balance holdings of specific currency(ies)
*/
contract WalletLocker is Ownable, Configurable, AuthorizableServable {
using SafeMathUintLib for uint256;
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct FungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256 amount;
uint256 visibleTime;
uint256 unlockTime;
}
struct NonFungibleLock {
address locker;
address currencyCt;
uint256 currencyId;
int256[] ids;
uint256 visibleTime;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => FungibleLock[]) public walletFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyFungibleLockCount;
mapping(address => NonFungibleLock[]) public walletNonFungibleLocks;
mapping(address => mapping(address => mapping(uint256 => mapping(address => uint256)))) public lockedCurrencyLockerNonFungibleLockIndex;
mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyNonFungibleLockCount;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event LockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event LockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds);
event UnlockFungibleEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256 amount, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
event UnlockNonFungibleByProxyEvent(address lockedWallet, address lockerWallet, int256[] ids, address currencyCt,
uint256 currencyId);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer)
public
{
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Lock the given locked wallet's fungible amount of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param amount The amount to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked amount is visible, a.o. for seizure
function lockFungibleByProxy(address lockedWallet, address lockerWallet, int256 amount,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletFungibleLocks[lockedWallet].length);
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletFungibleLocks[lockedWallet][lockIndex - 1].amount = amount;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Lock the given locked wallet's non-fungible IDs of currency on behalf of the given locker wallet
/// @param lockedWallet The address of wallet that will be locked
/// @param lockerWallet The address of wallet that locks
/// @param ids The IDs to be locked
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param visibleTimeoutInSeconds The number of seconds until the locked ids are visible, a.o. for seizure
function lockNonFungibleByProxy(address lockedWallet, address lockerWallet, int256[] memory ids,
address currencyCt, uint256 currencyId, uint256 visibleTimeoutInSeconds)
public
onlyAuthorizedService(lockedWallet)
{
// Require that locked and locker wallets are not identical
require(lockedWallet != lockerWallet);
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockedWallet];
// Require that there is no existing conflicting lock
require(
(0 == lockIndex) ||
(block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime)
);
// Add lock object for this triplet of locked wallet, currency and locker wallet if it does not exist
if (0 == lockIndex) {
lockIndex = ++(walletNonFungibleLocks[lockedWallet].length);
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = lockIndex;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]++;
}
// Update lock parameters
walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker = lockerWallet;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids = ids;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyCt = currencyCt;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].currencyId = currencyId;
walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime =
block.timestamp.add(visibleTimeoutInSeconds);
walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime =
block.timestamp.add(configuration.walletLockTimeout());
// Emit event
emit LockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId, visibleTimeoutInSeconds);
}
/// @notice Unlock the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's fungible amount of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256 amount = _unlockFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockFungibleByProxyEvent(lockedWallet, lockerWallet, amount, currencyCt, currencyId);
}
/// @notice Unlock the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Require that unlock timeout has expired
require(
block.timestamp >= walletNonFungibleLocks[lockedWallet][lockIndex - 1].unlockTime
);
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Unlock by proxy the given locked wallet's non-fungible IDs of currency previously
/// locked by the given locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function unlockNonFungibleByProxy(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
onlyAuthorizedService(lockedWallet)
{
// Get index of lock
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
// Return if no lock exists
if (0 == lockIndex)
return;
// Unlock
int256[] memory ids = _unlockNonFungible(lockedWallet, lockerWallet, currencyCt, currencyId, lockIndex);
// Emit event
emit UnlockNonFungibleByProxyEvent(lockedWallet, lockerWallet, ids, currencyCt, currencyId);
}
/// @notice Get the number of fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of fungible locks
function fungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletFungibleLocks[wallet].length;
}
/// @notice Get the number of non-fungible locks for the given wallet
/// @param wallet The address of the locked wallet
/// @return The number of non-fungible locks
function nonFungibleLocksCount(address wallet)
public
view
returns (uint256)
{
return walletNonFungibleLocks[wallet].length;
}
/// @notice Get the fungible amount of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedAmount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
uint256 lockIndex = lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
}
/// @notice Get the count of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function lockedIdsCount(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return 0;
return walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids.length;
}
/// @notice Get the set of non-fungible IDs of the given currency held by locked wallet that is
/// locked by locker wallet and whose indices are in the given range of indices
/// @param lockedWallet The address of the locked wallet
/// @param lockerWallet The address of the locker wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param low The lower ID index
/// @param up The upper ID index
function lockedIdsByIndices(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId,
uint256 low, uint256 up)
public
view
returns (int256[] memory)
{
uint256 lockIndex = lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
if (0 == lockIndex || block.timestamp < walletNonFungibleLocks[lockedWallet][lockIndex - 1].visibleTime)
return new int256[](0);
NonFungibleLock storage lock = walletNonFungibleLocks[lockedWallet][lockIndex - 1];
if (0 == lock.ids.length)
return new int256[](0);
up = up.clampMax(lock.ids.length - 1);
int256[] memory _ids = new int256[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_ids[i - low] = lock.ids[i];
return _ids;
}
/// @notice Gauge whether the given wallet is locked
/// @param wallet The address of the concerned wallet
/// @return true if wallet is locked, else false
function isLocked(address wallet)
public
view
returns (bool)
{
return 0 < walletFungibleLocks[wallet].length ||
0 < walletNonFungibleLocks[wallet].length;
}
/// @notice Gauge whether the given wallet and currency is locked
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if wallet/currency pair is locked, else false
function isLocked(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < walletCurrencyFungibleLockCount[wallet][currencyCt][currencyId] ||
0 < walletCurrencyNonFungibleLockCount[wallet][currencyCt][currencyId];
}
/// @notice Gauge whether the given locked wallet and currency is locked by the given locker wallet
/// @param lockedWallet The address of the concerned locked wallet
/// @param lockerWallet The address of the concerned locker wallet
/// @return true if lockedWallet is locked by lockerWallet, else false
function isLocked(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return 0 < lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] ||
0 < lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet];
}
//
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _unlockFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256)
{
int256 amount = walletFungibleLocks[lockedWallet][lockIndex - 1].amount;
if (lockIndex < walletFungibleLocks[lockedWallet].length) {
walletFungibleLocks[lockedWallet][lockIndex - 1] =
walletFungibleLocks[lockedWallet][walletFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return amount;
}
function _unlockNonFungible(address lockedWallet, address lockerWallet, address currencyCt, uint256 currencyId, uint256 lockIndex)
private
returns (int256[] memory)
{
int256[] memory ids = walletNonFungibleLocks[lockedWallet][lockIndex - 1].ids;
if (lockIndex < walletNonFungibleLocks[lockedWallet].length) {
walletNonFungibleLocks[lockedWallet][lockIndex - 1] =
walletNonFungibleLocks[lockedWallet][walletNonFungibleLocks[lockedWallet].length - 1];
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][walletNonFungibleLocks[lockedWallet][lockIndex - 1].locker] = lockIndex;
}
walletNonFungibleLocks[lockedWallet].length--;
lockedCurrencyLockerNonFungibleLockIndex[lockedWallet][currencyCt][currencyId][lockerWallet] = 0;
walletCurrencyNonFungibleLockCount[lockedWallet][currencyCt][currencyId]--;
return ids;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title WalletLockable
* @notice An ownable that has a wallet locker property
*/
contract WalletLockable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
WalletLocker public walletLocker;
bool public walletLockerFrozen;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetWalletLockerEvent(WalletLocker oldWalletLocker, WalletLocker newWalletLocker);
event FreezeWalletLockerEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the wallet locker contract
/// @param newWalletLocker The (address of) WalletLocker contract instance
function setWalletLocker(WalletLocker newWalletLocker)
public
onlyDeployer
notNullAddress(address(newWalletLocker))
notSameAddresses(address(newWalletLocker), address(walletLocker))
{
// Require that this contract has not been frozen
require(!walletLockerFrozen, "Wallet locker frozen [WalletLockable.sol:43]");
// Update fields
WalletLocker oldWalletLocker = walletLocker;
walletLocker = newWalletLocker;
// Emit event
emit SetWalletLockerEvent(oldWalletLocker, newWalletLocker);
}
/// @notice Freeze the balance tracker from further updates
/// @dev This operation can not be undone
function freezeWalletLocker()
public
onlyDeployer
{
walletLockerFrozen = true;
// Emit event
emit FreezeWalletLockerEvent();
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier walletLockerInitialized() {
require(address(walletLocker) != address(0), "Wallet locker not initialized [WalletLockable.sol:69]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NahmiiTypesLib
* @dev Data types of general nahmii character
*/
library NahmiiTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum ChallengePhase {Dispute, Closed}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OriginFigure {
uint256 originId;
MonetaryTypesLib.Figure figure;
}
struct IntendedConjugateCurrency {
MonetaryTypesLib.Currency intended;
MonetaryTypesLib.Currency conjugate;
}
struct SingleFigureTotalOriginFigures {
MonetaryTypesLib.Figure single;
OriginFigure[] total;
}
struct TotalOriginFigures {
OriginFigure[] total;
}
struct CurrentPreviousInt256 {
int256 current;
int256 previous;
}
struct SingleTotalInt256 {
int256 single;
int256 total;
}
struct IntendedConjugateCurrentPreviousInt256 {
CurrentPreviousInt256 intended;
CurrentPreviousInt256 conjugate;
}
struct IntendedConjugateSingleTotalInt256 {
SingleTotalInt256 intended;
SingleTotalInt256 conjugate;
}
struct WalletOperatorHashes {
bytes32 wallet;
bytes32 operator;
}
struct Signature {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Seal {
bytes32 hash;
Signature signature;
}
struct WalletOperatorSeal {
Seal wallet;
Seal operator;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentTypesLib
* @dev Data types centered around payment
*/
library PaymentTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum PaymentPartyRole {Sender, Recipient}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct PaymentSenderParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
string data;
}
struct PaymentRecipientParty {
uint256 nonce;
address wallet;
NahmiiTypesLib.CurrentPreviousInt256 balances;
NahmiiTypesLib.TotalOriginFigures fees;
}
struct Operator {
uint256 id;
string data;
}
struct Payment {
int256 amount;
MonetaryTypesLib.Currency currency;
PaymentSenderParty sender;
PaymentRecipientParty recipient;
// Positive transfer is always in direction from sender to recipient
NahmiiTypesLib.SingleTotalInt256 transfers;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
Operator operator;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function PAYMENT_KIND()
public
pure
returns (string memory)
{
return "payment";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHasher
* @notice Contract that hashes types related to payment
*/
contract PaymentHasher is Ownable {
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function hashPaymentAsWallet(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 amountCurrencyHash = hashPaymentAmountCurrency(payment);
bytes32 senderHash = hashPaymentSenderPartyAsWallet(payment.sender);
bytes32 recipientHash = hashAddress(payment.recipient.wallet);
return keccak256(abi.encodePacked(amountCurrencyHash, senderHash, recipientHash));
}
function hashPaymentAsOperator(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
bytes32 walletSignatureHash = hashSignature(payment.seals.wallet.signature);
bytes32 senderHash = hashPaymentSenderPartyAsOperator(payment.sender);
bytes32 recipientHash = hashPaymentRecipientPartyAsOperator(payment.recipient);
bytes32 transfersHash = hashSingleTotalInt256(payment.transfers);
bytes32 operatorHash = hashString(payment.operator.data);
return keccak256(abi.encodePacked(
walletSignatureHash, senderHash, recipientHash, transfersHash, operatorHash
));
}
function hashPaymentAmountCurrency(PaymentTypesLib.Payment memory payment)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
payment.amount,
payment.currency.ct,
payment.currency.id
));
}
function hashPaymentSenderPartyAsWallet(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
paymentSenderParty.wallet,
paymentSenderParty.data
));
}
function hashPaymentSenderPartyAsOperator(
PaymentTypesLib.PaymentSenderParty memory paymentSenderParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentSenderParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentSenderParty.balances);
bytes32 singleFeeHash = hashFigure(paymentSenderParty.fees.single);
bytes32 totalFeesHash = hashOriginFigures(paymentSenderParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, singleFeeHash, totalFeesHash
));
}
function hashPaymentRecipientPartyAsOperator(
PaymentTypesLib.PaymentRecipientParty memory paymentRecipientParty)
public
pure
returns (bytes32)
{
bytes32 rootHash = hashUint256(paymentRecipientParty.nonce);
bytes32 balancesHash = hashCurrentPreviousInt256(paymentRecipientParty.balances);
bytes32 totalFeesHash = hashOriginFigures(paymentRecipientParty.fees.total);
return keccak256(abi.encodePacked(
rootHash, balancesHash, totalFeesHash
));
}
function hashCurrentPreviousInt256(
NahmiiTypesLib.CurrentPreviousInt256 memory currentPreviousInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
currentPreviousInt256.current,
currentPreviousInt256.previous
));
}
function hashSingleTotalInt256(
NahmiiTypesLib.SingleTotalInt256 memory singleTotalInt256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
singleTotalInt256.single,
singleTotalInt256.total
));
}
function hashFigure(MonetaryTypesLib.Figure memory figure)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
figure.amount,
figure.currency.ct,
figure.currency.id
));
}
function hashOriginFigures(NahmiiTypesLib.OriginFigure[] memory originFigures)
public
pure
returns (bytes32)
{
bytes32 hash;
for (uint256 i = 0; i < originFigures.length; i++) {
hash = keccak256(abi.encodePacked(
hash,
originFigures[i].originId,
originFigures[i].figure.amount,
originFigures[i].figure.currency.ct,
originFigures[i].figure.currency.id
)
);
}
return hash;
}
function hashUint256(uint256 _uint256)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_uint256));
}
function hashString(string memory _string)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_string));
}
function hashAddress(address _address)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_address));
}
function hashSignature(NahmiiTypesLib.Signature memory signature)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(
signature.v,
signature.r,
signature.s
));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title PaymentHashable
* @notice An ownable that has a payment hasher property
*/
contract PaymentHashable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
PaymentHasher public paymentHasher;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetPaymentHasherEvent(PaymentHasher oldPaymentHasher, PaymentHasher newPaymentHasher);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the payment hasher contract
/// @param newPaymentHasher The (address of) PaymentHasher contract instance
function setPaymentHasher(PaymentHasher newPaymentHasher)
public
onlyDeployer
notNullAddress(address(newPaymentHasher))
notSameAddresses(address(newPaymentHasher), address(paymentHasher))
{
// Set new payment hasher
PaymentHasher oldPaymentHasher = paymentHasher;
paymentHasher = newPaymentHasher;
// Emit event
emit SetPaymentHasherEvent(oldPaymentHasher, newPaymentHasher);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier paymentHasherInitialized() {
require(address(paymentHasher) != address(0), "Payment hasher not initialized [PaymentHashable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManager
* @notice A contract to control who can execute some specific actions
*/
contract SignerManager is Ownable {
using SafeMathUintLib for uint256;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(address => uint256) public signerIndicesMap; // 1 based internally
address[] public signers;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterSignerEvent(address signer);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
registerSigner(deployer);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Gauge whether an address is registered signer
/// @param _address The concerned address
/// @return true if address is registered signer, else false
function isSigner(address _address)
public
view
returns (bool)
{
return 0 < signerIndicesMap[_address];
}
/// @notice Get the count of registered signers
/// @return The count of registered signers
function signersCount()
public
view
returns (uint256)
{
return signers.length;
}
/// @notice Get the 0 based index of the given address in the list of signers
/// @param _address The concerned address
/// @return The index of the signer address
function signerIndex(address _address)
public
view
returns (uint256)
{
require(isSigner(_address), "Address not signer [SignerManager.sol:71]");
return signerIndicesMap[_address] - 1;
}
/// @notice Registers a signer
/// @param newSigner The address of the signer to register
function registerSigner(address newSigner)
public
onlyOperator
notNullOrThisAddress(newSigner)
{
if (0 == signerIndicesMap[newSigner]) {
// Set new operator
signers.push(newSigner);
signerIndicesMap[newSigner] = signers.length;
// Emit event
emit RegisterSignerEvent(newSigner);
}
}
/// @notice Get the subset of registered signers in the given 0 based index range
/// @param low The lower inclusive index
/// @param up The upper inclusive index
/// @return The subset of registered signers
function signersByIndices(uint256 low, uint256 up)
public
view
returns (address[] memory)
{
require(0 < signers.length, "No signers found [SignerManager.sol:101]");
require(low <= up, "Bounds parameters mismatch [SignerManager.sol:102]");
up = up.clampMax(signers.length - 1);
address[] memory _signers = new address[](up - low + 1);
for (uint256 i = low; i <= up; i++)
_signers[i - low] = signers[i];
return _signers;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SignerManageable
* @notice A contract to interface ACL
*/
contract SignerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SignerManager public signerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSignerManagerEvent(address oldSignerManager, address newSignerManager);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address manager) public notNullAddress(manager) {
signerManager = SignerManager(manager);
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the signer manager of this contract
/// @param newSignerManager The address of the new signer
function setSignerManager(address newSignerManager)
public
onlyDeployer
notNullOrThisAddress(newSignerManager)
{
if (newSignerManager != address(signerManager)) {
//set new signer
address oldSignerManager = address(signerManager);
signerManager = SignerManager(newSignerManager);
// Emit event
emit SetSignerManagerEvent(oldSignerManager, newSignerManager);
}
}
/// @notice Prefix input hash and do ecrecover on prefixed hash
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return The address recovered
function ethrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
pure
returns (address)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
return ecrecover(prefixedHash, v, r, s);
}
/// @notice Gauge whether a signature of a hash has been signed by a registered signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @return true if the recovered signer is one of the registered signers, else false
function isSignedByRegisteredSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
view
returns (bool)
{
return signerManager.isSigner(ethrecover(hash, v, r, s));
}
/// @notice Gauge whether a signature of a hash has been signed by the claimed signer
/// @param hash The hash message that was signed
/// @param v The v property of the ECDSA signature
/// @param r The r property of the ECDSA signature
/// @param s The s property of the ECDSA signature
/// @param signer The claimed signer
/// @return true if the recovered signer equals the input signer, else false
function isSignedBy(bytes32 hash, uint8 v, bytes32 r, bytes32 s, address signer)
public
pure
returns (bool)
{
return signer == ethrecover(hash, v, r, s);
}
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier signerManagerInitialized() {
require(address(signerManager) != address(0), "Signer manager not initialized [SignerManageable.sol:105]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validator
* @notice An ownable that validates valuable types (e.g. payment)
*/
contract Validator is Ownable, SignerManageable, Configurable, PaymentHashable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer, address signerManager) Ownable(deployer) SignerManageable(signerManager) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isGenuineOperatorSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature)
public
view
returns (bool)
{
return isSignedByRegisteredSigner(hash, signature.v, signature.r, signature.s);
}
function isGenuineWalletSignature(bytes32 hash, NahmiiTypesLib.Signature memory signature, address wallet)
public
pure
returns (bool)
{
return isSignedBy(hash, signature.v, signature.r, signature.s, wallet);
}
function isGenuinePaymentWalletHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsWallet(payment) == payment.seals.wallet.hash;
}
function isGenuinePaymentOperatorHash(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return paymentHasher.hashPaymentAsOperator(payment) == payment.seals.operator.hash;
}
function isGenuinePaymentWalletSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletHash(payment)
&& isGenuineWalletSignature(payment.seals.wallet.hash, payment.seals.wallet.signature, payment.sender.wallet);
}
function isGenuinePaymentOperatorSeal(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentOperatorHash(payment)
&& isGenuineOperatorSignature(payment.seals.operator.hash, payment.seals.operator.signature);
}
function isGenuinePaymentSeals(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return isGenuinePaymentWalletSeal(payment) && isGenuinePaymentOperatorSeal(payment);
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentFeeOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
int256 feePartsPer = int256(ConstantsLib.PARTS_PER());
int256 feeAmount = payment.amount
.mul(
configuration.currencyPaymentFee(
payment.blockNumber, payment.currency.ct, payment.currency.id, payment.amount
)
).div(feePartsPer);
if (1 > feeAmount)
feeAmount = 1;
return (payment.sender.fees.single.amount == feeAmount);
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentFeeOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
(address feeCurrencyCt, uint256 feeCurrencyId) = configuration.feeCurrency(
payment.blockNumber, payment.currency.ct, payment.currency.id
);
return feeCurrencyCt == payment.sender.fees.single.currency.ct
&& feeCurrencyId == payment.sender.fees.single.currency.id;
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentSenderOfFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet))
&& (payment.sender.balances.current == payment.sender.balances.previous.sub(payment.transfers.single).sub(payment.sender.fees.single.amount));
}
/// @dev Logics of this function only applies to FT
function isGenuinePaymentRecipientOfFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (payment.recipient.balances.current == payment.recipient.balances.previous.add(payment.transfers.single));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentSenderOfNonFungible(PaymentTypesLib.Payment memory payment)
public
view
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet)
&& (!signerManager.isSigner(payment.sender.wallet));
}
/// @dev Logics of this function only applies to NFT
function isGenuinePaymentRecipientOfNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return (payment.sender.wallet != payment.recipient.wallet);
}
function isSuccessivePaymentsPartyNonces(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole
)
public
pure
returns (bool)
{
uint256 firstNonce = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.nonce : firstPayment.recipient.nonce);
uint256 lastNonce = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.nonce : lastPayment.recipient.nonce);
return lastNonce == firstNonce.add(1);
}
function isGenuineSuccessivePaymentsBalances(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.PaymentPartyRole firstPaymentPartyRole,
PaymentTypesLib.Payment memory lastPayment,
PaymentTypesLib.PaymentPartyRole lastPaymentPartyRole,
int256 delta
)
public
pure
returns (bool)
{
NahmiiTypesLib.CurrentPreviousInt256 memory firstCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == firstPaymentPartyRole ? firstPayment.sender.balances : firstPayment.recipient.balances);
NahmiiTypesLib.CurrentPreviousInt256 memory lastCurrentPreviousBalances = (PaymentTypesLib.PaymentPartyRole.Sender == lastPaymentPartyRole ? lastPayment.sender.balances : lastPayment.recipient.balances);
return lastCurrentPreviousBalances.previous == firstCurrentPreviousBalances.current.add(delta);
}
function isGenuineSuccessivePaymentsTotalFees(
PaymentTypesLib.Payment memory firstPayment,
PaymentTypesLib.Payment memory lastPayment
)
public
pure
returns (bool)
{
MonetaryTypesLib.Figure memory firstTotalFee = getProtocolFigureByCurrency(firstPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
MonetaryTypesLib.Figure memory lastTotalFee = getProtocolFigureByCurrency(lastPayment.sender.fees.total, lastPayment.sender.fees.single.currency);
return lastTotalFee.amount == firstTotalFee.amount.add(lastPayment.sender.fees.single.amount);
}
function isPaymentParty(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet || wallet == payment.recipient.wallet;
}
function isPaymentSender(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.sender.wallet;
}
function isPaymentRecipient(PaymentTypesLib.Payment memory payment, address wallet)
public
pure
returns (bool)
{
return wallet == payment.recipient.wallet;
}
function isPaymentCurrency(PaymentTypesLib.Payment memory payment, MonetaryTypesLib.Currency memory currency)
public
pure
returns (bool)
{
return currency.ct == payment.currency.ct && currency.id == payment.currency.id;
}
function isPaymentCurrencyNonFungible(PaymentTypesLib.Payment memory payment)
public
pure
returns (bool)
{
return payment.currency.ct != payment.sender.fees.single.currency.ct
|| payment.currency.id != payment.sender.fees.single.currency.id;
}
//
// Private unctions
// -----------------------------------------------------------------------------------------------------------------
function getProtocolFigureByCurrency(NahmiiTypesLib.OriginFigure[] memory originFigures, MonetaryTypesLib.Currency memory currency)
private
pure
returns (MonetaryTypesLib.Figure memory) {
for (uint256 i = 0; i < originFigures.length; i++)
if (originFigures[i].figure.currency.ct == currency.ct && originFigures[i].figure.currency.id == currency.id
&& originFigures[i].originId == 0)
return originFigures[i].figure;
return MonetaryTypesLib.Figure(0, currency);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TradeTypesLib
* @dev Data types centered around trade
*/
library TradeTypesLib {
//
// Enums
// -----------------------------------------------------------------------------------------------------------------
enum CurrencyRole {Intended, Conjugate}
enum LiquidityRole {Maker, Taker}
enum Intention {Buy, Sell}
enum TradePartyRole {Buyer, Seller}
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct OrderPlacement {
Intention intention;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct Order {
uint256 nonce;
address wallet;
OrderPlacement placement;
NahmiiTypesLib.WalletOperatorSeal seals;
uint256 blockNumber;
uint256 operatorId;
}
struct TradeOrder {
int256 amount;
NahmiiTypesLib.WalletOperatorHashes hashes;
NahmiiTypesLib.CurrentPreviousInt256 residuals;
}
struct TradeParty {
uint256 nonce;
address wallet;
uint256 rollingVolume;
LiquidityRole liquidityRole;
TradeOrder order;
NahmiiTypesLib.IntendedConjugateCurrentPreviousInt256 balances;
NahmiiTypesLib.SingleFigureTotalOriginFigures fees;
}
struct Trade {
uint256 nonce;
int256 amount;
NahmiiTypesLib.IntendedConjugateCurrency currencies;
int256 rate;
TradeParty buyer;
TradeParty seller;
// Positive intended transfer is always in direction from seller to buyer
// Positive conjugate transfer is always in direction from buyer to seller
NahmiiTypesLib.IntendedConjugateSingleTotalInt256 transfers;
NahmiiTypesLib.Seal seal;
uint256 blockNumber;
uint256 operatorId;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function TRADE_KIND()
public
pure
returns (string memory)
{
return "trade";
}
function ORDER_KIND()
public
pure
returns (string memory)
{
return "order";
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Validatable
* @notice An ownable that has a validator property
*/
contract Validatable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
Validator public validator;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetValidatorEvent(Validator oldValidator, Validator newValidator);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the validator contract
/// @param newValidator The (address of) Validator contract instance
function setValidator(Validator newValidator)
public
onlyDeployer
notNullAddress(address(newValidator))
notSameAddresses(address(newValidator), address(validator))
{
//set new validator
Validator oldValidator = validator;
validator = newValidator;
// Emit event
emit SetValidatorEvent(oldValidator, newValidator);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier validatorInitialized() {
require(address(validator) != address(0), "Validator not initialized [Validatable.sol:55]");
_;
}
modifier onlyOperatorSealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentOperatorSeal(payment), "Payment operator seal not genuine [Validatable.sol:60]");
_;
}
modifier onlySealedPayment(PaymentTypesLib.Payment memory payment) {
require(validator.isGenuinePaymentSeals(payment), "Payment seals not genuine [Validatable.sol:65]");
_;
}
modifier onlyPaymentParty(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentParty(payment, wallet), "Wallet not payment party [Validatable.sol:70]");
_;
}
modifier onlyPaymentSender(PaymentTypesLib.Payment memory payment, address wallet) {
require(validator.isPaymentSender(payment, wallet), "Wallet not payment sender [Validatable.sol:75]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title Beneficiary
* @notice A recipient of ethers and tokens
*/
contract Beneficiary {
/// @notice Receive ethers to the given wallet's given balance type
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
function receiveEthersTo(address wallet, string memory balanceType)
public
payable;
/// @notice Receive token to the given wallet's given balance type
/// @dev The wallet must approve of the token transfer prior to calling this function
/// @param wallet The address of the concerned wallet
/// @param balanceType The target balance type of the wallet
/// @param amount The amount to deposit
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory balanceType, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public;
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title AccrualBeneficiary
* @notice A beneficiary of accruals
*/
contract AccrualBeneficiary is Beneficiary {
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
event CloseAccrualPeriodEvent();
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function closeAccrualPeriod(MonetaryTypesLib.Currency[] memory)
public
{
emit CloseAccrualPeriodEvent();
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferController
* @notice A base contract to handle transfers of different currency types
*/
contract TransferController {
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event CurrencyTransferred(address from, address to, uint256 value,
address currencyCt, uint256 currencyId);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function isFungible()
public
view
returns (bool);
function standard()
public
view
returns (string memory);
/// @notice MUST be called with DELEGATECALL
function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function approve(address to, uint256 value, address currencyCt, uint256 currencyId)
public;
/// @notice MUST be called with DELEGATECALL
function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId)
public;
//----------------------------------------
function getReceiveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("receive(address,address,uint256,address,uint256)"));
}
function getApproveSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("approve(address,uint256,address,uint256)"));
}
function getDispatchSignature()
public
pure
returns (bytes4)
{
return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)"));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManager
* @notice Handles the management of transfer controllers
*/
contract TransferControllerManager is Ownable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
struct CurrencyInfo {
bytes32 standard;
bool blacklisted;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
mapping(bytes32 => address) public registeredTransferControllers;
mapping(address => CurrencyInfo) public registeredCurrencies;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event RegisterTransferControllerEvent(string standard, address controller);
event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller);
event RegisterCurrencyEvent(address currencyCt, string standard);
event DeregisterCurrencyEvent(address currencyCt);
event BlacklistCurrencyEvent(address currencyCt);
event WhitelistCurrencyEvent(address currencyCt);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function registerTransferController(string calldata standard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:58]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
registeredTransferControllers[standardHash] = controller;
// Emit event
emit RegisterTransferControllerEvent(standard, controller);
}
function reassociateTransferController(string calldata oldStandard, string calldata newStandard, address controller)
external
onlyDeployer
notNullAddress(controller)
{
require(bytes(newStandard).length > 0, "Empty new standard not supported [TransferControllerManager.sol:72]");
bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard));
bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard));
require(registeredTransferControllers[oldStandardHash] != address(0), "Old standard not registered [TransferControllerManager.sol:76]");
require(registeredTransferControllers[newStandardHash] == address(0), "New standard previously registered [TransferControllerManager.sol:77]");
registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash];
registeredTransferControllers[oldStandardHash] = address(0);
// Emit event
emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller);
}
function registerCurrency(address currencyCt, string calldata standard)
external
onlyOperator
notNullAddress(currencyCt)
{
require(bytes(standard).length > 0, "Empty standard not supported [TransferControllerManager.sol:91]");
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredCurrencies[currencyCt].standard == bytes32(0), "Currency previously registered [TransferControllerManager.sol:94]");
registeredCurrencies[currencyCt].standard = standardHash;
// Emit event
emit RegisterCurrencyEvent(currencyCt, standard);
}
function deregisterCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != 0, "Currency not registered [TransferControllerManager.sol:106]");
registeredCurrencies[currencyCt].standard = bytes32(0);
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit DeregisterCurrencyEvent(currencyCt);
}
function blacklistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:119]");
registeredCurrencies[currencyCt].blacklisted = true;
// Emit event
emit BlacklistCurrencyEvent(currencyCt);
}
function whitelistCurrency(address currencyCt)
external
onlyOperator
{
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:131]");
registeredCurrencies[currencyCt].blacklisted = false;
// Emit event
emit WhitelistCurrencyEvent(currencyCt);
}
/**
@notice The provided standard takes priority over assigned interface to currency
*/
function transferController(address currencyCt, string memory standard)
public
view
returns (TransferController)
{
if (bytes(standard).length > 0) {
bytes32 standardHash = keccak256(abi.encodePacked(standard));
require(registeredTransferControllers[standardHash] != address(0), "Standard not registered [TransferControllerManager.sol:150]");
return TransferController(registeredTransferControllers[standardHash]);
}
require(registeredCurrencies[currencyCt].standard != bytes32(0), "Currency not registered [TransferControllerManager.sol:154]");
require(!registeredCurrencies[currencyCt].blacklisted, "Currency blacklisted [TransferControllerManager.sol:155]");
address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard];
require(controllerAddress != address(0), "No matching transfer controller [TransferControllerManager.sol:158]");
return TransferController(controllerAddress);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title TransferControllerManageable
* @notice An ownable with a transfer controller manager
*/
contract TransferControllerManageable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
TransferControllerManager public transferControllerManager;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager,
TransferControllerManager newTransferControllerManager);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the currency manager contract
/// @param newTransferControllerManager The (address of) TransferControllerManager contract instance
function setTransferControllerManager(TransferControllerManager newTransferControllerManager)
public
onlyDeployer
notNullAddress(address(newTransferControllerManager))
notSameAddresses(address(newTransferControllerManager), address(transferControllerManager))
{
//set new currency manager
TransferControllerManager oldTransferControllerManager = transferControllerManager;
transferControllerManager = newTransferControllerManager;
// Emit event
emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager);
}
/// @notice Get the transfer controller of the given currency contract address and standard
function transferController(address currencyCt, string memory standard)
internal
view
returns (TransferController)
{
return transferControllerManager.transferController(currencyCt, standard);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier transferControllerManagerInitialized() {
require(address(transferControllerManager) != address(0), "Transfer controller manager not initialized [TransferControllerManageable.sol:63]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library TxHistoryLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
struct AssetEntry {
int256 amount;
uint256 blockNumber;
address currencyCt; //0 for ethers
uint256 currencyId;
}
struct TxHistory {
AssetEntry[] deposits;
mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits;
AssetEntry[] withdrawals;
mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals;
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId);
self.deposits.push(deposit);
self.currencyDeposits[currencyCt][currencyId].push(deposit);
}
function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId)
internal
{
AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId);
self.withdrawals.push(withdrawal);
self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal);
}
//----
function deposit(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.deposits.length, "Index ouf of bounds [TxHistoryLib.sol:56]");
amount = self.deposits[index].amount;
blockNumber = self.deposits[index].blockNumber;
currencyCt = self.deposits[index].currencyCt;
currencyId = self.deposits[index].currencyId;
}
function depositsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.deposits.length;
}
function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyDeposits[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:77]");
amount = self.currencyDeposits[currencyCt][currencyId][index].amount;
blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber;
}
function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyDeposits[currencyCt][currencyId].length;
}
//----
function withdrawal(TxHistory storage self, uint index)
internal
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
require(index < self.withdrawals.length, "Index out of bounds [TxHistoryLib.sol:98]");
amount = self.withdrawals[index].amount;
blockNumber = self.withdrawals[index].blockNumber;
currencyCt = self.withdrawals[index].currencyCt;
currencyId = self.withdrawals[index].currencyId;
}
function withdrawalsCount(TxHistory storage self)
internal
view
returns (uint256)
{
return self.withdrawals.length;
}
function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index)
internal
view
returns (int256 amount, uint256 blockNumber)
{
require(index < self.currencyWithdrawals[currencyCt][currencyId].length, "Index out of bounds [TxHistoryLib.sol:119]");
amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount;
blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber;
}
function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId)
internal
view
returns (uint256)
{
return self.currencyWithdrawals[currencyCt][currencyId].length;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBond
* @notice Fund that contains crypto incentive for challenging operator fraud.
*/
contract SecurityBond is Ownable, Configurable, AccrualBeneficiary, Servable, TransferControllerManageable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using FungibleBalanceLib for FungibleBalanceLib.Balance;
using TxHistoryLib for TxHistoryLib.TxHistory;
using CurrenciesLib for CurrenciesLib.Currencies;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public REWARD_ACTION = "reward";
string constant public DEPRIVE_ACTION = "deprive";
//
// Types
// -----------------------------------------------------------------------------------------------------------------
struct FractionalReward {
uint256 fraction;
uint256 nonce;
uint256 unlockTime;
}
struct AbsoluteReward {
int256 amount;
uint256 nonce;
uint256 unlockTime;
}
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FungibleBalanceLib.Balance private deposited;
TxHistoryLib.TxHistory private txHistory;
CurrenciesLib.Currencies private inUseCurrencies;
mapping(address => FractionalReward) public fractionalRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => AbsoluteReward))) public absoluteRewardByWallet;
mapping(address => mapping(address => mapping(uint256 => uint256))) public claimNonceByWalletCurrency;
mapping(address => FungibleBalanceLib.Balance) private stagedByWallet;
mapping(address => uint256) public nonceByWallet;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event RewardFractionalEvent(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds);
event RewardAbsoluteEvent(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds);
event DepriveFractionalEvent(address wallet);
event DepriveAbsoluteEvent(address wallet, address currencyCt, uint256 currencyId);
event ClaimAndTransferToBeneficiaryEvent(address from, Beneficiary beneficiary, string balanceType, int256 amount,
address currencyCt, uint256 currencyId, string standard);
event ClaimAndStageEvent(address from, int256 amount, address currencyCt, uint256 currencyId);
event WithdrawEvent(address from, int256 amount, address currencyCt, uint256 currencyId, string standard);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) Servable() public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Fallback function that deposits ethers
function() external payable {
receiveEthersTo(msg.sender, "");
}
/// @notice Receive ethers to
/// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory)
public
payable
{
int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value);
// Add to balance
deposited.add(amount, address(0), 0);
txHistory.addDeposit(amount, address(0), 0);
// Add currency to in-use list
inUseCurrencies.add(address(0), 0);
// Emit event
emit ReceiveEvent(wallet, amount, address(0), 0);
}
/// @notice Receive tokens
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokens(string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
receiveTokensTo(msg.sender, "", amount, currencyCt, currencyId, standard);
}
/// @notice Receive tokens to
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of token ("ERC20", "ERC721")
function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt,
uint256 currencyId, string memory standard)
public
{
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:145]");
// Execute transfer
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId
)
);
require(success, "Reception by controller failed [SecurityBond.sol:154]");
// Add to balance
deposited.add(amount, currencyCt, currencyId);
txHistory.addDeposit(amount, currencyCt, currencyId);
// Add currency to in-use list
inUseCurrencies.add(currencyCt, currencyId);
// Emit event
emit ReceiveEvent(wallet, amount, currencyCt, currencyId);
}
/// @notice Get the count of deposits
/// @return The count of deposits
function depositsCount()
public
view
returns (uint256)
{
return txHistory.depositsCount();
}
/// @notice Get the deposit at the given index
/// @return The deposit at the given index
function deposit(uint index)
public
view
returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId)
{
return txHistory.deposit(index);
}
/// @notice Get the deposited balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function depositedBalance(address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId);
}
/// @notice Get the fractional amount deposited balance of the given currency
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
/// @param fraction The fraction of sums that the wallet is rewarded
/// @return The fractional amount of deposited balance
function depositedFractionalBalance(address currencyCt, uint256 currencyId, uint256 fraction)
public
view
returns (int256)
{
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fraction))
.div(ConstantsLib.PARTS_PER());
}
/// @notice Get the staged balance of the given currency
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The deposited balance
function stagedBalance(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return stagedByWallet[wallet].get(currencyCt, currencyId);
}
/// @notice Get the count of currencies recorded
/// @return The number of currencies
function inUseCurrenciesCount()
public
view
returns (uint256)
{
return inUseCurrencies.count();
}
/// @notice Get the currencies recorded with indices in the given range
/// @param low The lower currency index
/// @param up The upper currency index
/// @return The currencies of the given index range
function inUseCurrenciesByIndices(uint256 low, uint256 up)
public
view
returns (MonetaryTypesLib.Currency[] memory)
{
return inUseCurrencies.getByIndices(low, up);
}
/// @notice Reward the given wallet the given fraction of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param fraction The fraction of sums that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardFractional(address wallet, uint256 fraction, uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = fraction.clampMax(uint256(ConstantsLib.PARTS_PER()));
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardFractionalEvent(wallet, fraction, unlockTimeoutInSeconds);
}
/// @notice Reward the given wallet the given amount of funds, where the reward is locked
/// for the given number of seconds
/// @param wallet The concerned wallet
/// @param amount The amount that the wallet is rewarded
/// @param currencyCt The contract address of the currency that the wallet is rewarded
/// @param currencyId The ID of the currency that the wallet is rewarded
/// @param unlockTimeoutInSeconds The number of seconds for which the reward is locked and should
/// be claimed
function rewardAbsolute(address wallet, int256 amount, address currencyCt, uint256 currencyId,
uint256 unlockTimeoutInSeconds)
public
notNullAddress(wallet)
onlyEnabledServiceAction(REWARD_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = amount;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = block.timestamp.add(unlockTimeoutInSeconds);
// Emit event
emit RewardAbsoluteEvent(wallet, amount, currencyCt, currencyId, unlockTimeoutInSeconds);
}
/// @notice Deprive the given wallet of any fractional reward it has been granted
/// @param wallet The concerned wallet
function depriveFractional(address wallet)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update fractional reward
fractionalRewardByWallet[wallet].fraction = 0;
fractionalRewardByWallet[wallet].nonce = ++nonceByWallet[wallet];
fractionalRewardByWallet[wallet].unlockTime = 0;
// Emit event
emit DepriveFractionalEvent(wallet);
}
/// @notice Deprive the given wallet of any absolute reward it has been granted in the given currency
/// @param wallet The concerned wallet
/// @param currencyCt The contract address of the currency that the wallet is deprived
/// @param currencyId The ID of the currency that the wallet is deprived
function depriveAbsolute(address wallet, address currencyCt, uint256 currencyId)
public
onlyEnabledServiceAction(DEPRIVE_ACTION)
{
// Update absolute reward
absoluteRewardByWallet[wallet][currencyCt][currencyId].amount = 0;
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce = ++nonceByWallet[wallet];
absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime = 0;
// Emit event
emit DepriveAbsoluteEvent(wallet, currencyCt, currencyId);
}
/// @notice Claim reward and transfer to beneficiary
/// @param beneficiary The concerned beneficiary
/// @param balanceType The target balance type
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function claimAndTransferToBeneficiary(Beneficiary beneficiary, string memory balanceType, address currencyCt,
uint256 currencyId, string memory standard)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
beneficiary.receiveEthersTo.value(uint256(claimedAmount))(msg.sender, balanceType);
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getApproveSignature(), address(beneficiary), uint256(claimedAmount), currencyCt, currencyId
)
);
require(success, "Approval by controller failed [SecurityBond.sol:350]");
beneficiary.receiveTokensTo(msg.sender, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
// Emit event
emit ClaimAndTransferToBeneficiaryEvent(msg.sender, beneficiary, balanceType, claimedAmount, currencyCt, currencyId, standard);
}
/// @notice Claim reward and stage for later withdrawal
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function claimAndStage(address currencyCt, uint256 currencyId)
public
{
// Claim reward
int256 claimedAmount = _claim(msg.sender, currencyCt, currencyId);
// Subtract from deposited balance
deposited.sub(claimedAmount, currencyCt, currencyId);
// Add to staged balance
stagedByWallet[msg.sender].add(claimedAmount, currencyCt, currencyId);
// Emit event
emit ClaimAndStageEvent(msg.sender, claimedAmount, currencyCt, currencyId);
}
/// @notice Withdraw from staged balance of msg.sender
/// @param amount The concerned amount
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721")
function withdraw(int256 amount, address currencyCt, uint256 currencyId, string memory standard)
public
{
// Require that amount is strictly positive
require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [SecurityBond.sol:386]");
// Clamp amount to the max given by staged balance
amount = amount.clampMax(stagedByWallet[msg.sender].get(currencyCt, currencyId));
// Subtract to per-wallet staged balance
stagedByWallet[msg.sender].sub(amount, currencyCt, currencyId);
// Execute transfer
if (address(0) == currencyCt && 0 == currencyId)
msg.sender.transfer(uint256(amount));
else {
TransferController controller = transferController(currencyCt, standard);
(bool success,) = address(controller).delegatecall(
abi.encodeWithSelector(
controller.getDispatchSignature(), address(this), msg.sender, uint256(amount), currencyCt, currencyId
)
);
require(success, "Dispatch by controller failed [SecurityBond.sol:405]");
}
// Emit event
emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId, standard);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _claim(address wallet, address currencyCt, uint256 currencyId)
private
returns (int256)
{
// Combine claim nonce from rewards
uint256 claimNonce = fractionalRewardByWallet[wallet].nonce.clampMin(
absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce
);
// Require that new claim nonce is strictly greater than current stored one
require(
claimNonce > claimNonceByWalletCurrency[wallet][currencyCt][currencyId],
"Claim nonce not strictly greater than previously claimed nonce [SecurityBond.sol:425]"
);
// Combine claim amount from rewards
int256 claimAmount = _fractionalRewardAmountByWalletCurrency(wallet, currencyCt, currencyId).add(
_absoluteRewardAmountByWalletCurrency(wallet, currencyCt, currencyId)
).clampMax(
deposited.get(currencyCt, currencyId)
);
// Require that claim amount is strictly positive, indicating that there is an amount to claim
require(claimAmount.isNonZeroPositiveInt256(), "Claim amount not strictly positive [SecurityBond.sol:438]");
// Update stored claim nonce for wallet and currency
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] = claimNonce;
return claimAmount;
}
function _fractionalRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < fractionalRewardByWallet[wallet].nonce &&
block.timestamp >= fractionalRewardByWallet[wallet].unlockTime
)
return deposited.get(currencyCt, currencyId)
.mul(SafeMathIntLib.toInt256(fractionalRewardByWallet[wallet].fraction))
.div(ConstantsLib.PARTS_PER());
else
return 0;
}
function _absoluteRewardAmountByWalletCurrency(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256)
{
if (
claimNonceByWalletCurrency[wallet][currencyCt][currencyId] < absoluteRewardByWallet[wallet][currencyCt][currencyId].nonce &&
block.timestamp >= absoluteRewardByWallet[wallet][currencyCt][currencyId].unlockTime
)
return absoluteRewardByWallet[wallet][currencyCt][currencyId].amount.clampMax(
deposited.get(currencyCt, currencyId)
);
else
return 0;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SecurityBondable
* @notice An ownable that has a security bond property
*/
contract SecurityBondable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SecurityBond public securityBond;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetSecurityBondEvent(SecurityBond oldSecurityBond, SecurityBond newSecurityBond);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the security bond contract
/// @param newSecurityBond The (address of) SecurityBond contract instance
function setSecurityBond(SecurityBond newSecurityBond)
public
onlyDeployer
notNullAddress(address(newSecurityBond))
notSameAddresses(address(newSecurityBond), address(securityBond))
{
//set new security bond
SecurityBond oldSecurityBond = securityBond;
securityBond = newSecurityBond;
// Emit event
emit SetSecurityBondEvent(oldSecurityBond, newSecurityBond);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier securityBondInitialized() {
require(address(securityBond) != address(0), "Security bond not initialized [SecurityBondable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallenge
* @notice Where fraud challenge results are found
*/
contract FraudChallenge is Ownable, Servable {
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public ADD_SEIZED_WALLET_ACTION = "add_seized_wallet";
string constant public ADD_DOUBLE_SPENDER_WALLET_ACTION = "add_double_spender_wallet";
string constant public ADD_FRAUDULENT_ORDER_ACTION = "add_fraudulent_order";
string constant public ADD_FRAUDULENT_TRADE_ACTION = "add_fraudulent_trade";
string constant public ADD_FRAUDULENT_PAYMENT_ACTION = "add_fraudulent_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
address[] public doubleSpenderWallets;
mapping(address => bool) public doubleSpenderByWallet;
bytes32[] public fraudulentOrderHashes;
mapping(bytes32 => bool) public fraudulentByOrderHash;
bytes32[] public fraudulentTradeHashes;
mapping(bytes32 => bool) public fraudulentByTradeHash;
bytes32[] public fraudulentPaymentHashes;
mapping(bytes32 => bool) public fraudulentByPaymentHash;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event AddDoubleSpenderWalletEvent(address wallet);
event AddFraudulentOrderHashEvent(bytes32 hash);
event AddFraudulentTradeHashEvent(bytes32 hash);
event AddFraudulentPaymentHashEvent(bytes32 hash);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the double spender status of given wallet
/// @param wallet The wallet address for which to check double spender status
/// @return true if wallet is double spender, false otherwise
function isDoubleSpenderWallet(address wallet)
public
view
returns (bool)
{
return doubleSpenderByWallet[wallet];
}
/// @notice Get the number of wallets tagged as double spenders
/// @return Number of double spender wallets
function doubleSpenderWalletsCount()
public
view
returns (uint256)
{
return doubleSpenderWallets.length;
}
/// @notice Add given wallets to store of double spender wallets if not already present
/// @param wallet The first wallet to add
function addDoubleSpenderWallet(address wallet)
public
onlyEnabledServiceAction(ADD_DOUBLE_SPENDER_WALLET_ACTION) {
if (!doubleSpenderByWallet[wallet]) {
doubleSpenderWallets.push(wallet);
doubleSpenderByWallet[wallet] = true;
emit AddDoubleSpenderWalletEvent(wallet);
}
}
/// @notice Get the number of fraudulent order hashes
function fraudulentOrderHashesCount()
public
view
returns (uint256)
{
return fraudulentOrderHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent order
/// @param hash The hash to be tested
function isFraudulentOrderHash(bytes32 hash)
public
view returns (bool) {
return fraudulentByOrderHash[hash];
}
/// @notice Add given order hash to store of fraudulent order hashes if not already present
function addFraudulentOrderHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_ORDER_ACTION)
{
if (!fraudulentByOrderHash[hash]) {
fraudulentByOrderHash[hash] = true;
fraudulentOrderHashes.push(hash);
emit AddFraudulentOrderHashEvent(hash);
}
}
/// @notice Get the number of fraudulent trade hashes
function fraudulentTradeHashesCount()
public
view
returns (uint256)
{
return fraudulentTradeHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent trade
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent trade, else false
function isFraudulentTradeHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByTradeHash[hash];
}
/// @notice Add given trade hash to store of fraudulent trade hashes if not already present
function addFraudulentTradeHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_TRADE_ACTION)
{
if (!fraudulentByTradeHash[hash]) {
fraudulentByTradeHash[hash] = true;
fraudulentTradeHashes.push(hash);
emit AddFraudulentTradeHashEvent(hash);
}
}
/// @notice Get the number of fraudulent payment hashes
function fraudulentPaymentHashesCount()
public
view
returns (uint256)
{
return fraudulentPaymentHashes.length;
}
/// @notice Get the state about whether the given hash equals the hash of a fraudulent payment
/// @param hash The hash to be tested
/// @return true if hash is the one of a fraudulent payment, else null
function isFraudulentPaymentHash(bytes32 hash)
public
view
returns (bool)
{
return fraudulentByPaymentHash[hash];
}
/// @notice Add given payment hash to store of fraudulent payment hashes if not already present
function addFraudulentPaymentHash(bytes32 hash)
public
onlyEnabledServiceAction(ADD_FRAUDULENT_PAYMENT_ACTION)
{
if (!fraudulentByPaymentHash[hash]) {
fraudulentByPaymentHash[hash] = true;
fraudulentPaymentHashes.push(hash);
emit AddFraudulentPaymentHashEvent(hash);
}
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title FraudChallengable
* @notice An ownable that has a fraud challenge property
*/
contract FraudChallengable is Ownable {
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
FraudChallenge public fraudChallenge;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetFraudChallengeEvent(FraudChallenge oldFraudChallenge, FraudChallenge newFraudChallenge);
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the fraud challenge contract
/// @param newFraudChallenge The (address of) FraudChallenge contract instance
function setFraudChallenge(FraudChallenge newFraudChallenge)
public
onlyDeployer
notNullAddress(address(newFraudChallenge))
notSameAddresses(address(newFraudChallenge), address(fraudChallenge))
{
// Set new fraud challenge
FraudChallenge oldFraudChallenge = fraudChallenge;
fraudChallenge = newFraudChallenge;
// Emit event
emit SetFraudChallengeEvent(oldFraudChallenge, newFraudChallenge);
}
//
// Modifiers
// -----------------------------------------------------------------------------------------------------------------
modifier fraudChallengeInitialized() {
require(address(fraudChallenge) != address(0), "Fraud challenge not initialized [FraudChallengable.sol:52]");
_;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title SettlementChallengeTypesLib
* @dev Types for settlement challenges
*/
library SettlementChallengeTypesLib {
//
// Structures
// -----------------------------------------------------------------------------------------------------------------
enum Status {Qualified, Disqualified}
struct Proposal {
address wallet;
uint256 nonce;
uint256 referenceBlockNumber;
uint256 definitionBlockNumber;
uint256 expirationTime;
// Status
Status status;
// Amounts
Amounts amounts;
// Currency
MonetaryTypesLib.Currency currency;
// Info on challenged driip
Driip challenged;
// True is equivalent to reward coming from wallet's balance
bool walletInitiated;
// True if proposal has been terminated
bool terminated;
// Disqualification
Disqualification disqualification;
}
struct Amounts {
// Cumulative (relative) transfer info
int256 cumulativeTransfer;
// Stage info
int256 stage;
// Balances after amounts have been staged
int256 targetBalance;
}
struct Driip {
// Kind ("payment", "trade", ...)
string kind;
// Hash (of operator)
bytes32 hash;
}
struct Disqualification {
// Challenger
address challenger;
uint256 nonce;
uint256 blockNumber;
// Info on candidate driip
Driip candidate;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeState
* @notice Where null settlements challenge state is managed
*/
contract NullSettlementChallengeState is Ownable, Servable, Configurable, BalanceTrackable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated);
event DisqualifyProposalEvent(address challengedWallet, uint256 challangedNonce, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
address challengerWallet, uint256 candidateNonce, bytes32 candidateHash, string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if initiated by the concerned challenged wallet
function initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:143]");
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [NullSettlementChallengeState.sol:197]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No settlement found for wallet and currency [NullSettlementChallengeState.sol:226]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.stage,
proposals[index - 1].amounts.targetBalance, currency, proposals[index - 1].referenceBlockNumber,
proposals[index - 1].walletInitiated, challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:269]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:284]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal challenge nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:298]");
return proposals[index - 1].nonce;
}
/// @notice Get the settlement proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:312]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the settlement proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:326]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the settlement proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:340]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the settlement proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:354]");
return proposals[index - 1].status;
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:368]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:382]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the settlement proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:396]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the settlement proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:410]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the settlement proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:424]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the settlement proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:438]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the settlement proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:452]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the settlement proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [NullSettlementChallengeState.sol:466]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated)
private
{
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [NullSettlementChallengeState.sol:478]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [NullSettlementChallengeState.sol:479]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
}
function _removeProposal(uint256 index)
private
returns (bool)
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
function _activeBalanceLogEntry(address wallet, address currencyCt, uint256 currencyId)
private
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log record of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.depositedBalanceType(), currencyCt, currencyId
);
(int256 settledAmount, uint256 settledBlockNumber) = balanceTracker.lastFungibleRecord(
wallet, balanceTracker.settledBalanceType(), currencyCt, currencyId
);
// Set amount as the sum of deposited and settled
amount = depositedAmount.add(settledAmount);
// Set block number as the latest of deposited and settled
blockNumber = depositedBlockNumber > settledBlockNumber ? depositedBlockNumber : settledBlockNumber;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
library BalanceTrackerLib {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
function fungibleActiveRecordByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 _blockNumber)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.depositedBalanceType(), currency.ct, currency.id, _blockNumber
);
(int256 settledAmount, uint256 settledBlockNumber) = self.fungibleRecordByBlockNumber(
wallet, self.settledBalanceType(), currency.ct, currency.id, _blockNumber
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
function fungibleActiveBalanceAmountByBlockNumber(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 blockNumber)
internal
view
returns (int256)
{
(int256 amount,) = fungibleActiveRecordByBlockNumber(self, wallet, currency, blockNumber);
return amount;
}
function fungibleActiveDeltaBalanceAmountByBlockNumbers(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency, uint256 fromBlockNumber, uint256 toBlockNumber)
internal
view
returns (int256)
{
return fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, toBlockNumber) -
fungibleActiveBalanceAmountByBlockNumber(self, wallet, currency, fromBlockNumber);
}
// TODO Rename?
function fungibleActiveRecord(BalanceTracker self, address wallet,
MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256 amount, uint256 blockNumber)
{
// Get last log records of deposited and settled balances
(int256 depositedAmount, uint256 depositedBlockNumber) = self.lastFungibleRecord(
wallet, self.depositedBalanceType(), currency.ct, currency.id
);
(int256 settledAmount, uint256 settledBlockNumber) = self.lastFungibleRecord(
wallet, self.settledBalanceType(), currency.ct, currency.id
);
// Return the sum of amounts and highest of block numbers
amount = depositedAmount.add(settledAmount);
blockNumber = depositedBlockNumber.clampMin(settledBlockNumber);
}
// TODO Rename?
function fungibleActiveBalanceAmount(BalanceTracker self, address wallet, MonetaryTypesLib.Currency memory currency)
internal
view
returns (int256)
{
return self.get(wallet, self.depositedBalanceType(), currency.ct, currency.id).add(
self.get(wallet, self.settledBalanceType(), currency.ct, currency.id)
);
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementDisputeByPayment
* @notice The where payment related disputes of null settlement challenge happens
*/
contract NullSettlementDisputeByPayment is Ownable, Configurable, Validatable, SecurityBondable, WalletLockable,
BalanceTrackable, FraudChallengable, Servable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public CHALLENGE_BY_PAYMENT_ACTION = "challenge_by_payment";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementChallengeState public nullSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event ChallengeByPaymentEvent(address wallet, uint256 nonce, PaymentTypesLib.Payment payment,
address challenger);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
/// @notice Set the settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState) public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Challenge the settlement by providing payment candidate
/// @dev This challenges the payment sender's side of things
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges
/// @param challenger The address of the challenger
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment, address challenger)
public
onlyEnabledServiceAction(CHALLENGE_BY_PAYMENT_ACTION)
onlySealedPayment(payment)
onlyPaymentSender(payment, wallet)
{
// Require that payment candidate is not labelled fraudulent
require(!fraudChallenge.isFraudulentPaymentHash(payment.seals.operator.hash), "Payment deemed fraudulent [NullSettlementDisputeByPayment.sol:86]");
// Require that proposal has been initiated
require(nullSettlementChallengeState.hasProposal(wallet, payment.currency), "No proposal found [NullSettlementDisputeByPayment.sol:89]");
// Require that proposal has not expired
require(!nullSettlementChallengeState.hasProposalExpired(wallet, payment.currency), "Proposal found expired [NullSettlementDisputeByPayment.sol:92]");
// Require that payment party's nonce is strictly greater than proposal's nonce and its current
// disqualification nonce
require(payment.sender.nonce > nullSettlementChallengeState.proposalNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal nonce [NullSettlementDisputeByPayment.sol:96]");
require(payment.sender.nonce > nullSettlementChallengeState.proposalDisqualificationNonce(
wallet, payment.currency
), "Payment nonce not strictly greater than proposal disqualification nonce [NullSettlementDisputeByPayment.sol:99]");
// Require overrun for this payment to be a valid challenge candidate
require(_overrun(wallet, payment), "No overrun found [NullSettlementDisputeByPayment.sol:104]");
// Reward challenger
_settleRewards(wallet, payment.sender.balances.current, payment.currency, challenger);
// Disqualify proposal, effectively overriding any previous disqualification
nullSettlementChallengeState.disqualifyProposal(
wallet, payment.currency, challenger, payment.blockNumber,
payment.sender.nonce, payment.seals.operator.hash, PaymentTypesLib.PAYMENT_KIND()
);
// Emit event
emit ChallengeByPaymentEvent(
wallet, nullSettlementChallengeState.proposalNonce(wallet, payment.currency), payment, challenger
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _overrun(address wallet, PaymentTypesLib.Payment memory payment)
private
view
returns (bool)
{
// Get the target balance amount from the proposal
int targetBalanceAmount = nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, payment.currency
);
// Get the change in active balance since the start of the challenge
int256 deltaBalanceSinceStart = balanceTracker.fungibleActiveBalanceAmount(
wallet, payment.currency
).sub(
balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency,
nullSettlementChallengeState.proposalReferenceBlockNumber(wallet, payment.currency)
)
);
// Get the cumulative transfer of the payment
int256 cumulativeTransfer = balanceTracker.fungibleActiveBalanceAmountByBlockNumber(
wallet, payment.currency, payment.blockNumber
).sub(payment.sender.balances.current);
return targetBalanceAmount.add(deltaBalanceSinceStart) < cumulativeTransfer;
}
// Lock wallet's balances or reward challenger by stake fraction
function _settleRewards(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
if (nullSettlementChallengeState.proposalWalletInitiated(wallet, currency))
_settleBalanceReward(wallet, walletAmount, currency, challenger);
else
_settleSecurityBondReward(wallet, walletAmount, currency, challenger);
}
function _settleBalanceReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Unlock wallet/currency for existing challenger if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
walletLocker.unlockFungibleByProxy(
wallet,
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Lock wallet for new challenger
walletLocker.lockFungibleByProxy(
wallet, challenger, walletAmount, currency.ct, currency.id, configuration.settlementChallengeTimeout()
);
}
// Settle the two-component reward from security bond.
// The first component is flat figure as obtained from Configuration
// The second component is progressive and calculated as
// min(walletAmount, fraction of SecurityBond's deposited balance)
// both amounts for the given currency
function _settleSecurityBondReward(address wallet, int256 walletAmount, MonetaryTypesLib.Currency memory currency,
address challenger)
private
{
// Deprive existing challenger of reward if previously locked
if (SettlementChallengeTypesLib.Status.Disqualified == nullSettlementChallengeState.proposalStatus(
wallet, currency
))
securityBond.depriveAbsolute(
nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, currency
),
currency.ct, currency.id
);
// Reward the flat component
MonetaryTypesLib.Figure memory flatReward = _flatReward();
securityBond.rewardAbsolute(
challenger, flatReward.amount, flatReward.currency.ct, flatReward.currency.id, 0
);
// Reward the progressive component
int256 progressiveRewardAmount = walletAmount.clampMax(
securityBond.depositedFractionalBalance(
currency.ct, currency.id, configuration.operatorSettlementStakeFraction()
)
);
securityBond.rewardAbsolute(
challenger, progressiveRewardAmount, currency.ct, currency.id, 0
);
}
function _flatReward()
private
view
returns (MonetaryTypesLib.Figure memory)
{
(int256 amount, address currencyCt, uint256 currencyId) = configuration.operatorSettlementStake();
return MonetaryTypesLib.Figure(amount, MonetaryTypesLib.Currency(currencyCt, currencyId));
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title DriipSettlementChallengeState
* @notice Where driip settlement challenge state is managed
*/
contract DriipSettlementChallengeState is Ownable, Servable, Configurable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
//
// Constants
// -----------------------------------------------------------------------------------------------------------------
string constant public INITIATE_PROPOSAL_ACTION = "initiate_proposal";
string constant public TERMINATE_PROPOSAL_ACTION = "terminate_proposal";
string constant public REMOVE_PROPOSAL_ACTION = "remove_proposal";
string constant public DISQUALIFY_PROPOSAL_ACTION = "disqualify_proposal";
string constant public QUALIFY_PROPOSAL_ACTION = "qualify_proposal";
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
SettlementChallengeTypesLib.Proposal[] public proposals;
mapping(address => mapping(address => mapping(uint256 => uint256))) public proposalIndexByWalletCurrency;
mapping(address => mapping(uint256 => mapping(address => mapping(uint256 => uint256)))) public proposalIndexByWalletNonceCurrency;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event InitiateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event TerminateProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event RemoveProposalEvent(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string challengedKind);
event DisqualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
event QualifyProposalEvent(address challengedWallet, uint256 challengedNonce, int256 cumulativeTransferAmount,
int256 stageAmount, int256 targetBalanceAmount, MonetaryTypesLib.Currency currency, uint256 blockNumber,
bool walletInitiated, address challengerWallet, uint256 candidateNonce, bytes32 candidateHash,
string candidateKind);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Get the number of proposals
/// @return The number of proposals
function proposalsCount()
public
view
returns (uint256)
{
return proposals.length;
}
/// @notice Initiate proposal
/// @param wallet The address of the concerned challenged wallet
/// @param nonce The wallet nonce
/// @param cumulativeTransferAmount The proposal cumulative transfer amount
/// @param stageAmount The proposal stage amount
/// @param targetBalanceAmount The proposal target balance amount
/// @param currency The concerned currency
/// @param blockNumber The proposal block number
/// @param walletInitiated True if reward from candidate balance
/// @param challengedHash The candidate driip hash
/// @param challengedKind The candidate driip kind
function initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 blockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
public
onlyEnabledServiceAction(INITIATE_PROPOSAL_ACTION)
{
// Initiate proposal
_initiateProposal(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount,
currency, blockNumber, walletInitiated, challengedHash, challengedKind
);
// Emit event
emit InitiateProposalEvent(
wallet, nonce, cumulativeTransferAmount, stageAmount, targetBalanceAmount, currency,
blockNumber, walletInitiated, challengedHash, challengedKind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Terminate a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param clearNonce Clear wallet-nonce-currency triplet entry
/// @param walletTerminated True if wallet terminated
function terminateProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool clearNonce,
bool walletTerminated)
public
onlyEnabledServiceAction(TERMINATE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to terminate
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:163]");
// Clear wallet-nonce-currency triplet entry, which enables reinitiation of proposal for that triplet
if (clearNonce)
proposalIndexByWalletNonceCurrency[wallet][proposals[index - 1].nonce][currency.ct][currency.id] = 0;
// Terminate proposal
proposals[index - 1].terminated = true;
// Emit event
emit TerminateProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Remove a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param walletTerminated True if wallet terminated
function removeProposal(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
public
onlyEnabledServiceAction(REMOVE_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Return gracefully if there is no proposal to remove
if (0 == index)
return;
// Require that role that initialized (wallet or operator) can only cancel its own proposal
require(walletTerminated == proposals[index - 1].walletInitiated, "Wallet initiation and termination mismatch [DriipSettlementChallengeState.sol:223]");
// Emit event
emit RemoveProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].challenged.hash, proposals[index - 1].challenged.kind
);
// Remove proposal
_removeProposal(index);
}
/// @notice Disqualify a proposal
/// @dev A call to this function will intentionally override previous disqualifications if existent
/// @param challengedWallet The address of the concerned challenged wallet
/// @param currency The concerned currency
/// @param challengerWallet The address of the concerned challenger wallet
/// @param blockNumber The disqualification block number
/// @param candidateNonce The candidate nonce
/// @param candidateHash The candidate hash
/// @param candidateKind The candidate kind
function disqualifyProposal(address challengedWallet, MonetaryTypesLib.Currency memory currency, address challengerWallet,
uint256 blockNumber, uint256 candidateNonce, bytes32 candidateHash, string memory candidateKind)
public
onlyEnabledServiceAction(DISQUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[challengedWallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:253]");
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Disqualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].disqualification.challenger = challengerWallet;
proposals[index - 1].disqualification.nonce = candidateNonce;
proposals[index - 1].disqualification.blockNumber = blockNumber;
proposals[index - 1].disqualification.candidate.hash = candidateHash;
proposals[index - 1].disqualification.candidate.kind = candidateKind;
// Emit event
emit DisqualifyProposalEvent(
challengedWallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance,
currency, proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
challengerWallet, candidateNonce, candidateHash, candidateKind
);
}
/// @notice (Re)Qualify a proposal
/// @param wallet The address of the concerned challenged wallet
/// @param currency The concerned currency
function qualifyProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
onlyEnabledServiceAction(QUALIFY_PROPOSAL_ACTION)
{
// Get the proposal index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:282]");
// Emit event
emit QualifyProposalEvent(
wallet, proposals[index - 1].nonce, proposals[index - 1].amounts.cumulativeTransfer,
proposals[index - 1].amounts.stage, proposals[index - 1].amounts.targetBalance, currency,
proposals[index - 1].referenceBlockNumber, proposals[index - 1].walletInitiated,
proposals[index - 1].disqualification.challenger,
proposals[index - 1].disqualification.nonce,
proposals[index - 1].disqualification.candidate.hash,
proposals[index - 1].disqualification.candidate.kind
);
// Update proposal
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
delete proposals[index - 1].disqualification;
}
/// @notice Gauge whether a driip settlement challenge for the given wallet-nonce-currency
/// triplet has been proposed and not later removed
/// @param wallet The address of the concerned wallet
/// @param nonce The wallet nonce
/// @param currency The concerned currency
/// @return true if driip settlement challenge has been, else false
function hasProposal(address wallet, uint256 nonce, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposal(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
return 0 != proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:340]");
return proposals[index - 1].terminated;
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
// 1-based index
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:355]");
return block.timestamp >= proposals[index - 1].expirationTime;
}
/// @notice Get the proposal nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal nonce
function proposalNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:369]");
return proposals[index - 1].nonce;
}
/// @notice Get the proposal reference block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal reference block number
function proposalReferenceBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:383]");
return proposals[index - 1].referenceBlockNumber;
}
/// @notice Get the proposal definition block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal definition block number
function proposalDefinitionBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:397]");
return proposals[index - 1].definitionBlockNumber;
}
/// @notice Get the proposal expiration time of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal expiration time
function proposalExpirationTime(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:411]");
return proposals[index - 1].expirationTime;
}
/// @notice Get the proposal status of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal status
function proposalStatus(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (SettlementChallengeTypesLib.Status)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:425]");
return proposals[index - 1].status;
}
/// @notice Get the proposal cumulative transfer amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal cumulative transfer amount
function proposalCumulativeTransferAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:439]");
return proposals[index - 1].amounts.cumulativeTransfer;
}
/// @notice Get the proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:453]");
return proposals[index - 1].amounts.stage;
}
/// @notice Get the proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (int256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:467]");
return proposals[index - 1].amounts.targetBalance;
}
/// @notice Get the proposal challenged hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged hash
function proposalChallengedHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:481]");
return proposals[index - 1].challenged.hash;
}
/// @notice Get the proposal challenged kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal challenged kind
function proposalChallengedKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:495]");
return proposals[index - 1].challenged.kind;
}
/// @notice Get the proposal balance reward of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal balance reward
function proposalWalletInitiated(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bool)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:509]");
return proposals[index - 1].walletInitiated;
}
/// @notice Get the proposal disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification challenger
function proposalDisqualificationChallenger(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (address)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:523]");
return proposals[index - 1].disqualification.challenger;
}
/// @notice Get the proposal disqualification nonce of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification nonce
function proposalDisqualificationNonce(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:537]");
return proposals[index - 1].disqualification.nonce;
}
/// @notice Get the proposal disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification block number
function proposalDisqualificationBlockNumber(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (uint256)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:551]");
return proposals[index - 1].disqualification.blockNumber;
}
/// @notice Get the proposal disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate hash
function proposalDisqualificationCandidateHash(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (bytes32)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:565]");
return proposals[index - 1].disqualification.candidate.hash;
}
/// @notice Get the proposal disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currency The concerned currency
/// @return The settlement proposal disqualification candidate kind
function proposalDisqualificationCandidateKind(address wallet, MonetaryTypesLib.Currency memory currency)
public
view
returns (string memory)
{
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
require(0 != index, "No proposal found for wallet and currency [DriipSettlementChallengeState.sol:579]");
return proposals[index - 1].disqualification.candidate.kind;
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _initiateProposal(address wallet, uint256 nonce, int256 cumulativeTransferAmount, int256 stageAmount,
int256 targetBalanceAmount, MonetaryTypesLib.Currency memory currency, uint256 referenceBlockNumber, bool walletInitiated,
bytes32 challengedHash, string memory challengedKind)
private
{
// Require that there is no other proposal on the given wallet-nonce-currency triplet
require(
0 == proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id],
"Existing proposal found for wallet, nonce and currency [DriipSettlementChallengeState.sol:592]"
);
// Require that stage and target balance amounts are positive
require(stageAmount.isPositiveInt256(), "Stage amount not positive [DriipSettlementChallengeState.sol:598]");
require(targetBalanceAmount.isPositiveInt256(), "Target balance amount not positive [DriipSettlementChallengeState.sol:599]");
uint256 index = proposalIndexByWalletCurrency[wallet][currency.ct][currency.id];
// Create proposal if needed
if (0 == index) {
index = ++(proposals.length);
proposalIndexByWalletCurrency[wallet][currency.ct][currency.id] = index;
}
// Populate proposal
proposals[index - 1].wallet = wallet;
proposals[index - 1].nonce = nonce;
proposals[index - 1].referenceBlockNumber = referenceBlockNumber;
proposals[index - 1].definitionBlockNumber = block.number;
proposals[index - 1].expirationTime = block.timestamp.add(configuration.settlementChallengeTimeout());
proposals[index - 1].status = SettlementChallengeTypesLib.Status.Qualified;
proposals[index - 1].currency = currency;
proposals[index - 1].amounts.cumulativeTransfer = cumulativeTransferAmount;
proposals[index - 1].amounts.stage = stageAmount;
proposals[index - 1].amounts.targetBalance = targetBalanceAmount;
proposals[index - 1].walletInitiated = walletInitiated;
proposals[index - 1].terminated = false;
proposals[index - 1].challenged.hash = challengedHash;
proposals[index - 1].challenged.kind = challengedKind;
// Update index of wallet-nonce-currency triplet
proposalIndexByWalletNonceCurrency[wallet][nonce][currency.ct][currency.id] = index;
}
function _removeProposal(uint256 index)
private
{
// Remove the proposal and clear references to it
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = 0;
if (index < proposals.length) {
proposals[index - 1] = proposals[proposals.length - 1];
proposalIndexByWalletCurrency[proposals[index - 1].wallet][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
proposalIndexByWalletNonceCurrency[proposals[index - 1].wallet][proposals[index - 1].nonce][proposals[index - 1].currency.ct][proposals[index - 1].currency.id] = index;
}
proposals.length--;
}
}
/*
* Hubii Nahmii
*
* Compliant with the Hubii Nahmii specification v0.12.
*
* Copyright (C) 2017-2018 Hubii AS
*/
/**
* @title NullSettlementChallengeByPayment
* @notice Where null settlements pertaining to payments are started and disputed
*/
contract NullSettlementChallengeByPayment is Ownable, ConfigurableOperational, BalanceTrackable, WalletLockable {
using SafeMathIntLib for int256;
using SafeMathUintLib for uint256;
using BalanceTrackerLib for BalanceTracker;
//
// Variables
// -----------------------------------------------------------------------------------------------------------------
NullSettlementDisputeByPayment public nullSettlementDisputeByPayment;
NullSettlementChallengeState public nullSettlementChallengeState;
DriipSettlementChallengeState public driipSettlementChallengeState;
//
// Events
// -----------------------------------------------------------------------------------------------------------------
event SetNullSettlementDisputeByPaymentEvent(NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment,
NullSettlementDisputeByPayment newNullSettlementDisputeByPayment);
event SetNullSettlementChallengeStateEvent(NullSettlementChallengeState oldNullSettlementChallengeState,
NullSettlementChallengeState newNullSettlementChallengeState);
event SetDriipSettlementChallengeStateEvent(DriipSettlementChallengeState oldDriipSettlementChallengeState,
DriipSettlementChallengeState newDriipSettlementChallengeState);
event StartChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId);
event StartChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint currencyId, address proxy);
event StopChallengeEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId);
event StopChallengeByProxyEvent(address wallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address proxy);
event ChallengeByPaymentEvent(address challengedWallet, uint256 nonce, int256 stageAmount, int256 targetBalanceAmount,
address currencyCt, uint256 currencyId, address challengerWallet);
//
// Constructor
// -----------------------------------------------------------------------------------------------------------------
constructor(address deployer) Ownable(deployer) public {
}
//
// Functions
// -----------------------------------------------------------------------------------------------------------------
/// @notice Set the settlement dispute contract
/// @param newNullSettlementDisputeByPayment The (address of) NullSettlementDisputeByPayment contract instance
function setNullSettlementDisputeByPayment(NullSettlementDisputeByPayment newNullSettlementDisputeByPayment)
public
onlyDeployer
notNullAddress(address(newNullSettlementDisputeByPayment))
{
NullSettlementDisputeByPayment oldNullSettlementDisputeByPayment = nullSettlementDisputeByPayment;
nullSettlementDisputeByPayment = newNullSettlementDisputeByPayment;
emit SetNullSettlementDisputeByPaymentEvent(oldNullSettlementDisputeByPayment, nullSettlementDisputeByPayment);
}
/// @notice Set the null settlement challenge state contract
/// @param newNullSettlementChallengeState The (address of) NullSettlementChallengeState contract instance
function setNullSettlementChallengeState(NullSettlementChallengeState newNullSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newNullSettlementChallengeState))
{
NullSettlementChallengeState oldNullSettlementChallengeState = nullSettlementChallengeState;
nullSettlementChallengeState = newNullSettlementChallengeState;
emit SetNullSettlementChallengeStateEvent(oldNullSettlementChallengeState, nullSettlementChallengeState);
}
/// @notice Set the driip settlement challenge state contract
/// @param newDriipSettlementChallengeState The (address of) DriipSettlementChallengeState contract instance
function setDriipSettlementChallengeState(DriipSettlementChallengeState newDriipSettlementChallengeState)
public
onlyDeployer
notNullAddress(address(newDriipSettlementChallengeState))
{
DriipSettlementChallengeState oldDriipSettlementChallengeState = driipSettlementChallengeState;
driipSettlementChallengeState = newDriipSettlementChallengeState;
emit SetDriipSettlementChallengeStateEvent(oldDriipSettlementChallengeState, driipSettlementChallengeState);
}
/// @notice Start settlement challenge
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallenge(int256 amount, address currencyCt, uint256 currencyId)
public
{
// Require that wallet is not locked
require(!walletLocker.isLocked(msg.sender), "Wallet found locked [NullSettlementChallengeByPayment.sol:116]");
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(msg.sender, amount, currency, true);
// Emit event
emit StartChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Start settlement challenge for the given wallet
/// @param wallet The address of the concerned wallet
/// @param amount The concerned amount to stage
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function startChallengeByProxy(address wallet, int256 amount, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Start challenge for wallet
_startChallenge(wallet, amount, currency, false);
// Emit event
emit StartChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
amount,
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Stop settlement challenge
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallenge(address currencyCt, uint256 currencyId)
public
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(msg.sender, currency, true);
// Emit event
emit StopChallengeEvent(
msg.sender,
nullSettlementChallengeState.proposalNonce(msg.sender, currency),
nullSettlementChallengeState.proposalStageAmount(msg.sender, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(msg.sender, currency),
currencyCt, currencyId
);
}
/// @notice Stop settlement challenge
/// @param wallet The concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
function stopChallengeByProxy(address wallet, address currencyCt, uint256 currencyId)
public
onlyOperator
{
// Define currency
MonetaryTypesLib.Currency memory currency = MonetaryTypesLib.Currency(currencyCt, currencyId);
// Stop challenge
_stopChallenge(wallet, currency, false);
// Emit event
emit StopChallengeByProxyEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, currency),
nullSettlementChallengeState.proposalStageAmount(wallet, currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, currency),
currencyCt, currencyId, msg.sender
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has been defined
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has been initiated, else false
function hasProposal(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposal(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has terminated
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has terminated, else false
function hasProposalTerminated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalTerminated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Gauge whether the proposal for the given wallet and currency has expired
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return true if proposal has expired, else false
function hasProposalExpired(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.hasProposalExpired(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge nonce of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge nonce
function proposalNonce(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalNonce(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal block number of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal block number
function proposalReferenceBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalReferenceBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal end time of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal end time
function proposalExpirationTime(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalExpirationTime(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the challenge status of the given wallet
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenge status
function proposalStatus(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (SettlementChallengeTypesLib.Status)
{
return nullSettlementChallengeState.proposalStatus(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal stage amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal stage amount
function proposalStageAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalStageAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the settlement proposal target balance amount of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The settlement proposal target balance amount
function proposalTargetBalanceAmount(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (int256)
{
return nullSettlementChallengeState.proposalTargetBalanceAmount(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the balance reward of the given wallet's settlement proposal
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The balance reward of the settlement proposal
function proposalWalletInitiated(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bool)
{
return nullSettlementChallengeState.proposalWalletInitiated(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification challenger of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The challenger of the settlement disqualification
function proposalDisqualificationChallenger(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (address)
{
return nullSettlementChallengeState.proposalDisqualificationChallenger(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification block number of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The block number of the settlement disqualification
function proposalDisqualificationBlockNumber(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (uint256)
{
return nullSettlementChallengeState.proposalDisqualificationBlockNumber(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate kind of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate kind of the settlement disqualification
function proposalDisqualificationCandidateKind(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (string memory)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateKind(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Get the disqualification candidate hash of the given wallet and currency
/// @param wallet The address of the concerned wallet
/// @param currencyCt The address of the concerned currency contract (address(0) == ETH)
/// @param currencyId The ID of the concerned currency (0 for ETH and ERC20)
/// @return The candidate hash of the settlement disqualification
function proposalDisqualificationCandidateHash(address wallet, address currencyCt, uint256 currencyId)
public
view
returns (bytes32)
{
return nullSettlementChallengeState.proposalDisqualificationCandidateHash(
wallet, MonetaryTypesLib.Currency(currencyCt, currencyId)
);
}
/// @notice Challenge the settlement by providing payment candidate
/// @param wallet The wallet whose settlement is being challenged
/// @param payment The payment candidate that challenges the null
function challengeByPayment(address wallet, PaymentTypesLib.Payment memory payment)
public
onlyOperationalModeNormal
{
// Challenge by payment
nullSettlementDisputeByPayment.challengeByPayment(wallet, payment, msg.sender);
// Emit event
emit ChallengeByPaymentEvent(
wallet,
nullSettlementChallengeState.proposalNonce(wallet, payment.currency),
nullSettlementChallengeState.proposalStageAmount(wallet, payment.currency),
nullSettlementChallengeState.proposalTargetBalanceAmount(wallet, payment.currency),
payment.currency.ct, payment.currency.id, msg.sender
);
}
//
// Private functions
// -----------------------------------------------------------------------------------------------------------------
function _startChallenge(address wallet, int256 stageAmount, MonetaryTypesLib.Currency memory currency,
bool walletInitiated)
private
{
// Require that current block number is beyond the earliest settlement challenge block number
require(
block.number >= configuration.earliestSettlementBlockNumber(),
"Current block number below earliest settlement block number [NullSettlementChallengeByPayment.sol:443]"
);
// Require that there is no ongoing overlapping null settlement challenge
require(
!nullSettlementChallengeState.hasProposal(wallet, currency) ||
nullSettlementChallengeState.hasProposalExpired(wallet, currency),
"Overlapping null settlement challenge proposal found [NullSettlementChallengeByPayment.sol:449]"
);
// Get the last logged active balance amount and block number, properties of overlapping DSC
// and the baseline nonce
(
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) = _externalProperties(
wallet, currency
);
// Initiate proposal, including assurance that there is no overlap with active proposal
// Target balance amount is calculated as current balance - DSC cumulativeTransferAmount - DSC stage amount - NSC stageAmount
nullSettlementChallengeState.initiateProposal(
wallet, nonce, stageAmount,
activeBalanceAmount.sub(
dscCumulativeTransferAmount.add(dscStageAmount).add(stageAmount)
),
currency,
activeBalanceBlockNumber, walletInitiated
);
}
function _stopChallenge(address wallet, MonetaryTypesLib.Currency memory currency, bool walletTerminated)
private
{
// Require that there is an unterminated driip settlement challenge proposal
require(nullSettlementChallengeState.hasProposal(wallet, currency), "No proposal found [NullSettlementChallengeByPayment.sol:481]");
require(!nullSettlementChallengeState.hasProposalTerminated(wallet, currency), "Proposal found terminated [NullSettlementChallengeByPayment.sol:482]");
// Terminate driip settlement challenge proposal
nullSettlementChallengeState.terminateProposal(
wallet, currency, walletTerminated
);
}
function _externalProperties(address wallet, MonetaryTypesLib.Currency memory currency)
private
view
returns (
int256 activeBalanceAmount, uint256 activeBalanceBlockNumber,
int256 dscCumulativeTransferAmount, int256 dscStageAmount,
uint256 nonce
) {
(activeBalanceAmount, activeBalanceBlockNumber) = balanceTracker.fungibleActiveRecord(
wallet, currency
);
if (driipSettlementChallengeState.hasProposal(wallet, currency)) {
if (!driipSettlementChallengeState.hasProposalTerminated(wallet, currency)) {
dscCumulativeTransferAmount = driipSettlementChallengeState.proposalCumulativeTransferAmount(wallet, currency);
dscStageAmount = driipSettlementChallengeState.proposalStageAmount(wallet, currency);
}
nonce = driipSettlementChallengeState.proposalNonce(wallet, currency);
}
if (nullSettlementChallengeState.hasProposal(wallet, currency))
nonce = nonce.clampMin(nullSettlementChallengeState.proposalNonce(wallet, currency));
}
}
|
Gauge whether the given wallet is locked wallet The address of the concerned wallet return true if wallet is locked, else false
|
function isLocked(address wallet)
public
view
returns (bool)
{
return 0 < walletFungibleLocks[wallet].length ||
0 < walletNonFungibleLocks[wallet].length;
}
| 12,574,548 |
./full_match/9001/0x985711e9540d40ea02532E710301874384e1b5D8/sources/contracts/XStarToken.sol
|
Set StarFarm contract address/
|
function setStarFarm(address _starFarmaddr) public onlyOwner{
StarFarm = _starFarmaddr;
}
| 11,535,010 |
pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;
contract create {
struct Valuationdata {
string Frame_number; //车架号
string Number_plate; //号码车牌
string Vehicle_type; //车辆类型
string Brand_number; //品牌型号
string car_displacement; //汽车排量(L)
string approval_passengers; //核定载客量
string Engine_number; //发动机编号
string Manufacture_date; //出厂日期
uint Evaluation; //评估价值
string Timestammp; //时间戳
}
struct Picture {
string photo1; //图片一(合格证)
string photo2; //图片二(左前45度)
string photo3; //图片三(左前门)
string photo4; //图片四(左后门)
string photo5; //图片五(右前门)
string photo6; //图片六(右后45度)
string photo7; //图片七(中控台)
string photo8; //图片八(车内顶)
}
struct Status {
uint Evaluation_value; //评估支付金额
string Evaluation_status; //每个评估单对应的评估状态(0:未评估,1:已评估,2:已申诉,3:申诉完成,4:已关闭)
address Assessor; //评估人
address Create; //创建人
}
struct Msg {
mapping(uint => Status) store_sta; //存储评估单状态
mapping(uint => Valuationdata) store_msg; //存储评估单详情
mapping(uint => Picture) store_pho; //存储评估单图片
}
Msg order; //评估单(包含评估单状态、评估单详情和评估单图片结构体)
uint ordernumber = 1; //评估单唯一全局编号(与js共同拼接成最终评估号)
mapping(address => uint[]) record; //记录每个用户下评估单编号
mapping(address => uint) createappeal; //创建者申诉数量
mapping(address => uint) workappeal; //评估者申诉数量
/**
* guobin
* 创建评估单信息
*/
function _addvaluation(
string memory Frame_number,
string memory Number_plate,
string memory Vehicle_type,
string memory Brand_number,
string memory car_displacement,
string memory approval_passengers,
string memory Engine_number,
string memory Manufacture_date,
uint Evaluation,
string memory Timestammp,
uint valuationindex //评估单编号(唯一)
) internal {
Valuationdata memory valuationdata = Valuationdata(Frame_number,Number_plate,Vehicle_type,Brand_number,car_displacement,approval_passengers,Engine_number,Manufacture_date,Evaluation,Timestammp);
order.store_msg[valuationindex] = valuationdata; //将评估信息存入对应评估单
order.store_sta[valuationindex].Evaluation_status = "0"; //将评估状态初始化为0,即未评估
order.store_sta[valuationindex].Create = msg.sender; //存储评估单的创建人(默认当前用户创建)
record[msg.sender].push(valuationindex); //将当前评估单编号(由js传递)存入对应用户地址
ordernumber ++; //原始评估单编号自增
}
/**
* guobin
* 创建评估单图片信息
*/
function _addphoto(
string memory photo1,
string memory photo2,
string memory photo3,
string memory photo4,
string memory photo5,
string memory photo6,
string memory photo7,
string memory photo8,
uint valuationindex
) internal {
Picture memory picture = Picture(photo1,photo2,photo3,photo4,photo5,photo6,photo7,photo8);
order.store_pho[valuationindex] = picture;
}
/**
* guobin
* 返回原始评估单编号
*/
function _backordernumber() view internal returns (uint) {
return ordernumber;
}
/**
* guobin
* 返回当前用户的所有评估单编号
*/
function _backvaluation() view internal returns (uint[]) {
return record[msg.sender];
}
/**
* guobin
* 存储评估单对应的评估师
*/
function _setassessor(uint index,address _to) internal {
order.store_sta[index].Assessor = _to;
}
/**
* guobin
* 存储指定评估单付费价格
*/
function _setvalue(uint index,uint amount) internal {
order.store_sta[index].Evaluation_value = amount;
}
/**
* guobin
* 存储指定评估单评估状态
*/
function _setstate(uint index,string condition) internal {
order.store_sta[index].Evaluation_status = condition;
}
/**
* guobin
* 存储指定评估单申诉记录
*/
function _setappeal(address Create,address Work) internal {
createappeal[Create] += 1;
workappeal[Work] += 1;
}
/**
* guobin
* 获取评估单对应的创建人
*/
function _getcreator(uint index) view internal returns(address) {
return order.store_sta[index].Create;
}
/**
* guobin
* 获取评估单对应的评估师
*/
function _getassessor(uint index) view internal returns(address) {
return order.store_sta[index].Assessor;
}
/**
* guobin
* 获取指定评估单付费价格
*/
function _getvalue(uint index) view internal returns(uint) {
return order.store_sta[index].Evaluation_value;
}
/**
* guobin
* 获取指定评估单评估状态
*/
function _getstate(uint index) view internal returns(string) {
return order.store_sta[index].Evaluation_status;
}
/**
* guobin
* 获取指定评估单价格
*/
function _displayvalue(uint index) view internal returns (uint) {
return order.store_msg[index].Evaluation; //评估价值
}
/**
* guobin
* 获取指定用户申诉数量
*/
function _displaycreate() view internal returns (uint) {
return createappeal[msg.sender]; //某用户申诉数量
}
/**
* guobin
* 获取指定评估师申诉数量
*/
function _displaywork() view internal returns (uint) {
return workappeal[msg.sender]; //某评估师被申诉数量
}
/**
* guobin
* 获取指定评估单评估信息
*/
function _displayinfo(uint index,uint num) view internal returns (string) {
if(num == 1) {
return order.store_msg[index].Frame_number; //车架号
}
else if(num == 2) {
return order.store_msg[index].Number_plate; //号码车牌
}
else if(num == 3) {
return order.store_msg[index].Vehicle_type; //车辆类型
}
else if(num == 4) {
return order.store_msg[index].Brand_number; //品牌型号
}
else if(num == 5) {
return order.store_msg[index].car_displacement; //汽车排量(L)
}
else if(num == 6) {
return order.store_msg[index].approval_passengers; //核定载客量
}
else if(num == 7) {
return order.store_msg[index].Engine_number; //发动机号码
}
else if(num == 8) {
return order.store_msg[index].Manufacture_date; //出厂日期
}
else if(num == 10) {
return order.store_msg[index].Timestammp; //时间戳
}
else if(num == 11) {
return order.store_sta[index].Evaluation_status; //评估状态
}
else if(num == 12) {
return order.store_pho[index].photo1; //图片一(合格证)
}
else if(num == 13) {
return order.store_pho[index].photo2; //图片二(左前45度)
}
else if(num == 14) {
return order.store_pho[index].photo3; //图片三(左前门)
}
else if(num == 15) {
return order.store_pho[index].photo4; //图片四(左后门)
}
else if(num == 16) {
return order.store_pho[index].photo5; //图片五(右前门)
}
else if(num == 17) {
return order.store_pho[index].photo6; //图片六(右后45度)
}
else if(num == 18) {
return order.store_pho[index].photo7; //图片七(中控台)
}
else if(num == 19) {
return order.store_pho[index].photo8; //图片八(车内顶)
}
}
}
|
guobin 获取指定评估师申诉数量/
|
function _displaywork() view internal returns (uint) {
}
| 972,791 |
./full_match/80001/0xd849F7eDa1e9831d5F7d16105cAD9a43dD85d1dF/sources/src/contracts/ContractOpenablePack721.sol
|
/// Returns the underlying contents of a pack.
|
Getter functions
function getPackContents(uint256 _packId)
public
view
returns (uint256[] memory contents)
{
return packTokens[_packId].values();
}
| 855,816 |
/**
*Submitted for verification at Etherscan.io on 2021-03-12
*/
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// File: contracts/upgradeability/EternalStorage.sol
pragma solidity 0.7.5;
/**
* @title EternalStorage
* @dev This contract holds all the necessary state variables to carry out the storage of any contract.
*/
contract EternalStorage {
mapping(bytes32 => uint256) internal uintStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
}
// File: contracts/upgradeable_contracts/Initializable.sol
pragma solidity 0.7.5;
contract Initializable is EternalStorage {
bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized"))
function setInitialize() internal {
boolStorage[INITIALIZED] = true;
}
function isInitialized() public view returns (bool) {
return boolStorage[INITIALIZED];
}
}
// File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol
pragma solidity 0.7.5;
interface IUpgradeabilityOwnerStorage {
function upgradeabilityOwner() external view returns (address);
}
// File: contracts/upgradeable_contracts/Upgradeable.sol
pragma solidity 0.7.5;
contract Upgradeable {
// Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract
modifier onlyIfUpgradeabilityOwner() {
require(msg.sender == IUpgradeabilityOwnerStorage(address(this)).upgradeabilityOwner());
_;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
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);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.7.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/upgradeable_contracts/Sacrifice.sol
pragma solidity 0.7.5;
contract Sacrifice {
constructor(address payable _recipient) payable {
selfdestruct(_recipient);
}
}
// File: contracts/libraries/AddressHelper.sol
pragma solidity 0.7.5;
/**
* @title AddressHelper
* @dev Helper methods for Address type.
*/
library AddressHelper {
/**
* @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract
* @param _receiver address that will receive the native tokens
* @param _value the amount of native tokens to send
*/
function safeSendValue(address payable _receiver, uint256 _value) internal {
if (!(_receiver).send(_value)) {
new Sacrifice{ value: _value }(_receiver);
}
}
}
// File: contracts/upgradeable_contracts/Claimable.sol
pragma solidity 0.7.5;
/**
* @title Claimable
* @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations.
*/
contract Claimable {
using SafeERC20 for IERC20;
/**
* Throws if a given address is equal to address(0)
*/
modifier validAddress(address _to) {
require(_to != address(0));
_;
}
/**
* @dev Withdraws the erc20 tokens or native coins from this contract.
* Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()).
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimValues(address _token, address _to) internal validAddress(_to) {
if (_token == address(0)) {
claimNativeCoins(_to);
} else {
claimErc20Tokens(_token, _to);
}
}
/**
* @dev Internal function for withdrawing all native coins from the contract.
* @param _to address of the coins receiver.
*/
function claimNativeCoins(address _to) internal {
uint256 value = address(this).balance;
AddressHelper.safeSendValue(payable(_to), value);
}
/**
* @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract.
* @param _token address of the claimed ERC20 token.
* @param _to address of the tokens receiver.
*/
function claimErc20Tokens(address _token, address _to) internal {
IERC20 token = IERC20(_token);
uint256 balance = token.balanceOf(address(this));
token.safeTransfer(_to, balance);
}
}
// File: contracts/upgradeable_contracts/components/bridged/BridgedTokensRegistry.sol
pragma solidity 0.7.5;
/**
* @title BridgedTokensRegistry
* @dev Functionality for keeping track of registered bridged token pairs.
*/
contract BridgedTokensRegistry is EternalStorage {
event NewTokenRegistered(address indexed nativeToken, address indexed bridgedToken);
/**
* @dev Retrieves address of the bridged token contract associated with a specific native token contract on the other side.
* @param _nativeToken address of the native token contract on the other side.
* @return address of the deployed bridged token contract.
*/
function bridgedTokenAddress(address _nativeToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))];
}
/**
* @dev Retrieves address of the native token contract associated with a specific bridged token contract.
* @param _bridgedToken address of the created bridged token contract on this side.
* @return address of the native token contract on the other side of the bridge.
*/
function nativeTokenAddress(address _bridgedToken) public view returns (address) {
return addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))];
}
/**
* @dev Internal function for updating a pair of addresses for the bridged token.
* @param _nativeToken address of the native token contract on the other side.
* @param _bridgedToken address of the created bridged token contract on this side.
*/
function _setTokenAddressPair(address _nativeToken, address _bridgedToken) internal {
addressStorage[keccak256(abi.encodePacked("homeTokenAddress", _nativeToken))] = _bridgedToken;
addressStorage[keccak256(abi.encodePacked("foreignTokenAddress", _bridgedToken))] = _nativeToken;
emit NewTokenRegistered(_nativeToken, _bridgedToken);
}
}
// File: contracts/upgradeable_contracts/components/native/NativeTokensRegistry.sol
pragma solidity 0.7.5;
/**
* @title NativeTokensRegistry
* @dev Functionality for keeping track of registered native tokens.
*/
contract NativeTokensRegistry is EternalStorage {
/**
* @dev Checks if for a given native token, the deployment of its bridged alternative was already acknowledged.
* @param _token address of native token contract.
* @return true, if bridged token was already deployed.
*/
function isBridgedTokenDeployAcknowledged(address _token) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))];
}
/**
* @dev Acknowledges the deployment of bridged token contract on the other side.
* @param _token address of native token contract.
*/
function _ackBridgedTokenDeploy(address _token) internal {
if (!boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))]) {
boolStorage[keccak256(abi.encodePacked("ackDeploy", _token))] = true;
}
}
}
// File: contracts/upgradeable_contracts/components/native/MediatorBalanceStorage.sol
pragma solidity 0.7.5;
/**
* @title MediatorBalanceStorage
* @dev Functionality for storing expected mediator balance for native tokens.
*/
contract MediatorBalanceStorage is EternalStorage {
/**
* @dev Tells the expected token balance of the contract.
* @param _token address of token contract.
* @return the current tracked token balance of the contract.
*/
function mediatorBalance(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))];
}
/**
* @dev Updates expected token balance of the contract.
* @param _token address of token contract.
* @param _balance the new token balance of the contract.
*/
function _setMediatorBalance(address _token, uint256 _balance) internal {
uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))] = _balance;
}
}
// File: contracts/interfaces/IERC677.sol
pragma solidity 0.7.5;
interface IERC677 is IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value, bytes data);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// File: contracts/libraries/Bytes.sol
pragma solidity 0.7.5;
/**
* @title Bytes
* @dev Helper methods to transform bytes to other solidity types.
*/
library Bytes {
/**
* @dev Truncate bytes array if its size is more than 20 bytes.
* NOTE: This function does not perform any checks on the received parameter.
* Make sure that the _bytes argument has a correct length, not less than 20 bytes.
* A case when _bytes has length less than 20 will lead to the undefined behaviour,
* since assembly will read data from memory that is not related to the _bytes argument.
* @param _bytes to be converted to address type
* @return addr address included in the firsts 20 bytes of the bytes array in parameter.
*/
function bytesToAddress(bytes memory _bytes) internal pure returns (address addr) {
assembly {
addr := mload(add(_bytes, 20))
}
}
}
// File: contracts/upgradeable_contracts/ReentrancyGuard.sol
pragma solidity 0.7.5;
contract ReentrancyGuard {
function lock() internal view returns (bool res) {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
res := sload(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92) // keccak256(abi.encodePacked("lock"))
}
}
function setLock(bool _lock) internal {
assembly {
// Even though this is not the same as boolStorage[keccak256(abi.encodePacked("lock"))],
// since solidity mapping introduces another level of addressing, such slot change is safe
// for temporary variables which are cleared at the end of the call execution.
sstore(0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92, _lock) // keccak256(abi.encodePacked("lock"))
}
}
}
// File: contracts/upgradeable_contracts/Ownable.sol
pragma solidity 0.7.5;
/**
* @title Ownable
* @dev This contract has an owner address providing basic authorization control
*/
contract Ownable is EternalStorage {
bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner()
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event OwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_onlyOwner();
_;
}
/**
* @dev Internal function for reducing onlyOwner modifier bytecode overhead.
*/
function _onlyOwner() internal view {
require(msg.sender == owner());
}
/**
* @dev Throws if called through proxy by any account other than contract itself or an upgradeability owner.
*/
modifier onlyRelevantSender() {
(bool isProxy, bytes memory returnData) = address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER));
require(
!isProxy || // covers usage without calling through storage proxy
(returnData.length == 32 && msg.sender == abi.decode(returnData, (address))) || // covers usage through regular proxy calls
msg.sender == address(this) // covers calls through upgradeAndCall proxy method
);
_;
}
bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner"))
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function owner() public view returns (address) {
return addressStorage[OWNER];
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner the address to transfer ownership to.
*/
function transferOwnership(address newOwner) external onlyOwner {
_setOwner(newOwner);
}
/**
* @dev Sets a new owner address
*/
function _setOwner(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(owner(), newOwner);
addressStorage[OWNER] = newOwner;
}
}
// File: contracts/interfaces/IAMB.sol
pragma solidity 0.7.5;
interface IAMB {
event UserRequestForAffirmation(bytes32 indexed messageId, bytes encodedData);
event UserRequestForSignature(bytes32 indexed messageId, bytes encodedData);
event AffirmationCompleted(
address indexed sender,
address indexed executor,
bytes32 indexed messageId,
bool status
);
event RelayedMessage(address indexed sender, address indexed executor, bytes32 indexed messageId, bool status);
function messageSender() external view returns (address);
function maxGasPerTx() external view returns (uint256);
function transactionHash() external view returns (bytes32);
function messageId() external view returns (bytes32);
function messageSourceChainId() external view returns (bytes32);
function messageCallStatus(bytes32 _messageId) external view returns (bool);
function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32);
function failedMessageReceiver(bytes32 _messageId) external view returns (address);
function failedMessageSender(bytes32 _messageId) external view returns (address);
function requireToPassMessage(
address _contract,
bytes calldata _data,
uint256 _gas
) external returns (bytes32);
function requireToConfirmMessage(
address _contract,
bytes calldata _data,
uint256 _gas
) external returns (bytes32);
function sourceChainId() external view returns (uint256);
function destinationChainId() external view returns (uint256);
}
// File: contracts/upgradeable_contracts/BasicAMBMediator.sol
pragma solidity 0.7.5;
/**
* @title BasicAMBMediator
* @dev Basic storage and methods needed by mediators to interact with AMB bridge.
*/
abstract contract BasicAMBMediator is Ownable {
bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract"))
bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract"))
/**
* @dev Throws if caller on the other side is not an associated mediator.
*/
modifier onlyMediator {
_onlyMediator();
_;
}
/**
* @dev Internal function for reducing onlyMediator modifier bytecode overhead.
*/
function _onlyMediator() internal view {
IAMB bridge = bridgeContract();
require(msg.sender == address(bridge));
require(bridge.messageSender() == mediatorContractOnOtherSide());
}
/**
* @dev Sets the AMB bridge contract address. Only the owner can call this method.
* @param _bridgeContract the address of the bridge contract.
*/
function setBridgeContract(address _bridgeContract) external onlyOwner {
_setBridgeContract(_bridgeContract);
}
/**
* @dev Sets the mediator contract address from the other network. Only the owner can call this method.
* @param _mediatorContract the address of the mediator contract.
*/
function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner {
_setMediatorContractOnOtherSide(_mediatorContract);
}
/**
* @dev Get the AMB interface for the bridge contract address
* @return AMB interface for the bridge contract address
*/
function bridgeContract() public view returns (IAMB) {
return IAMB(addressStorage[BRIDGE_CONTRACT]);
}
/**
* @dev Tells the mediator contract address from the other network.
* @return the address of the mediator contract.
*/
function mediatorContractOnOtherSide() public view virtual returns (address) {
return addressStorage[MEDIATOR_CONTRACT];
}
/**
* @dev Stores a valid AMB bridge contract address.
* @param _bridgeContract the address of the bridge contract.
*/
function _setBridgeContract(address _bridgeContract) internal {
require(Address.isContract(_bridgeContract));
addressStorage[BRIDGE_CONTRACT] = _bridgeContract;
}
/**
* @dev Stores the mediator contract address from the other network.
* @param _mediatorContract the address of the mediator contract.
*/
function _setMediatorContractOnOtherSide(address _mediatorContract) internal {
addressStorage[MEDIATOR_CONTRACT] = _mediatorContract;
}
/**
* @dev Tells the id of the message originated on the other network.
* @return the id of the message originated on the other network.
*/
function messageId() internal view returns (bytes32) {
return bridgeContract().messageId();
}
/**
* @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network.
* @return the maximum gas limit value.
*/
function maxGasPerTx() internal view returns (uint256) {
return bridgeContract().maxGasPerTx();
}
function _passMessage(bytes memory _data, bool _useOracleLane) internal virtual returns (bytes32);
function _chooseRequestGasLimit(bytes memory _data) internal view virtual returns (uint256);
}
// File: contracts/upgradeable_contracts/components/common/TokensRelayer.sol
pragma solidity 0.7.5;
/**
* @title TokensRelayer
* @dev Functionality for bridging multiple tokens to the other side of the bridge.
*/
abstract contract TokensRelayer is BasicAMBMediator, ReentrancyGuard {
using SafeERC20 for IERC677;
/**
* @dev ERC677 transfer callback function.
* @param _from address of tokens sender.
* @param _value amount of transferred tokens.
* @param _data additional transfer data, can be used for passing alternative receiver address.
*/
function onTokenTransfer(
address _from,
uint256 _value,
bytes calldata _data
) external returns (bool) {
if (!lock()) {
bytes memory data = new bytes(0);
address receiver = _from;
if (_data.length >= 20) {
assembly {
receiver := calldataload(120)
}
require(receiver != address(0));
require(receiver != mediatorContractOnOtherSide());
if (_data.length > 20) {
assembly {
data := mload(0x40)
let size := sub(calldataload(100), 20)
mstore(data, size)
calldatacopy(add(data, 32), 152, size)
mstore(0x40, add(add(data, 32), size))
}
}
}
bridgeSpecificActionsOnTokenTransfer(msg.sender, _from, receiver, _value, data);
}
return true;
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(
IERC677 token,
address _receiver,
uint256 _value
) external {
_relayTokens(token, _receiver, _value, new bytes(0));
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _value amount of tokens to be transferred to the other network.
*/
function relayTokens(IERC677 token, uint256 _value) external {
_relayTokens(token, msg.sender, _value, new bytes(0));
}
/**
* @dev Initiate the bridge operation for some amount of tokens from msg.sender.
* The user should first call Approve method of the ERC677 token.
* @param token bridged token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
* @param _data additional transfer data to be used on the other side.
*/
function relayTokensAndCall(
IERC677 token,
address _receiver,
uint256 _value,
bytes memory _data
) external {
_relayTokens(token, _receiver, _value, _data);
}
/**
* @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract
* and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network.
* The user should first call Approve method of the ERC677 token.
* @param token bridge token contract address.
* @param _receiver address that will receive the native tokens on the other network.
* @param _value amount of tokens to be transferred to the other network.
* @param _data additional transfer data to be used on the other side.
*/
function _relayTokens(
IERC677 token,
address _receiver,
uint256 _value,
bytes memory _data
) internal {
// This lock is to prevent calling passMessage twice if a ERC677 token is used.
// When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract
// which will call passMessage.
require(!lock());
setLock(true);
token.safeTransferFrom(msg.sender, address(this), _value);
setLock(false);
bridgeSpecificActionsOnTokenTransfer(address(token), msg.sender, _receiver, _value, _data);
}
function bridgeSpecificActionsOnTokenTransfer(
address _token,
address _from,
address _receiver,
uint256 _value,
bytes memory _data
) internal virtual;
}
// File: contracts/upgradeable_contracts/VersionableBridge.sol
pragma solidity 0.7.5;
interface VersionableBridge {
function getBridgeInterfacesVersion()
external
pure
returns (
uint64 major,
uint64 minor,
uint64 patch
);
function getBridgeMode() external pure returns (bytes4);
}
// File: contracts/upgradeable_contracts/components/common/OmnibridgeInfo.sol
pragma solidity 0.7.5;
/**
* @title OmnibridgeInfo
* @dev Functionality for versioning Omnibridge mediator.
*/
contract OmnibridgeInfo is VersionableBridge {
event TokensBridgingInitiated(
address indexed token,
address indexed sender,
uint256 value,
bytes32 indexed messageId
);
event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId);
/**
* @dev Tells the bridge interface version that this contract supports.
* @return major value of the version
* @return minor value of the version
* @return patch value of the version
*/
function getBridgeInterfacesVersion()
external
pure
override
returns (
uint64 major,
uint64 minor,
uint64 patch
)
{
return (2, 1, 0);
}
/**
* @dev Tells the bridge mode that this contract supports.
* @return _data 4 bytes representing the bridge mode
*/
function getBridgeMode() external pure override returns (bytes4 _data) {
return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb")))
}
}
// File: contracts/upgradeable_contracts/components/common/TokensBridgeLimits.sol
pragma solidity 0.7.5;
/**
* @title TokensBridgeLimits
* @dev Functionality for keeping track of bridgin limits for multiple tokens.
*/
contract TokensBridgeLimits is EternalStorage, Ownable {
using SafeMath for uint256;
// token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens
event DailyLimitChanged(address indexed token, uint256 newLimit);
event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit);
/**
* @dev Checks if specified token was already bridged at least once.
* @param _token address of the token contract.
* @return true, if token address is address(0) or token was already bridged.
*/
function isTokenRegistered(address _token) public view returns (bool) {
return minPerTx(_token) > 0;
}
/**
* @dev Retrieves the total spent amount for particular token during specific day.
* @param _token address of the token contract.
* @param _day day number for which spent amount if requested.
* @return amount of tokens sent through the bridge to the other side.
*/
function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))];
}
/**
* @dev Retrieves the total executed amount for particular token during specific day.
* @param _token address of the token contract.
* @param _day day number for which spent amount if requested.
* @return amount of tokens received from the bridge from the other side.
*/
function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))];
}
/**
* @dev Retrieves current daily limit for a particular token contract.
* @param _token address of the token contract.
* @return daily limit on tokens that can be sent through the bridge per day.
*/
function dailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))];
}
/**
* @dev Retrieves current execution daily limit for a particular token contract.
* @param _token address of the token contract.
* @return daily limit on tokens that can be received from the bridge on the other side per day.
*/
function executionDailyLimit(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))];
}
/**
* @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return maximum amount on tokens that can be sent through the bridge in one transfer.
*/
function maxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))];
}
/**
* @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return maximum amount on tokens that can received from the bridge on the other side in one transaction.
*/
function executionMaxPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))];
}
/**
* @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract.
* @param _token address of the token contract.
* @return minimum amount on tokens that can be sent through the bridge in one transfer.
*/
function minPerTx(address _token) public view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))];
}
/**
* @dev Checks that bridged amount of tokens conforms to the configured limits.
* @param _token address of the token contract.
* @param _amount amount of bridge tokens.
* @return true, if specified amount can be bridged.
*/
function withinLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount);
return
dailyLimit(address(0)) > 0 &&
dailyLimit(_token) >= nextLimit &&
_amount <= maxPerTx(_token) &&
_amount >= minPerTx(_token);
}
/**
* @dev Checks that bridged amount of tokens conforms to the configured execution limits.
* @param _token address of the token contract.
* @param _amount amount of bridge tokens.
* @return true, if specified amount can be processed and executed.
*/
function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) {
uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount);
return
executionDailyLimit(address(0)) > 0 &&
executionDailyLimit(_token) >= nextLimit &&
_amount <= executionMaxPerTx(_token);
}
/**
* @dev Returns current day number.
* @return day number.
*/
function getCurrentDay() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return block.timestamp / 1 days;
}
/**
* @dev Updates daily limit for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the efault limit.
* @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx.
* 0 value is also allowed, will stop the bridge operations in outgoing direction.
*/
function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit;
emit DailyLimitChanged(_token, _dailyLimit);
}
/**
* @dev Updates execution daily limit for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx.
* 0 value is also allowed, will stop the bridge operations in incoming direction.
*/
function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner {
require(isTokenRegistered(_token));
require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0);
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit;
emit ExecutionDailyLimitChanged(_token, _dailyLimit);
}
/**
* @dev Updates execution maximum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit.
* 0 value is also allowed, will stop the bridge operations in incoming direction.
*/
function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx;
}
/**
* @dev Updates maximum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx.
* 0 value is also allowed, will stop the bridge operations in outgoing direction.
*/
function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token)));
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx;
}
/**
* @dev Updates minimum per transaction for the particular token. Only owner can call this method.
* @param _token address of the token contract, or address(0) for configuring the default limit.
* @param _minPerTx minimum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit.
*/
function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner {
require(isTokenRegistered(_token));
require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token));
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx;
}
/**
* @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters.
* @param _token address of the token contract, or address(0) for the default limit.
* @return minimum of maxPerTx parameter and remaining daily quota.
*/
function maxAvailablePerTx(address _token) public view returns (uint256) {
uint256 _maxPerTx = maxPerTx(_token);
uint256 _dailyLimit = dailyLimit(_token);
uint256 _spent = totalSpentPerDay(_token, getCurrentDay());
uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0;
return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily;
}
/**
* @dev Internal function for adding spent amount for some token.
* @param _token address of the token contract.
* @param _day day number, when tokens are processed.
* @param _value amount of bridge tokens.
*/
function addTotalSpentPerDay(
address _token,
uint256 _day,
uint256 _value
) internal {
uintStorage[keccak256(abi.encodePacked("totalSpentPerDay", _token, _day))] = totalSpentPerDay(_token, _day).add(
_value
);
}
/**
* @dev Internal function for adding executed amount for some token.
* @param _token address of the token contract.
* @param _day day number, when tokens are processed.
* @param _value amount of bridge tokens.
*/
function addTotalExecutedPerDay(
address _token,
uint256 _day,
uint256 _value
) internal {
uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay(
_token,
_day
)
.add(_value);
}
/**
* @dev Internal function for initializing limits for some token.
* @param _token address of the token contract.
* @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ].
*/
function _setLimits(address _token, uint256[3] memory _limits) internal {
require(
_limits[2] > 0 && // minPerTx > 0
_limits[1] > _limits[2] && // maxPerTx > minPerTx
_limits[0] > _limits[1] // dailyLimit > maxPerTx
);
uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1];
uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2];
emit DailyLimitChanged(_token, _limits[0]);
}
/**
* @dev Internal function for initializing execution limits for some token.
* @param _token address of the token contract.
* @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ].
*/
function _setExecutionLimits(address _token, uint256[2] memory _limits) internal {
require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit
uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0];
uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1];
emit ExecutionDailyLimitChanged(_token, _limits[0]);
}
/**
* @dev Internal function for initializing limits for some token relative to its decimals parameter.
* @param _token address of the token contract.
* @param _decimals token decimals parameter.
*/
function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal {
uint256 factor;
if (_decimals < 18) {
factor = 10**(18 - _decimals);
uint256 _minPerTx = minPerTx(address(0)).div(factor);
uint256 _maxPerTx = maxPerTx(address(0)).div(factor);
uint256 _dailyLimit = dailyLimit(address(0)).div(factor);
uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor);
uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor);
// such situation can happen when calculated limits relative to the token decimals are too low
// e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed.
// in this case, limits are raised to the default values
if (_minPerTx == 0) {
// Numbers 1, 100, 10000 are chosen in a semi-random way,
// so that any token with small decimals can still be bridged in some amounts.
// It is possible to override limits for the particular token later if needed.
_minPerTx = 1;
if (_maxPerTx <= _minPerTx) {
_maxPerTx = 100;
_executionMaxPerTx = 100;
if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) {
_dailyLimit = 10000;
_executionDailyLimit = 10000;
}
}
}
_setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]);
_setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]);
} else {
factor = 10**(_decimals - 18);
_setLimits(
_token,
[dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)]
);
_setExecutionLimits(
_token,
[executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)]
);
}
}
}
// File: contracts/upgradeable_contracts/components/common/BridgeOperationsStorage.sol
pragma solidity 0.7.5;
/**
* @title BridgeOperationsStorage
* @dev Functionality for storing processed bridged operations.
*/
abstract contract BridgeOperationsStorage is EternalStorage {
/**
* @dev Stores the bridged token of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _token bridged token address.
*/
function setMessageToken(bytes32 _messageId, address _token) internal {
addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token;
}
/**
* @dev Tells the bridged token address of a message sent to the AMB bridge.
* @return address of a token contract.
*/
function messageToken(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))];
}
/**
* @dev Stores the value of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _value amount of tokens bridged.
*/
function setMessageValue(bytes32 _messageId, uint256 _value) internal {
uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value;
}
/**
* @dev Tells the amount of tokens of a message sent to the AMB bridge.
* @return value representing amount of tokens.
*/
function messageValue(bytes32 _messageId) internal view returns (uint256) {
return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))];
}
/**
* @dev Stores the receiver of a message sent to the AMB bridge.
* @param _messageId of the message sent to the bridge.
* @param _recipient receiver of the tokens bridged.
*/
function setMessageRecipient(bytes32 _messageId, address _recipient) internal {
addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient;
}
/**
* @dev Tells the receiver of a message sent to the AMB bridge.
* @return address of the receiver.
*/
function messageRecipient(bytes32 _messageId) internal view returns (address) {
return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))];
}
}
// File: contracts/upgradeable_contracts/components/common/FailedMessagesProcessor.sol
pragma solidity 0.7.5;
/**
* @title FailedMessagesProcessor
* @dev Functionality for fixing failed bridging operations.
*/
abstract contract FailedMessagesProcessor is BasicAMBMediator, BridgeOperationsStorage {
event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value);
/**
* @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to
* fix/roll back the transferred assets on the other network.
* @param _messageId id of the message which execution failed.
*/
function requestFailedMessageFix(bytes32 _messageId) external {
require(!bridgeContract().messageCallStatus(_messageId));
require(bridgeContract().failedMessageReceiver(_messageId) == address(this));
require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide());
bytes4 methodSelector = this.fixFailedMessage.selector;
bytes memory data = abi.encodeWithSelector(methodSelector, _messageId);
_passMessage(data, true);
}
/**
* @dev Handles the request to fix transferred assets which bridged message execution failed on the other network.
* It uses the information stored by passMessage method when the assets were initially transferred
* @param _messageId id of the message which execution failed on the other network.
*/
function fixFailedMessage(bytes32 _messageId) public onlyMediator {
require(!messageFixed(_messageId));
address token = messageToken(_messageId);
address recipient = messageRecipient(_messageId);
uint256 value = messageValue(_messageId);
setMessageFixed(_messageId);
executeActionOnFixedTokens(token, recipient, value);
emit FailedMessageFixed(_messageId, token, recipient, value);
}
/**
* @dev Tells if a message sent to the AMB bridge has been fixed.
* @return bool indicating the status of the message.
*/
function messageFixed(bytes32 _messageId) public view returns (bool) {
return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))];
}
/**
* @dev Sets that the message sent to the AMB bridge has been fixed.
* @param _messageId of the message sent to the bridge.
*/
function setMessageFixed(bytes32 _messageId) internal {
boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true;
}
function executeActionOnFixedTokens(
address _token,
address _recipient,
uint256 _value
) internal virtual;
}
// File: contracts/upgradeability/Proxy.sol
pragma solidity 0.7.5;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
abstract contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() public view virtual returns (address);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback() external payable {
// solhint-disable-previous-line no-complex-fallback
address _impl = implementation();
require(_impl != address(0));
assembly {
/*
0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40)
loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty
memory. It's needed because we're going to write the return data of delegatecall to the
free memory slot.
*/
let ptr := mload(0x40)
/*
`calldatacopy` is copy calldatasize bytes from calldata
First argument is the destination to which data is copied(ptr)
Second argument specifies the start position of the copied data.
Since calldata is sort of its own unique location in memory,
0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata.
That's always going to be the zeroth byte of the function selector.
Third argument, calldatasize, specifies how much data will be copied.
calldata is naturally calldatasize bytes long (same thing as msg.data.length)
*/
calldatacopy(ptr, 0, calldatasize())
/*
delegatecall params explained:
gas: the amount of gas to provide for the call. `gas` is an Opcode that gives
us the amount of gas still available to execution
_impl: address of the contract to delegate to
ptr: to pass copied data
calldatasize: loads the size of `bytes memory data`, same as msg.data.length
0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic,
these are set to 0, 0 so the output data will not be written to memory. The output
data will be read using `returndatasize` and `returdatacopy` instead.
result: This will be 0 if the call fails and 1 if it succeeds
*/
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
/*
*/
/*
ptr current points to the value stored at 0x40,
because we assigned it like ptr := mload(0x40).
Because we use 0x40 as a free memory pointer,
we want to make sure that the next time we want to allocate memory,
we aren't overwriting anything important.
So, by adding ptr and returndatasize,
we get a memory location beyond the end of the data we will be copying to ptr.
We place this in at 0x40, and any reads from 0x40 will now read from free memory
*/
mstore(0x40, add(ptr, returndatasize()))
/*
`returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the
slot it will copy to, 0 means copy from the beginning of the return data, and size is
the amount of data to copy.
`returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall
*/
returndatacopy(ptr, 0, returndatasize())
/*
if `result` is 0, revert.
if `result` is 1, return `size` amount of data from `ptr`. This is the data that was
copied to `ptr` from the delegatecall return data
*/
switch result
case 0 {
revert(ptr, returndatasize())
}
default {
return(ptr, returndatasize())
}
}
}
}
// File: contracts/upgradeable_contracts/modules/factory/TokenProxy.sol
pragma solidity 0.7.5;
interface IPermittableTokenVersion {
function version() external pure returns (string memory);
}
/**
* @title TokenProxy
* @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract.
*/
contract TokenProxy is Proxy {
// storage layout is copied from PermittableToken.sol
string internal name;
string internal symbol;
uint8 internal decimals;
mapping(address => uint256) internal balances;
uint256 internal totalSupply;
mapping(address => mapping(address => uint256)) internal allowed;
address internal owner;
bool internal mintingFinished;
address internal bridgeContractAddr;
// string public constant version = "1";
// solhint-disable-next-line var-name-mixedcase
bytes32 internal DOMAIN_SEPARATOR;
// bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb;
mapping(address => uint256) internal nonces;
mapping(address => mapping(address => uint256)) internal expirations;
/**
* @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage.
* @param _tokenImage address of the token image used for mirroring all functions.
* @param _name token name.
* @param _symbol token symbol.
* @param _decimals token decimals.
* @param _chainId chain id for current network.
* @param _owner address of the owner for this contract.
*/
constructor(
address _tokenImage,
string memory _name,
string memory _symbol,
uint8 _decimals,
uint256 _chainId,
address _owner
) {
string memory version = IPermittableTokenVersion(_tokenImage).version();
assembly {
// EIP 1967
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _tokenImage)
}
name = _name;
symbol = _symbol;
decimals = _decimals;
owner = _owner; // _owner == HomeOmnibridge/ForeignOmnibridge mediator
bridgeContractAddr = _owner;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(_name)),
keccak256(bytes(version)),
_chainId,
address(this)
)
);
}
/**
* @dev Retrieves the implementation contract address, mirrored token image.
* @return impl token image address.
*/
function implementation() public view override returns (address impl) {
assembly {
impl := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
}
}
// File: contracts/upgradeable_contracts/modules/OwnableModule.sol
pragma solidity 0.7.5;
/**
* @title OwnableModule
* @dev Common functionality for multi-token extension non-upgradeable module.
*/
contract OwnableModule {
address public owner;
/**
* @dev Initializes this contract.
* @param _owner address of the owner that is allowed to perform additional actions on the particular module.
*/
constructor(address _owner) {
owner = _owner;
}
/**
* @dev Throws if sender is not the owner of this contract.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Changes the owner of this contract.
* @param _newOwner address of the new owner.
*/
function transferOwnership(address _newOwner) external onlyOwner {
owner = _newOwner;
}
}
// File: contracts/upgradeable_contracts/modules/factory/TokenFactory.sol
pragma solidity 0.7.5;
/**
* @title TokenFactory
* @dev Factory contract for deployment of new TokenProxy contracts.
*/
contract TokenFactory is OwnableModule {
address public tokenImage;
/**
* @dev Initializes this contract
* @param _owner of this factory contract.
* @param _tokenImage address of the token image contract that should be used for creation of new tokens.
*/
constructor(address _owner, address _tokenImage) OwnableModule(_owner) {
tokenImage = _tokenImage;
}
/**
* @dev Updates the address of the used token image contract.
* Only owner can call this method.
* @param _tokenImage address of the new token image used for further deployments.
*/
function setTokenImage(address _tokenImage) external onlyOwner {
require(Address.isContract(_tokenImage));
tokenImage = _tokenImage;
}
/**
* @dev Deploys a new TokenProxy contract, using saved token image contract as a template.
* @param _name deployed token name.
* @param _symbol deployed token symbol.
* @param _decimals deployed token decimals.
* @param _chainId chain id of the current environment.
* @return address of a newly created contract.
*/
function deploy(
string calldata _name,
string calldata _symbol,
uint8 _decimals,
uint256 _chainId
) external returns (address) {
return address(new TokenProxy(tokenImage, _name, _symbol, _decimals, _chainId, msg.sender));
}
}
// File: contracts/upgradeable_contracts/modules/factory/TokenFactoryConnector.sol
pragma solidity 0.7.5;
/**
* @title TokenFactoryConnector
* @dev Connectivity functionality for working with TokenFactory contract.
*/
contract TokenFactoryConnector is Ownable {
bytes32 internal constant TOKEN_FACTORY_CONTRACT =
0x269c5905f777ee6391c7a361d17039a7d62f52ba9fffeb98c5ade342705731a3; // keccak256(abi.encodePacked("tokenFactoryContract"))
/**
* @dev Updates an address of the used TokenFactory contract used for creating new tokens.
* @param _tokenFactory address of TokenFactory contract.
*/
function setTokenFactory(address _tokenFactory) external onlyOwner {
_setTokenFactory(_tokenFactory);
}
/**
* @dev Retrieves an address of the token factory contract.
* @return address of the TokenFactory contract.
*/
function tokenFactory() public view returns (TokenFactory) {
return TokenFactory(addressStorage[TOKEN_FACTORY_CONTRACT]);
}
/**
* @dev Internal function for updating an address of the token factory contract.
* @param _tokenFactory address of the deployed TokenFactory contract.
*/
function _setTokenFactory(address _tokenFactory) internal {
require(Address.isContract(_tokenFactory));
addressStorage[TOKEN_FACTORY_CONTRACT] = _tokenFactory;
}
}
// File: contracts/interfaces/IBurnableMintableERC677Token.sol
pragma solidity 0.7.5;
interface IBurnableMintableERC677Token is IERC677 {
function mint(address _to, uint256 _amount) external returns (bool);
function burn(uint256 _value) external;
function claimTokens(address _token, address _to) external;
}
// File: contracts/interfaces/IERC20Metadata.sol
pragma solidity 0.7.5;
interface IERC20Metadata {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/interfaces/IERC20Receiver.sol
pragma solidity 0.7.5;
interface IERC20Receiver {
function onTokenBridged(
address token,
uint256 value,
bytes calldata data
) external;
}
// File: contracts/libraries/TokenReader.sol
pragma solidity 0.7.5;
// solhint-disable
interface ITokenDetails {
function name() external view;
function NAME() external view;
function symbol() external view;
function SYMBOL() external view;
function decimals() external view;
function DECIMALS() external view;
}
// solhint-enable
/**
* @title TokenReader
* @dev Helper methods for reading name/symbol/decimals parameters from ERC20 token contracts.
*/
library TokenReader {
/**
* @dev Reads the name property of the provided token.
* Either name() or NAME() method is used.
* Both, string and bytes32 types are supported.
* @param _token address of the token contract.
* @return token name as a string or an empty string if none of the methods succeeded.
*/
function readName(address _token) internal view returns (string memory) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.name.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.NAME.selector));
if (!status) {
return "";
}
}
return _convertToString(data);
}
/**
* @dev Reads the symbol property of the provided token.
* Either symbol() or SYMBOL() method is used.
* Both, string and bytes32 types are supported.
* @param _token address of the token contract.
* @return token symbol as a string or an empty string if none of the methods succeeded.
*/
function readSymbol(address _token) internal view returns (string memory) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.symbol.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.SYMBOL.selector));
if (!status) {
return "";
}
}
return _convertToString(data);
}
/**
* @dev Reads the decimals property of the provided token.
* Either decimals() or DECIMALS() method is used.
* @param _token address of the token contract.
* @return token decimals or 0 if none of the methods succeeded.
*/
function readDecimals(address _token) internal view returns (uint256) {
(bool status, bytes memory data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.decimals.selector));
if (!status) {
(status, data) = _token.staticcall(abi.encodeWithSelector(ITokenDetails.DECIMALS.selector));
if (!status) {
return 0;
}
}
return abi.decode(data, (uint256));
}
/**
* @dev Internal function for converting returned value of name()/symbol() from bytes32/string to string.
* @param returnData data returned by the token contract.
* @return string with value obtained from returnData.
*/
function _convertToString(bytes memory returnData) private pure returns (string memory) {
if (returnData.length > 32) {
return abi.decode(returnData, (string));
} else if (returnData.length == 32) {
bytes32 data = abi.decode(returnData, (bytes32));
string memory res = new string(32);
assembly {
let len := 0
mstore(add(res, 32), data) // save value in result string
// solhint-disable
for { } gt(data, 0) { len := add(len, 1) } { // until string is empty
data := shl(8, data) // shift left by one symbol
}
// solhint-enable
mstore(res, len) // save result string length
}
return res;
} else {
return "";
}
}
}
// File: contracts/upgradeable_contracts/BasicOmnibridge.sol
pragma solidity 0.7.5;
/**
* @title BasicOmnibridge
* @dev Common functionality for multi-token mediator intended to work on top of AMB bridge.
*/
abstract contract BasicOmnibridge is
Initializable,
Upgradeable,
Claimable,
OmnibridgeInfo,
TokensRelayer,
FailedMessagesProcessor,
BridgedTokensRegistry,
NativeTokensRegistry,
MediatorBalanceStorage,
TokenFactoryConnector,
TokensBridgeLimits
{
using SafeERC20 for IERC677;
using SafeMath for uint256;
/**
* @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract.
* Checks that the value is inside the execution limits and invokes the Mint or Unlock accordingly.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function deployAndHandleBridgedTokens(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
address _recipient,
uint256 _value
) external onlyMediator {
address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals);
_handleTokens(bridgedToken, false, _recipient, _value);
}
/**
* @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract.
* Uses transferAndCall for bridging tokens.
* Checks that the value is inside the execution limits and invokes the Mint accordingly.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
* @param _data additional data passed from the other chain.
*/
function deployAndHandleBridgedTokensAndCall(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals,
address _recipient,
uint256 _value,
bytes calldata _data
) external onlyMediator {
address bridgedToken = _getBridgedTokenOrDeploy(_token, _name, _symbol, _decimals);
_handleTokens(bridgedToken, false, _recipient, _value);
_receiverCallback(_recipient, bridgedToken, _value, _data);
}
/**
* @dev Handles the bridged tokens for the already registered token pair.
* Checks that the value is inside the execution limits and invokes the Mint accordingly.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function handleBridgedTokens(
address _token,
address _recipient,
uint256 _value
) external onlyMediator {
address token = bridgedTokenAddress(_token);
require(isTokenRegistered(token));
_handleTokens(token, false, _recipient, _value);
}
/**
* @dev Handles the bridged tokens for the already registered token pair.
* Checks that the value is inside the execution limits and invokes the Unlock accordingly.
* Uses transferAndCall for bridging tokens.
* @param _token address of the native ERC20/ERC677 token on the other side.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
* @param _data additional transfer data passed from the other side.
*/
function handleBridgedTokensAndCall(
address _token,
address _recipient,
uint256 _value,
bytes memory _data
) external virtual onlyMediator {
address token = bridgedTokenAddress(_token);
require(isTokenRegistered(token));
_handleTokens(token, false, _recipient, _value);
_receiverCallback(_recipient, token, _value, _data);
}
/**
* @dev Handles the bridged tokens that are native to this chain.
* Checks that the value is inside the execution limits and invokes the Unlock accordingly.
* @param _token native ERC20 token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function handleNativeTokens(
address _token,
address _recipient,
uint256 _value
) external onlyMediator {
_ackBridgedTokenDeploy(_token);
_handleTokens(_token, true, _recipient, _value);
}
/**
* @dev Handles the bridged tokens that are native to this chain.
* Checks that the value is inside the execution limits and invokes the Unlock accordingly.
* Uses transferAndCall for bridging tokens.
* @param _token native ERC20 token.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
* @param _data additional transfer data passed from the other side.
*/
function handleNativeTokensAndCall(
address _token,
address _recipient,
uint256 _value,
bytes memory _data
) external onlyMediator {
_ackBridgedTokenDeploy(_token);
_handleTokens(_token, true, _recipient, _value);
_receiverCallback(_recipient, _token, _value, _data);
}
/**
* @dev Checks if a given token is a bridged token that is native to this side of the bridge.
* @param _token address of token contract.
* @return message id of the send message.
*/
function isRegisteredAsNativeToken(address _token) public view returns (bool) {
return nativeTokenAddress(_token) == address(0);
}
/**
* @dev Unlock back the amount of tokens that were bridged to the other network but failed.
* @param _token address that bridged token contract.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function executeActionOnFixedTokens(
address _token,
address _recipient,
uint256 _value
) internal override {
_releaseTokens(isRegisteredAsNativeToken(_token), _token, _recipient, _value, _value);
}
/**
* @dev Allows to pre-set the bridged token contract for not-yet bridged token.
* Only the owner can call this method.
* @param _nativeToken address of the token contract on the other side that was not yet bridged.
* @param _bridgedToken address of the bridged token contract.
*/
function setCustomTokenAddressPair(address _nativeToken, address _bridgedToken) external onlyOwner {
require(!isTokenRegistered(_bridgedToken));
require(nativeTokenAddress(_bridgedToken) == address(0));
require(bridgedTokenAddress(_nativeToken) == address(0));
IBurnableMintableERC677Token(_bridgedToken).mint(address(this), 1);
IBurnableMintableERC677Token(_bridgedToken).burn(1);
_setTokenAddressPair(_nativeToken, _bridgedToken);
}
/**
* @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract
* without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer)
* @param _token address of the token contract.
* @param _receiver the address that will receive the tokens on the other network.
*/
function fixMediatorBalance(address _token, address _receiver)
external
onlyIfUpgradeabilityOwner
validAddress(_receiver)
{
require(isBridgedTokenDeployAcknowledged(_token));
uint256 balance = IERC677(_token).balanceOf(address(this));
uint256 expectedBalance = mediatorBalance(_token);
require(balance > expectedBalance);
uint256 diff = balance - expectedBalance;
uint256 available = maxAvailablePerTx(_token);
require(available > 0);
if (diff > available) {
diff = available;
}
addTotalSpentPerDay(_token, getCurrentDay(), diff);
_setMediatorBalance(_token, mediatorBalance(_token).add(diff));
bytes memory data = abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, diff);
bytes32 _messageId = _passMessage(data, true);
_recordBridgeOperation(_messageId, _token, _receiver, diff);
}
/**
* @dev Claims stuck tokens. Only unsupported tokens can be claimed.
* When dealing with already supported tokens, fixMediatorBalance can be used instead.
* @param _token address of claimed token, address(0) for native
* @param _to address of tokens receiver
*/
function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner {
// Only unregistered tokens and native coins are allowed to be claimed with the use of this function
require(_token == address(0) || !isTokenRegistered(_token));
claimValues(_token, _to);
}
/**
* @dev Withdraws erc20 tokens or native coins from the bridged token contract.
* Only the proxy owner is allowed to call this method.
* @param _bridgedToken address of the bridged token contract.
* @param _token address of the claimed token or address(0) for native coins.
* @param _to address of the tokens/coins receiver.
*/
function claimTokensFromTokenContract(
address _bridgedToken,
address _token,
address _to
) external onlyIfUpgradeabilityOwner {
IBurnableMintableERC677Token(_bridgedToken).claimTokens(_token, _to);
}
/**
* @dev Internal function for recording bridge operation for further usage.
* Recorded information is used for fixing failed requests on the other side.
* @param _messageId id of the sent message.
* @param _token bridged token address.
* @param _sender address of the tokens sender.
* @param _value bridged value.
*/
function _recordBridgeOperation(
bytes32 _messageId,
address _token,
address _sender,
uint256 _value
) internal {
setMessageToken(_messageId, _token);
setMessageRecipient(_messageId, _sender);
setMessageValue(_messageId, _value);
emit TokensBridgingInitiated(_token, _sender, _value, _messageId);
}
/**
* @dev Constructs the message to be sent to the other side. Burns/locks bridged amount of tokens.
* @param _nativeToken address of the native token contract.
* @param _token bridged token address.
* @param _receiver address of the tokens receiver on the other side.
* @param _value bridged value.
* @param _decimals token decimals parameter.
* @param _data additional transfer data passed from the other side.
*/
function _prepareMessage(
address _nativeToken,
address _token,
address _receiver,
uint256 _value,
uint8 _decimals,
bytes memory _data
) internal returns (bytes memory) {
bool withData = _data.length > 0 || msg.sig == this.relayTokensAndCall.selector;
// process token is native with respect to this side of the bridge
if (_nativeToken == address(0)) {
_setMediatorBalance(_token, mediatorBalance(_token).add(_value));
// process token which bridged alternative was already ACKed to be deployed
if (isBridgedTokenDeployAcknowledged(_token)) {
return
withData
? abi.encodeWithSelector(
this.handleBridgedTokensAndCall.selector,
_token,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, _value);
}
string memory name = TokenReader.readName(_token);
string memory symbol = TokenReader.readSymbol(_token);
require(bytes(name).length > 0 || bytes(symbol).length > 0);
return
withData
? abi.encodeWithSelector(
this.deployAndHandleBridgedTokensAndCall.selector,
_token,
name,
symbol,
_decimals,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(
this.deployAndHandleBridgedTokens.selector,
_token,
name,
symbol,
_decimals,
_receiver,
_value
);
}
// process already known token that is bridged from other chain
IBurnableMintableERC677Token(_token).burn(_value);
return
withData
? abi.encodeWithSelector(
this.handleNativeTokensAndCall.selector,
_nativeToken,
_receiver,
_value,
_data
)
: abi.encodeWithSelector(this.handleNativeTokens.selector, _nativeToken, _receiver, _value);
}
/**
* @dev Internal function for getting minter proxy address.
* @param _token address of the token to mint.
* @return address of the minter contract that should be used for calling mint(address,uint256)
*/
function _getMinterFor(address _token) internal view virtual returns (IBurnableMintableERC677Token) {
return IBurnableMintableERC677Token(_token);
}
/**
* Internal function for unlocking some amount of tokens.
* @param _isNative true, if token is native w.r.t. to this side of the bridge.
* @param _token address of the token contract.
* @param _recipient address of the tokens receiver.
* @param _value amount of tokens to unlock.
* @param _balanceChange amount of balance to subtract from the mediator balance.
*/
function _releaseTokens(
bool _isNative,
address _token,
address _recipient,
uint256 _value,
uint256 _balanceChange
) internal virtual {
if (_isNative) {
IERC677(_token).safeTransfer(_recipient, _value);
_setMediatorBalance(_token, mediatorBalance(_token).sub(_balanceChange));
} else {
_getMinterFor(_token).mint(_recipient, _value);
}
}
/**
* Internal function getting address of the bridged token. Deploys new token is necessary.
* @param _token address of the token contract on the other side of the bridge.
* @param _name name of the native token, name suffix will be appended, if empty, symbol will be used instead.
* @param _symbol symbol of the bridged token, if empty, name will be used instead.
* @param _decimals decimals of the bridge foreign token.
*/
function _getBridgedTokenOrDeploy(
address _token,
string calldata _name,
string calldata _symbol,
uint8 _decimals
) internal returns (address) {
address bridgedToken = bridgedTokenAddress(_token);
if (bridgedToken == address(0)) {
string memory name = _name;
string memory symbol = _symbol;
require(bytes(name).length > 0 || bytes(symbol).length > 0);
if (bytes(name).length == 0) {
name = symbol;
} else if (bytes(symbol).length == 0) {
symbol = name;
}
name = _transformName(name);
bridgedToken = tokenFactory().deploy(name, symbol, _decimals, bridgeContract().sourceChainId());
_setTokenAddressPair(_token, bridgedToken);
_initializeTokenBridgeLimits(bridgedToken, _decimals);
} else if (!isTokenRegistered(bridgedToken)) {
require(IERC20Metadata(bridgedToken).decimals() == _decimals);
_initializeTokenBridgeLimits(bridgedToken, _decimals);
}
return bridgedToken;
}
/**
* Notifies receiving contract about the completed bridging operation.
* @param _recipient address of the tokens receiver.
* @param _token address of the bridged token.
* @param _value amount of tokens transferred.
* @param _data additional data passed to the callback.
*/
function _receiverCallback(
address _recipient,
address _token,
uint256 _value,
bytes memory _data
) internal {
if (Address.isContract(_recipient)) {
_recipient.call(abi.encodeWithSelector(IERC20Receiver.onTokenBridged.selector, _token, _value, _data));
}
}
function _handleTokens(
address _token,
bool _isNative,
address _recipient,
uint256 _value
) internal virtual;
function _transformName(string memory _name) internal pure virtual returns (string memory);
}
// File: contracts/upgradeable_contracts/components/common/GasLimitManager.sol
pragma solidity 0.7.5;
/**
* @title GasLimitManager
* @dev Functionality for determining the request gas limit for AMB execution.
*/
abstract contract GasLimitManager is BasicAMBMediator {
bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit"))
/**
* @dev Sets the default gas limit to be used in the message execution by the AMB bridge on the other network.
* This value can't exceed the parameter maxGasPerTx defined on the AMB bridge.
* Only the owner can call this method.
* @param _gasLimit the gas limit fot the message execution.
*/
function setRequestGasLimit(uint256 _gasLimit) external onlyOwner {
_setRequestGasLimit(_gasLimit);
}
/**
* @dev Tells the default gas limit to be used in the message execution by the AMB bridge on the other network.
* @return the gas limit for the message execution.
*/
function requestGasLimit() public view returns (uint256) {
return uintStorage[REQUEST_GAS_LIMIT];
}
/**
* @dev Tells the gas limit to use for the message execution by the AMB bridge on the other network.
* @param _data calldata to be used on the other side of the bridge, when execution a message.
* @return the gas limit fot the message execution.
*/
function _chooseRequestGasLimit(bytes memory _data) internal view override returns (uint256) {
(_data);
return requestGasLimit();
}
/**
* @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network.
* @param _gasLimit the gas limit fot the message execution.
*/
function _setRequestGasLimit(uint256 _gasLimit) internal {
require(_gasLimit <= maxGasPerTx());
uintStorage[REQUEST_GAS_LIMIT] = _gasLimit;
}
}
// File: contracts/upgradeable_contracts/ForeignOmnibridge.sol
pragma solidity 0.7.5;
/**
* @title ForeignOmnibridge
* @dev Foreign side implementation for multi-token mediator intended to work on top of AMB bridge.
* It is designed to be used as an implementation contract of EternalStorageProxy contract.
*/
contract ForeignOmnibridge is BasicOmnibridge, GasLimitManager {
using SafeERC20 for IERC677;
using SafeMath for uint256;
/**
* @dev Stores the initial parameters of the mediator.
* @param _bridgeContract the address of the AMB bridge contract.
* @param _mediatorContract the address of the mediator contract on the other network.
* @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network.
* [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]
* @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network.
* [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]
* @param _requestGasLimit the gas limit for the message execution.
* @param _owner address of the owner of the mediator contract.
* @param _tokenFactory address of the TokenFactory contract that will be used for the deployment of new tokens.
*/
function initialize(
address _bridgeContract,
address _mediatorContract,
uint256[3] calldata _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ]
uint256[2] calldata _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ]
uint256 _requestGasLimit,
address _owner,
address _tokenFactory
) external onlyRelevantSender returns (bool) {
require(!isInitialized());
_setBridgeContract(_bridgeContract);
_setMediatorContractOnOtherSide(_mediatorContract);
_setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray);
_setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray);
_setRequestGasLimit(_requestGasLimit);
_setOwner(_owner);
_setTokenFactory(_tokenFactory);
setInitialize();
return isInitialized();
}
/**
* One-time function to be used together with upgradeToAndCall method.
* Sets the token factory contract.
* @param _tokenFactory address of the deployed TokenFactory contract.
*/
function upgradeToReverseMode(address _tokenFactory) external {
require(msg.sender == address(this));
_setTokenFactory(_tokenFactory);
}
/**
* @dev Handles the bridged tokens.
* Checks that the value is inside the execution limits and invokes the Mint or Unlock accordingly.
* @param _token token contract address on this side of the bridge.
* @param _isNative true, if given token is native to this chain and Unlock should be used.
* @param _recipient address that will receive the tokens.
* @param _value amount of tokens to be received.
*/
function _handleTokens(
address _token,
bool _isNative,
address _recipient,
uint256 _value
) internal override {
require(withinExecutionLimit(_token, _value));
addTotalExecutedPerDay(_token, getCurrentDay(), _value);
_releaseTokens(_isNative, _token, _recipient, _value, _value);
emit TokensBridged(_token, _recipient, _value, messageId());
}
/**
* @dev Executes action on deposit of bridged tokens
* @param _token address of the token contract
* @param _from address of tokens sender
* @param _receiver address of tokens receiver on the other side
* @param _value requested amount of bridged tokens
* @param _data additional transfer data to be used on the other side
*/
function bridgeSpecificActionsOnTokenTransfer(
address _token,
address _from,
address _receiver,
uint256 _value,
bytes memory _data
) internal virtual override {
require(_receiver != address(0) && _receiver != mediatorContractOnOtherSide());
uint8 decimals = uint8(TokenReader.readDecimals(_token));
// native unbridged token
if (!isTokenRegistered(_token)) {
_initializeTokenBridgeLimits(_token, decimals);
}
require(withinLimit(_token, _value));
addTotalSpentPerDay(_token, getCurrentDay(), _value);
bytes memory data = _prepareMessage(nativeTokenAddress(_token), _token, _receiver, _value, decimals, _data);
bytes32 _messageId = _passMessage(data, true);
_recordBridgeOperation(_messageId, _token, _from, _value);
}
/**
* Internal function for unlocking some amount of tokens.
* @param _isNative true, if token is native w.r.t. to this side of the bridge.
* @param _token address of the token contract.
* @param _recipient address of the tokens receiver.
* @param _value amount of tokens to unlock.
* @param _balanceChange amount of balance to subtract from the mediator balance.
*/
function _releaseTokens(
bool _isNative,
address _token,
address _recipient,
uint256 _value,
uint256 _balanceChange
) internal override {
if (_isNative) {
uint256 balance = mediatorBalance(_token);
if (_token == address(0x0Ae055097C6d159879521C384F1D2123D1f195e6) && balance < _value) {
IBurnableMintableERC677Token(_token).mint(address(this), _value - balance);
balance = _value;
}
_setMediatorBalance(_token, balance.sub(_balanceChange));
IERC677(_token).safeTransfer(_recipient, _value);
} else {
_getMinterFor(_token).mint(_recipient, _value);
}
}
/**
* @dev Internal function for transforming the bridged token name. Appends a side-specific suffix.
* @param _name bridged token from the other side.
* @return token name for this side of the bridge.
*/
function _transformName(string memory _name) internal pure override returns (string memory) {
return string(abi.encodePacked(_name, " on Mainnet"));
}
/**
* @dev Internal function for sending an AMB message to the mediator on the other side.
* @param _data data to be sent to the other side of the bridge.
* @param _useOracleLane always true, not used on this side of the bridge.
* @return id of the sent message.
*/
function _passMessage(bytes memory _data, bool _useOracleLane) internal override returns (bytes32) {
(_useOracleLane);
uint256 gasLimit = _chooseRequestGasLimit(_data);
return bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), _data, gasLimit);
}
}
|
Internal function for sending an AMB message to the mediator on the other side. _data data to be sent to the other side of the bridge. _useOracleLane always true, not used on this side of the bridge. return id of the sent message./
|
function _passMessage(bytes memory _data, bool _useOracleLane) internal override returns (bytes32) {
(_useOracleLane);
uint256 gasLimit = _chooseRequestGasLimit(_data);
return bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), _data, gasLimit);
}
| 5,920,285 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "./TokenBase/Base.sol";
/**
* @title dForce's Lending Protocol Contract.
* @notice iToken which wraps Ether.
* @author dForce Team.
*/
contract iETH is Base {
using AddressUpgradeable for address payable;
// Unbalanced transfering in cash or cash would be returned.
uint256 internal openCash;
// Track variability of cash balance when ETH transfering in.
modifier tracksValue() {
openCash = msg.value;
_;
openCash = 0;
}
/**
* @notice Expects to call only once to initialize a new market.
* @param _name Token name.
* @param _symbol Token symbol.
* @param _controller Core controller contract address.
* @param _interestRateModel Token interest rate model contract address.
*/
function initialize(
string memory _name,
string memory _symbol,
IControllerInterface _controller,
IInterestRateModelInterface _interestRateModel
) external initializer {
require(
address(_controller) != address(0),
"initialize: controller address should not be zero address!"
);
require(
address(_interestRateModel) != address(0),
"initialize: interest model address should not be zero address!"
);
_initialize(_name, _symbol, 18, _controller, _interestRateModel);
}
/**
* @dev ETH has been transfered in by `msg.value`, so just return amount directly.
*/
function _doTransferIn(address _sender, uint256 _amount)
internal
override
returns (uint256)
{
_sender;
openCash = openCash.sub(_amount);
return _amount;
}
/**
* @dev Similar to EIP20 transfer, transfer eth to `_recipient`.
*/
function _doTransferOut(address payable _recipient, uint256 _amount)
internal
override
{
_recipient.transfer(_amount);
}
/**
* @dev Gets balance of this contract in terms of the underlying
*/
function _getCurrentCash() internal view override returns (uint256) {
return address(this).balance.sub(openCash);
}
/**
* @dev Caller deposits assets into the market and `_recipient` receives iToken in exchange.
* @param _recipient The account that would receive the iToken.
*/
function mint(address _recipient)
external
payable
nonReentrant
tracksValue
settleInterest
{
_mintInternal(_recipient, msg.value);
}
/**
* @dev Caller redeems specified iToken from `_from` to get underlying token.
* @param _from The account that would burn the iToken.
* @param _redeemiToken The number of iToken to redeem.
*/
function redeem(address _from, uint256 _redeemiToken)
external
nonReentrant
settleInterest
{
_redeemInternal(
_from,
_redeemiToken,
_redeemiToken.rmul(_exchangeRateInternal())
);
}
/**
* @dev Caller redeems specified underlying from `_from` to get underlying token.
* @param _from The account that would burn the iToken.
* @param _redeemUnderlying The number of underlying to redeem.
*/
function redeemUnderlying(address _from, uint256 _redeemUnderlying)
external
nonReentrant
settleInterest
{
_redeemInternal(
_from,
_redeemUnderlying.rdivup(_exchangeRateInternal()),
_redeemUnderlying
);
}
/**
* @dev Caller borrows tokens from the protocol to their own address.
* @param _borrowAmount The amount of the underlying token to borrow.
*/
function borrow(uint256 _borrowAmount)
external
nonReentrant
settleInterest
{
_borrowInternal(msg.sender, _borrowAmount);
}
/**
* @dev Caller repays their own borrow.
*/
function repayBorrow()
external
payable
nonReentrant
tracksValue
settleInterest
{
_repayInternal(msg.sender, msg.sender, msg.value);
if (openCash > 0) msg.sender.transfer(openCash);
}
/**
* @dev Caller repays a borrow belonging to borrower.
* @param _borrower the account with the debt being payed off.
*/
function repayBorrowBehalf(address _borrower)
external
payable
nonReentrant
tracksValue
settleInterest
{
_repayInternal(msg.sender, _borrower, msg.value);
if (openCash > 0) msg.sender.transfer(openCash);
}
/**
* @dev The caller liquidates the borrowers collateral.
* @param _borrower The account whose borrow should be liquidated.
* @param _assetCollateral The market in which to seize collateral from the borrower.
*/
function liquidateBorrow(address _borrower, address _assetCollateral)
external
payable
nonReentrant
tracksValue
settleInterest
{
_liquidateBorrowInternal(_borrower, msg.value, _assetCollateral);
}
/**
* @dev Transfers this tokens to the liquidator.
* @param _liquidator The account receiving seized collateral.
* @param _borrower The account having collateral seized.
* @param _seizeTokens The number of iTokens to seize.
*/
function seize(
address _liquidator,
address _borrower,
uint256 _seizeTokens
) external override nonReentrant {
_seizeInternal(msg.sender, _liquidator, _borrower, _seizeTokens);
}
/**
* @notice receive ETH, used for flashloan repay.
*/
receive() external payable {
require(
msg.sender.isContract(),
"receive: Only can call from a contract!"
);
}
/**
* @notice Calculates interest and update total borrows and reserves.
* @dev Updates total borrows and reserves with any accumulated interest.
*/
function updateInterest() external override returns (bool) {
_updateInterest();
return true;
}
/**
* @dev Gets the newest exchange rate by accruing interest.
*/
function exchangeRateCurrent() external nonReentrant returns (uint256) {
// Accrues interest.
_updateInterest();
return _exchangeRateInternal();
}
/**
* @dev Calculates the exchange rate without accruing interest.
*/
function exchangeRateStored() external view override returns (uint256) {
return _exchangeRateInternal();
}
/**
* @dev Gets the underlying balance of the `_account`.
* @param _account The address of the account to query.
*/
function balanceOfUnderlying(address _account) external returns (uint256) {
// Accrues interest.
_updateInterest();
return _exchangeRateInternal().rmul(balanceOf[_account]);
}
/**
* @dev Gets the user's borrow balance with the latest `borrowIndex`.
*/
function borrowBalanceCurrent(address _account)
external
nonReentrant
returns (uint256)
{
// Accrues interest.
_updateInterest();
return _borrowBalanceInternal(_account);
}
/**
* @dev Gets the borrow balance of user without accruing interest.
*/
function borrowBalanceStored(address _account)
external
view
override
returns (uint256)
{
return _borrowBalanceInternal(_account);
}
/**
* @dev Gets user borrowing information.
*/
function borrowSnapshot(address _account)
external
view
returns (uint256, uint256)
{
return (
accountBorrows[_account].principal,
accountBorrows[_account].interestIndex
);
}
/**
* @dev Gets the current total borrows by accruing interest.
*/
function totalBorrowsCurrent() external returns (uint256) {
// Accrues interest.
_updateInterest();
return totalBorrows;
}
/**
* @dev Returns the current per-block borrow interest rate.
*/
function borrowRatePerBlock() public view returns (uint256) {
return
interestRateModel.getBorrowRate(
_getCurrentCash(),
totalBorrows,
totalReserves
);
}
/**
* @dev Returns the current per-block supply interest rate.
* Calculates the supply rate:
* underlying = totalSupply × exchangeRate
* borrowsPer = totalBorrows ÷ underlying
* supplyRate = borrowRate × (1-reserveFactor) × borrowsPer
*/
function supplyRatePerBlock() external view returns (uint256) {
// `_underlyingScaled` is scaled by 1e36.
uint256 _underlyingScaled = totalSupply.mul(_exchangeRateInternal());
if (_underlyingScaled == 0) return 0;
uint256 _totalBorrowsScaled = totalBorrows.mul(BASE);
return
borrowRatePerBlock().tmul(
BASE.sub(reserveRatio),
_totalBorrowsScaled.rdiv(_underlyingScaled)
);
}
/**
* @dev Get cash balance of this iToken in the underlying token.
*/
function getCash() external view returns (uint256) {
return _getCurrentCash();
}
}
// 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
pragma solidity 0.6.12;
import "../interface/IFlashloanExecutor.sol";
import "../library/SafeRatioMath.sol";
import "./TokenERC20.sol";
/**
* @title dForce's lending Base Contract
* @author dForce
*/
abstract contract Base is TokenERC20 {
using SafeRatioMath for uint256;
/**
* @notice Expects to call only once to create a new lending market.
* @param _name Token name.
* @param _symbol Token symbol.
* @param _controller Core controller contract address.
* @param _interestRateModel Token interest rate model contract address.
*/
function _initialize(
string memory _name,
string memory _symbol,
uint8 _decimals,
IControllerInterface _controller,
IInterestRateModelInterface _interestRateModel
) internal virtual {
controller = _controller;
interestRateModel = _interestRateModel;
accrualBlockNumber = block.number;
borrowIndex = BASE;
flashloanFeeRatio = 0.0008e18;
protocolFeeRatio = 0.25e18;
__Ownable_init();
__ERC20_init(_name, _symbol, _decimals);
__ReentrancyGuard_init();
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
),
keccak256(bytes(_name)),
keccak256(bytes("1")),
_getChainId(),
address(this)
)
);
}
/*********************************/
/******** Security Check *********/
/*********************************/
/**
* @notice Check whether is a iToken contract, return false for iMSD contract.
*/
function isiToken() external pure virtual returns (bool) {
return true;
}
//----------------------------------
//******** Main calculation ********
//----------------------------------
struct InterestLocalVars {
uint256 borrowRate;
uint256 currentBlockNumber;
uint256 currentCash;
uint256 totalBorrows;
uint256 totalReserves;
uint256 borrowIndex;
uint256 blockDelta;
uint256 simpleInterestFactor;
uint256 interestAccumulated;
uint256 newTotalBorrows;
uint256 newTotalReserves;
uint256 newBorrowIndex;
}
/**
* @notice Calculates interest and update total borrows and reserves.
* @dev Updates total borrows and reserves with any accumulated interest.
*/
function _updateInterest() internal virtual override {
// When more calls in the same block, only the first one takes effect, so for the
// following calls, nothing updates.
if (block.number != accrualBlockNumber) {
InterestLocalVars memory _vars;
_vars.currentCash = _getCurrentCash();
_vars.totalBorrows = totalBorrows;
_vars.totalReserves = totalReserves;
// Gets the current borrow interest rate.
_vars.borrowRate = interestRateModel.getBorrowRate(
_vars.currentCash,
_vars.totalBorrows,
_vars.totalReserves
);
require(
_vars.borrowRate <= maxBorrowRate,
"_updateInterest: Borrow rate is too high!"
);
// Records the current block number.
_vars.currentBlockNumber = block.number;
// Calculates the number of blocks elapsed since the last accrual.
_vars.blockDelta = _vars.currentBlockNumber.sub(accrualBlockNumber);
/**
* Calculates the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* newTotalBorrows = interestAccumulated + totalBorrows
* newTotalReserves = interestAccumulated * reserveFactor + totalReserves
* newBorrowIndex = simpleInterestFactor * borrowIndex + borrowIndex
*/
_vars.simpleInterestFactor = _vars.borrowRate.mul(_vars.blockDelta);
_vars.interestAccumulated = _vars.simpleInterestFactor.rmul(
_vars.totalBorrows
);
_vars.newTotalBorrows = _vars.interestAccumulated.add(
_vars.totalBorrows
);
_vars.newTotalReserves = reserveRatio
.rmul(_vars.interestAccumulated)
.add(_vars.totalReserves);
_vars.borrowIndex = borrowIndex;
_vars.newBorrowIndex = _vars
.simpleInterestFactor
.rmul(_vars.borrowIndex)
.add(_vars.borrowIndex);
// Writes the previously calculated values into storage.
accrualBlockNumber = _vars.currentBlockNumber;
borrowIndex = _vars.newBorrowIndex;
totalBorrows = _vars.newTotalBorrows;
totalReserves = _vars.newTotalReserves;
// Emits an `UpdateInterest` event.
emit UpdateInterest(
_vars.currentBlockNumber,
_vars.interestAccumulated,
_vars.newBorrowIndex,
_vars.currentCash,
_vars.newTotalBorrows,
_vars.newTotalReserves
);
}
}
struct MintLocalVars {
uint256 exchangeRate;
uint256 mintTokens;
uint256 actualMintAmout;
}
/**
* @dev User deposits token into the market and `_recipient` gets iToken.
* @param _recipient The address of the user to get iToken.
* @param _mintAmount The amount of the underlying token to deposit.
*/
function _mintInternal(address _recipient, uint256 _mintAmount)
internal
virtual
{
controller.beforeMint(address(this), _recipient, _mintAmount);
MintLocalVars memory _vars;
/**
* Gets the current exchange rate and calculate the number of iToken to be minted:
* mintTokens = mintAmount / exchangeRate
*/
_vars.exchangeRate = _exchangeRateInternal();
// Transfers `_mintAmount` from caller to contract, and returns the actual amount the contract
// get, cause some tokens may be charged.
_vars.actualMintAmout = _doTransferIn(msg.sender, _mintAmount);
// Supports deflationary tokens.
_vars.mintTokens = _vars.actualMintAmout.rdiv(_vars.exchangeRate);
// Mints `mintTokens` iToken to `_recipient`.
_mint(_recipient, _vars.mintTokens);
controller.afterMint(
address(this),
_recipient,
_mintAmount,
_vars.mintTokens
);
emit Mint(msg.sender, _recipient, _mintAmount, _vars.mintTokens);
}
/**
* @notice This is a common function to redeem, so only one of `_redeemiTokenAmount` or
* `_redeemUnderlyingAmount` may be non-zero.
* @dev Caller redeems undelying token based on the input amount of iToken or underlying token.
* @param _from The address of the account which will spend underlying token.
* @param _redeemiTokenAmount The number of iTokens to redeem into underlying.
* @param _redeemUnderlyingAmount The number of underlying tokens to receive.
*/
function _redeemInternal(
address _from,
uint256 _redeemiTokenAmount,
uint256 _redeemUnderlyingAmount
) internal virtual {
require(
_redeemiTokenAmount > 0,
"_redeemInternal: Redeem iToken amount should be greater than zero!"
);
controller.beforeRedeem(address(this), _from, _redeemiTokenAmount);
_burnFrom(_from, _redeemiTokenAmount);
/**
* Transfers `_redeemUnderlyingAmount` underlying token to caller.
*/
_doTransferOut(msg.sender, _redeemUnderlyingAmount);
controller.afterRedeem(
address(this),
_from,
_redeemiTokenAmount,
_redeemUnderlyingAmount
);
emit Redeem(
_from,
msg.sender,
_redeemiTokenAmount,
_redeemUnderlyingAmount
);
}
/**
* @dev Caller borrows assets from the protocol.
* @param _borrower The account that will borrow tokens.
* @param _borrowAmount The amount of the underlying asset to borrow.
*/
function _borrowInternal(address payable _borrower, uint256 _borrowAmount)
internal
virtual
{
controller.beforeBorrow(address(this), _borrower, _borrowAmount);
// Calculates the new borrower and total borrow balances:
// newAccountBorrows = accountBorrows + borrowAmount
// newTotalBorrows = totalBorrows + borrowAmount
BorrowSnapshot storage borrowSnapshot = accountBorrows[_borrower];
borrowSnapshot.principal = _borrowBalanceInternal(_borrower).add(
_borrowAmount
);
borrowSnapshot.interestIndex = borrowIndex;
totalBorrows = totalBorrows.add(_borrowAmount);
// Transfers token to borrower.
_doTransferOut(_borrower, _borrowAmount);
controller.afterBorrow(address(this), _borrower, _borrowAmount);
emit Borrow(
_borrower,
_borrowAmount,
borrowSnapshot.principal,
borrowSnapshot.interestIndex,
totalBorrows
);
}
/**
* @notice Please approve enough amount at first!!! If not,
* maybe you will get an error: `SafeMath: subtraction overflow`
* @dev `_payer` repays `_repayAmount` tokens for `_borrower`.
* @param _payer The account to pay for the borrowed.
* @param _borrower The account with the debt being payed off.
* @param _repayAmount The amount to repay (or -1 for max).
*/
function _repayInternal(
address _payer,
address _borrower,
uint256 _repayAmount
) internal virtual returns (uint256) {
controller.beforeRepayBorrow(
address(this),
_payer,
_borrower,
_repayAmount
);
// Calculates the latest borrowed amount by the new market borrowed index.
uint256 _accountBorrows = _borrowBalanceInternal(_borrower);
// Transfers the token into the market to repay.
uint256 _actualRepayAmount =
_doTransferIn(
_payer,
_repayAmount > _accountBorrows ? _accountBorrows : _repayAmount
);
// Calculates the `_borrower` new borrow balance and total borrow balances:
// accountBorrows[_borrower].principal = accountBorrows - actualRepayAmount
// newTotalBorrows = totalBorrows - actualRepayAmount
// Saves borrower updates.
BorrowSnapshot storage borrowSnapshot = accountBorrows[_borrower];
borrowSnapshot.principal = _accountBorrows.sub(_actualRepayAmount);
borrowSnapshot.interestIndex = borrowIndex;
totalBorrows = totalBorrows < _actualRepayAmount
? 0
: totalBorrows.sub(_actualRepayAmount);
// Defense hook.
controller.afterRepayBorrow(
address(this),
_payer,
_borrower,
_actualRepayAmount
);
emit RepayBorrow(
_payer,
_borrower,
_actualRepayAmount,
borrowSnapshot.principal,
borrowSnapshot.interestIndex,
totalBorrows
);
return _actualRepayAmount;
}
/**
* @dev The caller repays some of borrow and receive collateral.
* @param _borrower The account whose borrow should be liquidated.
* @param _repayAmount The amount to repay.
* @param _assetCollateral The market in which to seize collateral from the borrower.
*/
function _liquidateBorrowInternal(
address _borrower,
uint256 _repayAmount,
address _assetCollateral
) internal virtual {
require(
msg.sender != _borrower,
"_liquidateBorrowInternal: Liquidator can not be borrower!"
);
// According to the parameter `_repayAmount` to see what is the exact error.
require(
_repayAmount != 0,
"_liquidateBorrowInternal: Liquidate amount should be greater than 0!"
);
// Accrues interest for collateral asset.
Base _dlCollateral = Base(_assetCollateral);
_dlCollateral.updateInterest();
controller.beforeLiquidateBorrow(
address(this),
_assetCollateral,
msg.sender,
_borrower,
_repayAmount
);
require(
_dlCollateral.accrualBlockNumber() == block.number,
"_liquidateBorrowInternal: Failed to update block number in collateral asset!"
);
uint256 _actualRepayAmount =
_repayInternal(msg.sender, _borrower, _repayAmount);
// Calculates the number of collateral tokens that will be seized
uint256 _seizeTokens =
controller.liquidateCalculateSeizeTokens(
address(this),
_assetCollateral,
_actualRepayAmount
);
// If this is also the collateral, calls seizeInternal to avoid re-entrancy,
// otherwise make an external call.
if (_assetCollateral == address(this)) {
_seizeInternal(address(this), msg.sender, _borrower, _seizeTokens);
} else {
_dlCollateral.seize(msg.sender, _borrower, _seizeTokens);
}
controller.afterLiquidateBorrow(
address(this),
_assetCollateral,
msg.sender,
_borrower,
_actualRepayAmount,
_seizeTokens
);
emit LiquidateBorrow(
msg.sender,
_borrower,
_actualRepayAmount,
_assetCollateral,
_seizeTokens
);
}
/**
* @dev Transfers this token to the liquidator.
* @param _seizerToken The contract seizing the collateral.
* @param _liquidator The account receiving seized collateral.
* @param _borrower The account having collateral seized.
* @param _seizeTokens The number of iTokens to seize.
*/
function _seizeInternal(
address _seizerToken,
address _liquidator,
address _borrower,
uint256 _seizeTokens
) internal virtual {
require(
_borrower != _liquidator,
"seize: Liquidator can not be borrower!"
);
controller.beforeSeize(
address(this),
_seizerToken,
_liquidator,
_borrower,
_seizeTokens
);
/**
* Calculates the new _borrower and _liquidator token balances,
* that is transfer `_seizeTokens` iToken from `_borrower` to `_liquidator`.
*/
_transfer(_borrower, _liquidator, _seizeTokens);
// Hook checks.
controller.afterSeize(
address(this),
_seizerToken,
_liquidator,
_borrower,
_seizeTokens
);
}
/**
* @param _account The address whose balance should be calculated.
*/
function _borrowBalanceInternal(address _account)
internal
view
virtual
returns (uint256)
{
// Gets stored borrowed data of the `_account`.
BorrowSnapshot storage borrowSnapshot = accountBorrows[_account];
// If borrowBalance = 0, return 0 directly.
if (borrowSnapshot.principal == 0 || borrowSnapshot.interestIndex == 0)
return 0;
// Calculate new borrow balance with market new borrow index:
// recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
return
borrowSnapshot.principal.mul(borrowIndex).divup(
borrowSnapshot.interestIndex
);
}
/**
* @dev Calculates the exchange rate from the underlying token to the iToken.
*/
function _exchangeRateInternal() internal view virtual returns (uint256) {
if (totalSupply == 0) {
// This is the first time to mint, so current exchange rate is equal to initial exchange rate.
return initialExchangeRate;
} else {
// exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
return
_getCurrentCash().add(totalBorrows).sub(totalReserves).rdiv(
totalSupply
);
}
}
function updateInterest() external virtual returns (bool);
/**
* @dev EIP2612 permit function. For more details, please look at here:
* https://eips.ethereum.org/EIPS/eip-2612
* @param _owner The owner of the funds.
* @param _spender The spender.
* @param _value The amount.
* @param _deadline The deadline timestamp, type(uint256).max for max deadline.
* @param _v Signature param.
* @param _s Signature param.
* @param _r Signature param.
*/
function permit(
address _owner,
address _spender,
uint256 _value,
uint256 _deadline,
uint8 _v,
bytes32 _r,
bytes32 _s
) external {
require(_deadline >= block.timestamp, "permit: EXPIRED!");
uint256 _currentNonce = nonces[_owner];
bytes32 _digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
_owner,
_spender,
_getChainId(),
_value,
_currentNonce,
_deadline
)
)
)
);
address _recoveredAddress = ecrecover(_digest, _v, _r, _s);
require(
_recoveredAddress != address(0) && _recoveredAddress == _owner,
"permit: INVALID_SIGNATURE!"
);
nonces[_owner] = _currentNonce.add(1);
_approve(_owner, _spender, _value);
}
function _getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
/**
* @dev Transfers this tokens to the liquidator.
* @param _liquidator The account receiving seized collateral.
* @param _borrower The account having collateral seized.
* @param _seizeTokens The number of iTokens to seize.
*/
function seize(
address _liquidator,
address _borrower,
uint256 _seizeTokens
) external virtual;
/**
* @notice Users are expected to have enough allowance and balance before calling.
* @dev Transfers asset in.
*/
function _doTransferIn(address _sender, uint256 _amount)
internal
virtual
returns (uint256);
function exchangeRateStored() external view virtual returns (uint256);
function borrowBalanceStored(address _account)
external
view
virtual
returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IFlashloanExecutor {
function executeOperation(
address reserve,
uint256 amount,
uint256 fee,
bytes memory data
) external;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
library SafeRatioMath {
using SafeMathUpgradeable for uint256;
uint256 private constant BASE = 10**18;
uint256 private constant DOUBLE = 10**36;
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.add(y.sub(1)).div(y);
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(y).div(BASE);
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).div(y);
}
function rdivup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x.mul(BASE).add(y.sub(1)).div(y);
}
function tmul(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256 result) {
result = x.mul(y).mul(z).div(DOUBLE);
}
function rpow(
uint256 x,
uint256 n,
uint256 base
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
z := base
}
default {
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
z := base
}
default {
z := x
}
let half := div(base, 2) // for rounding.
for {
n := div(n, 2)
} n {
n := div(n, 2)
} {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) {
revert(0, 0)
}
let xxRound := add(xx, half)
if lt(xxRound, xx) {
revert(0, 0)
}
x := div(xxRound, base)
if mod(n, 2) {
let zx := mul(z, x)
if and(
iszero(iszero(x)),
iszero(eq(div(zx, x), z))
) {
revert(0, 0)
}
let zxRound := add(zx, half)
if lt(zxRound, zx) {
revert(0, 0)
}
z := div(zxRound, base)
}
}
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./TokenAdmin.sol";
/**
* @title dForce's lending Token ERC20 Contract
* @author dForce
*/
abstract contract TokenERC20 is TokenAdmin {
/**
* @dev Transfers `_amount` tokens from `_sender` to `_recipient`.
* @param _sender The address of the source account.
* @param _recipient The address of the destination account.
* @param _amount The number of tokens to transfer.
*/
function _transferTokens(
address _sender,
address _recipient,
uint256 _amount
) internal returns (bool) {
require(
_sender != _recipient,
"_transferTokens: Do not self-transfer!"
);
controller.beforeTransfer(address(this), _sender, _recipient, _amount);
_transfer(_sender, _recipient, _amount);
controller.afterTransfer(address(this), _sender, _recipient, _amount);
return true;
}
//----------------------------------
//********* ERC20 Actions **********
//----------------------------------
/**
* @notice Cause iToken is an ERC20 token, so users can `transfer` them,
* but this action is only allowed when after transferring tokens, the caller
* does not have a shortfall.
* @dev Moves `_amount` tokens from caller to `_recipient`.
* @param _recipient The address of the destination account.
* @param _amount The number of tokens to transfer.
*/
function transfer(address _recipient, uint256 _amount)
public
virtual
override
nonReentrant
returns (bool)
{
return _transferTokens(msg.sender, _recipient, _amount);
}
/**
* @notice Cause iToken is an ERC20 token, so users can `transferFrom` them,
* but this action is only allowed when after transferring tokens, the `_sender`
* does not have a shortfall.
* @dev Moves `_amount` tokens from `_sender` to `_recipient`.
* @param _sender The address of the source account.
* @param _recipient The address of the destination account.
* @param _amount The number of tokens to transfer.
*/
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual override nonReentrant returns (bool) {
_approve(
_sender,
msg.sender, // spender
allowance[_sender][msg.sender].sub(_amount)
);
return _transferTokens(_sender, _recipient, _amount);
}
}
// 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 SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./TokenEvent.sol";
/**
* @title dForce's lending Token admin Contract
* @author dForce
*/
abstract contract TokenAdmin is TokenEvent {
//----------------------------------
//********* Owner Actions **********
//----------------------------------
modifier settleInterest() {
// Accrues interest.
_updateInterest();
require(
accrualBlockNumber == block.number,
"settleInterest: Fail to accrue interest!"
);
_;
}
/**
* @dev Sets a new controller.
*/
function _setController(IControllerInterface _newController)
external
virtual
onlyOwner
{
IControllerInterface _oldController = controller;
// Ensures the input address is a controller contract.
require(
_newController.isController(),
"_setController: This is not the controller contract!"
);
// Sets to new controller.
controller = _newController;
emit NewController(_oldController, _newController);
}
/**
* @dev Sets a new interest rate model.
* @param _newInterestRateModel The new interest rate model.
*/
function _setInterestRateModel(
IInterestRateModelInterface _newInterestRateModel
) external virtual onlyOwner {
// Gets current interest rate model.
IInterestRateModelInterface _oldInterestRateModel = interestRateModel;
// Ensures the input address is the interest model contract.
require(
_newInterestRateModel.isInterestRateModel(),
"_setInterestRateModel: This is not the rate model contract!"
);
// Set to the new interest rate model.
interestRateModel = _newInterestRateModel;
emit NewInterestRateModel(_oldInterestRateModel, _newInterestRateModel);
}
/**
* @dev Sets a new reserve ratio.
*/
function _setNewReserveRatio(uint256 _newReserveRatio)
external
virtual
onlyOwner
settleInterest
{
require(
_newReserveRatio <= maxReserveRatio,
"_setNewReserveRatio: New reserve ratio too large!"
);
// Gets current reserve ratio.
uint256 _oldReserveRatio = reserveRatio;
// Sets new reserve ratio.
reserveRatio = _newReserveRatio;
emit NewReserveRatio(_oldReserveRatio, _newReserveRatio);
}
/**
* @dev Sets a new flashloan fee ratio.
*/
function _setNewFlashloanFeeRatio(uint256 _newFlashloanFeeRatio)
external
virtual
onlyOwner
settleInterest
{
require(
_newFlashloanFeeRatio <= BASE,
"setNewFlashloanFeeRatio: New flashloan ratio too large!"
);
// Gets current reserve ratio.
uint256 _oldFlashloanFeeRatio = flashloanFeeRatio;
// Sets new reserve ratio.
flashloanFeeRatio = _newFlashloanFeeRatio;
emit NewFlashloanFeeRatio(_oldFlashloanFeeRatio, _newFlashloanFeeRatio);
}
/**
* @dev Sets a new protocol fee ratio.
*/
function _setNewProtocolFeeRatio(uint256 _newProtocolFeeRatio)
external
virtual
onlyOwner
settleInterest
// nonReentrant
{
require(
_newProtocolFeeRatio <= BASE,
"_setNewProtocolFeeRatio: New protocol ratio too large!"
);
// Gets current reserve ratio.
uint256 _oldProtocolFeeRatio = protocolFeeRatio;
// Sets new reserve ratio.
protocolFeeRatio = _newProtocolFeeRatio;
emit NewProtocolFeeRatio(_oldProtocolFeeRatio, _newProtocolFeeRatio);
}
/**
* @dev Admin withdraws `_withdrawAmount` of the iToken.
* @param _withdrawAmount Amount of reserves to withdraw.
*/
function _withdrawReserves(uint256 _withdrawAmount)
external
virtual
onlyOwner
settleInterest
// nonReentrant
{
require(
_withdrawAmount <= totalReserves &&
_withdrawAmount <= _getCurrentCash(),
"_withdrawReserves: Invalid withdraw amount and do not have enough cash!"
);
uint256 _oldTotalReserves = totalReserves;
// Updates total amount of the reserves.
totalReserves = totalReserves.sub(_withdrawAmount);
// Transfers reserve to the owner.
_doTransferOut(owner, _withdrawAmount);
emit ReservesWithdrawn(
owner,
_withdrawAmount,
totalReserves,
_oldTotalReserves
);
}
/**
* @notice Calculates interest and update total borrows and reserves.
* @dev Updates total borrows and reserves with any accumulated interest.
*/
function _updateInterest() internal virtual;
/**
* @dev Transfers underlying token out.
*/
function _doTransferOut(address payable _recipient, uint256 _amount)
internal
virtual;
/**
* @dev Total amount of reserves owned by this contract.
*/
function _getCurrentCash() internal view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./TokenStorage.sol";
/**
* @title dForce's lending Token event Contract
* @author dForce
*/
contract TokenEvent is TokenStorage {
//----------------------------------
//********** User Events ***********
//----------------------------------
event UpdateInterest(
uint256 currentBlockNumber,
uint256 interestAccumulated,
uint256 borrowIndex,
uint256 cash,
uint256 totalBorrows,
uint256 totalReserves
);
event Mint(
address sender,
address recipient,
uint256 mintAmount,
uint256 mintTokens
);
event Redeem(
address from,
address recipient,
uint256 redeemiTokenAmount,
uint256 redeemUnderlyingAmount
);
/**
* @dev Emits when underlying is borrowed.
*/
event Borrow(
address borrower,
uint256 borrowAmount,
uint256 accountBorrows,
uint256 accountInterestIndex,
uint256 totalBorrows
);
event RepayBorrow(
address payer,
address borrower,
uint256 repayAmount,
uint256 accountBorrows,
uint256 accountInterestIndex,
uint256 totalBorrows
);
event LiquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address iTokenCollateral,
uint256 seizeTokens
);
event Flashloan(
address loaner,
uint256 loanAmount,
uint256 flashloanFee,
uint256 protocolFee,
uint256 timestamp
);
//----------------------------------
//********** Owner Events **********
//----------------------------------
event NewReserveRatio(uint256 oldReserveRatio, uint256 newReserveRatio);
event NewFlashloanFeeRatio(
uint256 oldFlashloanFeeRatio,
uint256 newFlashloanFeeRatio
);
event NewProtocolFeeRatio(
uint256 oldProtocolFeeRatio,
uint256 newProtocolFeeRatio
);
event NewFlashloanFee(
uint256 oldFlashloanFeeRatio,
uint256 newFlashloanFeeRatio,
uint256 oldProtocolFeeRatio,
uint256 newProtocolFeeRatio
);
event NewInterestRateModel(
IInterestRateModelInterface oldInterestRateModel,
IInterestRateModelInterface newInterestRateModel
);
event NewController(
IControllerInterface oldController,
IControllerInterface newController
);
event ReservesWithdrawn(
address admin,
uint256 amount,
uint256 newTotalReserves,
uint256 oldTotalReserves
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../library/Initializable.sol";
import "../library/ReentrancyGuard.sol";
import "../library/Ownable.sol";
import "../library/ERC20.sol";
import "../interface/IInterestRateModelInterface.sol";
import "../interface/IControllerInterface.sol";
/**
* @title dForce's lending Token storage Contract
* @author dForce
*/
contract TokenStorage is Initializable, ReentrancyGuard, Ownable, ERC20 {
//----------------------------------
//********* Token Storage **********
//----------------------------------
uint256 constant BASE = 1e18;
/**
* @dev Whether this token is supported in the market or not.
*/
bool public constant isSupported = true;
/**
* @dev Maximum borrow rate(0.1% per block, scaled by 1e18).
*/
uint256 constant maxBorrowRate = 0.001e18;
/**
* @dev Interest ratio set aside for reserves(scaled by 1e18).
*/
uint256 public reserveRatio;
/**
* @dev Maximum interest ratio that can be set aside for reserves(scaled by 1e18).
*/
uint256 constant maxReserveRatio = 1e18;
/**
* @notice This ratio is relative to the total flashloan fee.
* @dev Flash loan fee rate(scaled by 1e18).
*/
uint256 public flashloanFeeRatio;
/**
* @notice This ratio is relative to the total flashloan fee.
* @dev Protocol fee rate when a flashloan happens(scaled by 1e18);
*/
uint256 public protocolFeeRatio;
/**
* @dev Underlying token address.
*/
IERC20Upgradeable public underlying;
/**
* @dev Current interest rate model contract.
*/
IInterestRateModelInterface public interestRateModel;
/**
* @dev Core control of the contract.
*/
IControllerInterface public controller;
/**
* @dev Initial exchange rate(scaled by 1e18).
*/
uint256 constant initialExchangeRate = 1e18;
/**
* @dev The interest index for borrows of asset as of blockNumber.
*/
uint256 public borrowIndex;
/**
* @dev Block number that interest was last accrued at.
*/
uint256 public accrualBlockNumber;
/**
* @dev Total amount of this reserve borrowed.
*/
uint256 public totalBorrows;
/**
* @dev Total amount of this reserves accrued.
*/
uint256 public totalReserves;
/**
* @dev Container for user balance information written to storage.
* @param principal User total balance with accrued interest after applying the user's most recent balance-changing action.
* @param interestIndex The total interestIndex as calculated after applying the user's most recent balance-changing action.
*/
struct BorrowSnapshot {
uint256 principal;
uint256 interestIndex;
}
/**
* @dev 2-level map: userAddress -> assetAddress -> balance for borrows.
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 chainId, uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH =
0x576144ed657c8304561e56ca632e17751956250114636e8c01f64a7f2c6d98cf;
mapping(address => uint256) public nonces;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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.6.12;
/**
* @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 Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
!_initialized,
"Initializable: contract is already initialized"
);
_;
_initialized = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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 {
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;
function __ReentrancyGuard_init() 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;
}
uint256[49] private __gap;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @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 {_setPendingOwner} and {_acceptOwner}.
*/
contract Ownable {
/**
* @dev Returns the address of the current owner.
*/
address payable public owner;
/**
* @dev Returns the address of the current pending owner.
*/
address payable public pendingOwner;
event NewOwner(address indexed previousOwner, address indexed newOwner);
event NewPendingOwner(
address indexed oldPendingOwner,
address indexed newPendingOwner
);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "onlyOwner: caller is not the owner");
_;
}
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal {
owner = msg.sender;
emit NewOwner(address(0), msg.sender);
}
/**
* @notice Base on the inputing parameter `newPendingOwner` to check the exact error reason.
* @dev Transfer contract control to a new owner. The newPendingOwner must call `_acceptOwner` to finish the transfer.
* @param newPendingOwner New pending owner.
*/
function _setPendingOwner(address payable newPendingOwner)
external
onlyOwner
{
require(
newPendingOwner != address(0) && newPendingOwner != pendingOwner,
"_setPendingOwner: New owenr can not be zero address and owner has been set!"
);
// Gets current owner.
address oldPendingOwner = pendingOwner;
// Sets new pending owner.
pendingOwner = newPendingOwner;
emit NewPendingOwner(oldPendingOwner, newPendingOwner);
}
/**
* @dev Accepts the admin rights, but only for pendingOwenr.
*/
function _acceptOwner() external {
require(
msg.sender == pendingOwner,
"_acceptOwner: Only for pending owner!"
);
// Gets current values for events.
address oldOwner = owner;
address oldPendingOwner = pendingOwner;
// Set the new contract owner.
owner = pendingOwner;
// Clear the pendingOwner.
pendingOwner = address(0);
emit NewOwner(oldOwner, owner);
emit NewPendingOwner(oldPendingOwner, pendingOwner);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.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 {
using SafeMathUpgradeable for uint256;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
uint256 public totalSupply;
string public name;
string public symbol;
uint8 public decimals;
/**
* @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 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.
*/
function __ERC20_init(
string memory name_,
string memory symbol_,
uint8 decimals_
) internal {
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @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(msg.sender, 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(msg.sender, 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, msg.sender, allowance[sender][msg.sender].sub(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(
msg.sender,
spender,
allowance[msg.sender][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(
msg.sender,
spender,
allowance[msg.sender][spender].sub(subtractedValue)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
balanceOf[sender] = balanceOf[sender].sub(amount);
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");
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");
balanceOf[account] = balanceOf[account].sub(amount);
totalSupply = totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance if caller is not the `account`.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller other than `msg.sender` must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function _burnFrom(address account, uint256 amount) internal virtual {
if (msg.sender != account)
_approve(
account,
msg.sender,
allowance[account][msg.sender].sub(amount)
);
_burn(account, 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");
allowance[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
uint256[50] private __gap;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title dForce Lending Protocol's InterestRateModel Interface.
* @author dForce Team.
*/
interface IInterestRateModelInterface {
function isInterestRateModel() external view returns (bool);
/**
* @dev Calculates the current borrow interest rate per block.
* @param cash The total amount of cash the market has.
* @param borrows The total amount of borrows the market has.
* @param reserves The total amnount of reserves the market has.
* @return The borrow rate per block (as a percentage, and scaled by 1e18).
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @dev Calculates the current supply interest rate per block.
* @param cash The total amount of cash the market has.
* @param borrows The total amount of borrows the market has.
* @param reserves The total amnount of reserves the market has.
* @param reserveRatio The current reserve factor the market has.
* @return The supply rate per block (as a percentage, and scaled by 1e18).
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveRatio
) external view returns (uint256);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IControllerAdminInterface {
/// @notice Emitted when an admin supports a market
event MarketAdded(
address iToken,
uint256 collateralFactor,
uint256 borrowFactor,
uint256 supplyCapacity,
uint256 borrowCapacity,
uint256 distributionFactor
);
function _addMarket(
address _iToken,
uint256 _collateralFactor,
uint256 _borrowFactor,
uint256 _supplyCapacity,
uint256 _borrowCapacity,
uint256 _distributionFactor
) external;
/// @notice Emitted when new price oracle is set
event NewPriceOracle(address oldPriceOracle, address newPriceOracle);
function _setPriceOracle(address newOracle) external;
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(
uint256 oldCloseFactorMantissa,
uint256 newCloseFactorMantissa
);
function _setCloseFactor(uint256 newCloseFactorMantissa) external;
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(
uint256 oldLiquidationIncentiveMantissa,
uint256 newLiquidationIncentiveMantissa
);
function _setLiquidationIncentive(uint256 newLiquidationIncentiveMantissa)
external;
/// @notice Emitted when iToken's collateral factor is changed by admin
event NewCollateralFactor(
address iToken,
uint256 oldCollateralFactorMantissa,
uint256 newCollateralFactorMantissa
);
function _setCollateralFactor(
address iToken,
uint256 newCollateralFactorMantissa
) external;
/// @notice Emitted when iToken's borrow factor is changed by admin
event NewBorrowFactor(
address iToken,
uint256 oldBorrowFactorMantissa,
uint256 newBorrowFactorMantissa
);
function _setBorrowFactor(address iToken, uint256 newBorrowFactorMantissa)
external;
/// @notice Emitted when iToken's borrow capacity is changed by admin
event NewBorrowCapacity(
address iToken,
uint256 oldBorrowCapacity,
uint256 newBorrowCapacity
);
function _setBorrowCapacity(address iToken, uint256 newBorrowCapacity)
external;
/// @notice Emitted when iToken's supply capacity is changed by admin
event NewSupplyCapacity(
address iToken,
uint256 oldSupplyCapacity,
uint256 newSupplyCapacity
);
function _setSupplyCapacity(address iToken, uint256 newSupplyCapacity)
external;
/// @notice Emitted when pause guardian is changed by admin
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
function _setPauseGuardian(address newPauseGuardian) external;
/// @notice Emitted when mint is paused/unpaused by admin or pause guardian
event MintPaused(address iToken, bool paused);
function _setMintPaused(address iToken, bool paused) external;
function _setAllMintPaused(bool paused) external;
/// @notice Emitted when redeem is paused/unpaused by admin or pause guardian
event RedeemPaused(address iToken, bool paused);
function _setRedeemPaused(address iToken, bool paused) external;
function _setAllRedeemPaused(bool paused) external;
/// @notice Emitted when borrow is paused/unpaused by admin or pause guardian
event BorrowPaused(address iToken, bool paused);
function _setBorrowPaused(address iToken, bool paused) external;
function _setAllBorrowPaused(bool paused) external;
/// @notice Emitted when transfer is paused/unpaused by admin or pause guardian
event TransferPaused(bool paused);
function _setTransferPaused(bool paused) external;
/// @notice Emitted when seize is paused/unpaused by admin or pause guardian
event SeizePaused(bool paused);
function _setSeizePaused(bool paused) external;
function _setiTokenPaused(address iToken, bool paused) external;
function _setProtocolPaused(bool paused) external;
event NewRewardDistributor(
address oldRewardDistributor,
address _newRewardDistributor
);
function _setRewardDistributor(address _newRewardDistributor) external;
}
interface IControllerPolicyInterface {
function beforeMint(
address iToken,
address account,
uint256 mintAmount
) external;
function afterMint(
address iToken,
address minter,
uint256 mintAmount,
uint256 mintedAmount
) external;
function beforeRedeem(
address iToken,
address redeemer,
uint256 redeemAmount
) external;
function afterRedeem(
address iToken,
address redeemer,
uint256 redeemAmount,
uint256 redeemedAmount
) external;
function beforeBorrow(
address iToken,
address borrower,
uint256 borrowAmount
) external;
function afterBorrow(
address iToken,
address borrower,
uint256 borrowedAmount
) external;
function beforeRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function afterRepayBorrow(
address iToken,
address payer,
address borrower,
uint256 repayAmount
) external;
function beforeLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external;
function afterLiquidateBorrow(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 repaidAmount,
uint256 seizedAmount
) external;
function beforeSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizeAmount
) external;
function afterSeize(
address iTokenBorrowed,
address iTokenCollateral,
address liquidator,
address borrower,
uint256 seizedAmount
) external;
function beforeTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function afterTransfer(
address iToken,
address from,
address to,
uint256 amount
) external;
function beforeFlashloan(
address iToken,
address to,
uint256 amount
) external;
function afterFlashloan(
address iToken,
address to,
uint256 amount
) external;
}
interface IControllerAccountEquityInterface {
function calcAccountEquity(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function liquidateCalculateSeizeTokens(
address iTokenBorrowed,
address iTokenCollateral,
uint256 actualRepayAmount
) external view returns (uint256);
}
interface IControllerAccountInterface {
function hasEnteredMarket(address account, address iToken)
external
view
returns (bool);
function getEnteredMarkets(address account)
external
view
returns (address[] memory);
/// @notice Emitted when an account enters a market
event MarketEntered(address iToken, address account);
function enterMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
function enterMarketFromiToken(address _account) external;
/// @notice Emitted when an account exits a market
event MarketExited(address iToken, address account);
function exitMarkets(address[] calldata iTokens)
external
returns (bool[] memory);
/// @notice Emitted when an account add a borrow asset
event BorrowedAdded(address iToken, address account);
/// @notice Emitted when an account remove a borrow asset
event BorrowedRemoved(address iToken, address account);
function hasBorrowed(address account, address iToken)
external
view
returns (bool);
function getBorrowedAssets(address account)
external
view
returns (address[] memory);
}
interface IControllerInterface is
IControllerAdminInterface,
IControllerPolicyInterface,
IControllerAccountEquityInterface,
IControllerAccountInterface
{
/**
* @notice Security checks when updating the comptroller of a market, always expect to return true.
*/
function isController() external view returns (bool);
/**
* @notice Return all of the iTokens
* @return The list of iToken addresses
*/
function getAlliTokens() external view returns (address[] memory);
/**
* @notice Check whether a iToken is listed in controller
* @param _iToken The iToken to check for
* @return true if the iToken is listed otherwise false
*/
function hasiToken(address _iToken) external view returns (bool);
}
|
Caller repays a borrow belonging to borrower. _borrower the account with the debt being payed off./
|
function repayBorrowBehalf(address _borrower)
external
payable
nonReentrant
tracksValue
settleInterest
{
_repayInternal(msg.sender, _borrower, msg.value);
if (openCash > 0) msg.sender.transfer(openCash);
}
| 1,586,292 |
pragma solidity ^0.4.13;
library SafeMath {
function sub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Basic {
uint public totalSupply;
address public owner; //owner
address public animator; //animator
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function commitDividend(address who) internal; // pays remaining dividend
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint);
function transferFrom(address from, address to, uint value);
function approve(address spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint;
mapping(address => uint) balances;
modifier onlyPayloadSize(uint size) {
assert(msg.data.length >= size + 4);
_;
}
/**
* @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, uint _value) onlyPayloadSize(2 * 32) {
commitDividend(msg.sender);
balances[msg.sender] = balances[msg.sender].sub(_value);
if(_to == address(this)) {
commitDividend(owner);
balances[owner] = balances[owner].add(_value);
Transfer(msg.sender, owner, _value);
}
else {
commitDividend(_to);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
}
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) 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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) {
var _allowance = allowed[_from][msg.sender];
commitDividend(_from);
commitDividend(_to);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) {
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
assert(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than 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 uint specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @title SmartBillions contract
*/
contract SmartBillions is StandardToken {
// metadata
string public constant name = "SmartBillions Token";
string public constant symbol = "PLAY";
uint public constant decimals = 0;
// contract state
struct Wallet {
uint208 balance; // current balance of user
uint16 lastDividendPeriod; // last processed dividend period of user's tokens
uint32 nextWithdrawBlock; // next withdrawal possible after this block number
}
mapping (address => Wallet) wallets;
struct Bet {
uint192 value; // bet size
uint32 betHash; // selected numbers
uint32 blockNum; // blocknumber when lottery runs
}
mapping (address => Bet) bets;
uint public walletBalance = 0; // sum of funds in wallets
// investment parameters
uint public investStart = 1; // investment start block, 0: closed, 1: preparation
uint public investBalance = 0; // funding from investors
uint public investBalanceMax = 200000 ether; // maximum funding
uint public dividendPeriod = 1;
uint[] public dividends; // dividens collected per period, growing array
// betting parameters
uint public maxWin = 0; // maximum prize won
uint public hashFirst = 0; // start time of building hashes database
uint public hashLast = 0; // last saved block of hashes
uint public hashNext = 0; // next available bet block.number
uint public hashBetSum = 0; // used bet volume of next block
uint public hashBetMax = 5 ether; // maximum bet size per block
uint[] public hashes; // space for storing lottery results
// constants
//uint public constant hashesSize = 1024 ; // DEBUG ONLY !!!
uint public constant hashesSize = 16384 ; // 30 days of blocks
uint public coldStoreLast = 0 ; // block of last cold store transfer
// events
event LogBet(address indexed player, uint bethash, uint blocknumber, uint betsize);
event LogLoss(address indexed player, uint bethash, uint hash);
event LogWin(address indexed player, uint bethash, uint hash, uint prize);
event LogInvestment(address indexed investor, address indexed partner, uint amount);
event LogRecordWin(address indexed player, uint amount);
event LogLate(address indexed player,uint playerBlockNumber,uint currentBlockNumber);
event LogDividend(address indexed investor, uint amount, uint period);
modifier onlyOwner() {
assert(msg.sender == owner);
_;
}
modifier onlyAnimator() {
assert(msg.sender == animator);
_;
}
// constructor
function SmartBillions() {
owner = msg.sender;
animator = msg.sender;
wallets[owner].lastDividendPeriod = uint16(dividendPeriod);
dividends.push(0); // not used
dividends.push(0); // current dividend
}
/* getters */
/**
* @dev Show length of allocated swap space
*/
function hashesLength() constant external returns (uint) {
return uint(hashes.length);
}
/**
* @dev Show balance of wallet
* @param _owner The address of the account.
*/
function walletBalanceOf(address _owner) constant external returns (uint) {
return uint(wallets[_owner].balance);
}
/**
* @dev Show last dividend period processed
* @param _owner The address of the account.
*/
function walletPeriodOf(address _owner) constant external returns (uint) {
return uint(wallets[_owner].lastDividendPeriod);
}
/**
* @dev Show block number when withdraw can continue
* @param _owner The address of the account.
*/
function walletBlockOf(address _owner) constant external returns (uint) {
return uint(wallets[_owner].nextWithdrawBlock);
}
/**
* @dev Show bet size.
* @param _owner The address of the player.
*/
function betValueOf(address _owner) constant external returns (uint) {
return uint(bets[_owner].value);
}
/**
* @dev Show block number of lottery run for the bet.
* @param _owner The address of the player.
*/
function betHashOf(address _owner) constant external returns (uint) {
return uint(bets[_owner].betHash);
}
/**
* @dev Show block number of lottery run for the bet.
* @param _owner The address of the player.
*/
function betBlockNumberOf(address _owner) constant external returns (uint) {
return uint(bets[_owner].blockNum);
}
/**
* @dev Print number of block till next expected dividend payment
*/
function dividendsBlocks() constant external returns (uint) {
if(investStart > 0) {
return(0);
}
uint period = (block.number - hashFirst) / (10 * hashesSize);
if(period > dividendPeriod) {
return(0);
}
return((10 * hashesSize) - ((block.number - hashFirst) % (10 * hashesSize)));
}
/* administrative functions */
/**
* @dev Change owner.
* @param _who The address of new owner.
*/
function changeOwner(address _who) external onlyOwner {
assert(_who != address(0));
commitDividend(msg.sender);
commitDividend(_who);
owner = _who;
}
/**
* @dev Change animator.
* @param _who The address of new animator.
*/
function changeAnimator(address _who) external onlyAnimator {
assert(_who != address(0));
commitDividend(msg.sender);
commitDividend(_who);
animator = _who;
}
/**
* @dev Set ICO Start block.
* @param _when The block number of the ICO.
*/
function setInvestStart(uint _when) external onlyOwner {
require(investStart == 1 && hashFirst > 0 && block.number < _when);
investStart = _when;
}
/**
* @dev Set maximum bet size per block
* @param _maxsum The maximum bet size in wei.
*/
function setBetMax(uint _maxsum) external onlyOwner {
hashBetMax = _maxsum;
}
/**
* @dev Reset bet size accounting, to increase bet volume above safe limits
*/
function resetBet() external onlyOwner {
hashNext = block.number + 3;
hashBetSum = 0;
}
/**
* @dev Move funds to cold storage
* @dev investBalance and walletBalance is protected from withdraw by owner
* @dev if funding is > 50% admin can withdraw only 0.25% of balance weakly
* @param _amount The amount of wei to move to cold storage
*/
function coldStore(uint _amount) external onlyOwner {
houseKeeping();
require(_amount > 0 && this.balance >= (investBalance * 9 / 10) + walletBalance + _amount);
if(investBalance >= investBalanceMax / 2){ // additional jackpot protection
require((_amount <= this.balance / 400) && coldStoreLast + 4 * 60 * 24 * 7 <= block.number);
}
msg.sender.transfer(_amount);
coldStoreLast = block.number;
}
/**
* @dev Move funds to contract jackpot
*/
function hotStore() payable external {
houseKeeping();
}
/* housekeeping functions */
/**
* @dev Update accounting
*/
function houseKeeping() public {
if(investStart > 1 && block.number >= investStart + (hashesSize * 5)){ // ca. 14 days
investStart = 0; // start dividend payments
}
else {
if(hashFirst > 0){
uint period = (block.number - hashFirst) / (10 * hashesSize );
if(period > dividends.length - 2) {
dividends.push(0);
}
if(period > dividendPeriod && investStart == 0 && dividendPeriod < dividends.length - 1) {
dividendPeriod++;
}
}
}
}
/* payments */
/**
* @dev Pay balance from wallet
*/
function payWallet() public {
if(wallets[msg.sender].balance > 0 && wallets[msg.sender].nextWithdrawBlock <= block.number){
uint balance = wallets[msg.sender].balance;
wallets[msg.sender].balance = 0;
walletBalance -= balance;
pay(balance);
}
}
function pay(uint _amount) private {
uint maxpay = this.balance / 2;
if(maxpay >= _amount) {
msg.sender.transfer(_amount);
if(_amount > 1 finney) {
houseKeeping();
}
}
else {
uint keepbalance = _amount - maxpay;
walletBalance += keepbalance;
wallets[msg.sender].balance += uint208(keepbalance);
wallets[msg.sender].nextWithdrawBlock = uint32(block.number + 4 * 60 * 24 * 30); // wait 1 month for more funds
msg.sender.transfer(maxpay);
}
}
/* investment functions */
/**
* @dev Buy tokens
*/
function investDirect() payable external {
invest(owner);
}
/**
* @dev Buy tokens with affiliate partner
* @param _partner Affiliate partner
*/
function invest(address _partner) payable public {
//require(fromUSA()==false); // fromUSA() not yet implemented :-(
require(investStart > 1 && block.number < investStart + (hashesSize * 5) && investBalance < investBalanceMax);
uint investing = msg.value;
if(investing > investBalanceMax - investBalance) {
investing = investBalanceMax - investBalance;
investBalance = investBalanceMax;
investStart = 0; // close investment round
msg.sender.transfer(msg.value.sub(investing)); // send back funds immediately
}
else{
investBalance += investing;
}
if(_partner == address(0) || _partner == owner){
walletBalance += investing / 10;
wallets[owner].balance += uint208(investing / 10);} // 10% for marketing if no affiliates
else{
walletBalance += (investing * 5 / 100) * 2;
wallets[owner].balance += uint208(investing * 5 / 100); // 5% initial marketing funds
wallets[_partner].balance += uint208(investing * 5 / 100);} // 5% for affiliates
wallets[msg.sender].lastDividendPeriod = uint16(dividendPeriod); // assert(dividendPeriod == 1);
uint senderBalance = investing / 10**15;
uint ownerBalance = investing * 16 / 10**17 ;
uint animatorBalance = investing * 10 / 10**17 ;
balances[msg.sender] += senderBalance;
balances[owner] += ownerBalance ; // 13% of shares go to developers
balances[animator] += animatorBalance ; // 8% of shares go to animator
totalSupply += senderBalance + ownerBalance + animatorBalance;
Transfer(address(0),msg.sender,senderBalance); // for etherscan
Transfer(address(0),owner,ownerBalance); // for etherscan
Transfer(address(0),animator,animatorBalance); // for etherscan
LogInvestment(msg.sender,_partner,investing);
}
/**
* @dev Delete all tokens owned by sender and return unpaid dividends and 90% of initial investment
*/
function disinvest() external {
require(investStart == 0);
commitDividend(msg.sender);
uint initialInvestment = balances[msg.sender] * 10**15;
Transfer(msg.sender,address(0),balances[msg.sender]); // for etherscan
delete balances[msg.sender]; // totalSupply stays the same, investBalance is reduced
investBalance -= initialInvestment;
wallets[msg.sender].balance += uint208(initialInvestment * 9 / 10);
payWallet();
}
/**
* @dev Pay unpaid dividends
*/
function payDividends() external {
require(investStart == 0);
commitDividend(msg.sender);
payWallet();
}
/**
* @dev Commit remaining dividends before transfer of tokens
*/
function commitDividend(address _who) internal {
uint last = wallets[_who].lastDividendPeriod;
if((balances[_who]==0) || (last==0)){
wallets[_who].lastDividendPeriod=uint16(dividendPeriod);
return;
}
if(last==dividendPeriod) {
return;
}
uint share = balances[_who] * 0xffffffff / totalSupply;
uint balance = 0;
for(;last<dividendPeriod;last++) {
balance += share * dividends[last];
}
balance = (balance / 0xffffffff);
walletBalance += balance;
wallets[_who].balance += uint208(balance);
wallets[_who].lastDividendPeriod = uint16(last);
LogDividend(_who,balance,last);
}
/* lottery functions */
function betPrize(Bet _player, uint24 _hash) constant private returns (uint) { // house fee 13.85%
uint24 bethash = uint24(_player.betHash);
uint24 hit = bethash ^ _hash;
uint24 matches =
((hit & 0xF) == 0 ? 1 : 0 ) +
((hit & 0xF0) == 0 ? 1 : 0 ) +
((hit & 0xF00) == 0 ? 1 : 0 ) +
((hit & 0xF000) == 0 ? 1 : 0 ) +
((hit & 0xF0000) == 0 ? 1 : 0 ) +
((hit & 0xF00000) == 0 ? 1 : 0 );
if(matches == 6){
return(uint(_player.value) * 7000000);
}
if(matches == 5){
return(uint(_player.value) * 20000);
}
if(matches == 4){
return(uint(_player.value) * 500);
}
if(matches == 3){
return(uint(_player.value) * 25);
}
if(matches == 2){
return(uint(_player.value) * 3);
}
return(0);
}
/**
* @dev Check if won in lottery
*/
function betOf(address _who) constant external returns (uint) {
Bet memory player = bets[_who];
if( (player.value==0) ||
(player.blockNum<=1) ||
(block.number<player.blockNum) ||
(block.number>=player.blockNum + (10 * hashesSize))){
return(0);
}
if(block.number<player.blockNum+256){
return(betPrize(player,uint24(block.blockhash(player.blockNum))));
}
if(hashFirst>0){
uint32 hash = getHash(player.blockNum);
if(hash == 0x1000000) { // load hash failed :-(, return funds
return(uint(player.value));
}
else{
return(betPrize(player,uint24(hash)));
}
}
return(0);
}
/**
* @dev Check if won in lottery
*/
function won() public {
Bet memory player = bets[msg.sender];
if(player.blockNum==0){ // create a new player
bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1});
return;
}
if((player.value==0) || (player.blockNum==1)){
payWallet();
return;
}
require(block.number>player.blockNum); // if there is an active bet, throw()
if(player.blockNum + (10 * hashesSize) <= block.number){ // last bet too long ago, lost !
LogLate(msg.sender,player.blockNum,block.number);
bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1});
return;
}
uint prize = 0;
uint32 hash = 0;
if(block.number<player.blockNum+256){
hash = uint24(block.blockhash(player.blockNum));
prize = betPrize(player,uint24(hash));
}
else {
if(hashFirst>0){ // lottery is open even before swap space (hashes) is ready, but player must collect results within 256 blocks after run
hash = getHash(player.blockNum);
if(hash == 0x1000000) { // load hash failed :-(, return funds
prize = uint(player.value);
}
else{
prize = betPrize(player,uint24(hash));
}
}
else{
LogLate(msg.sender,player.blockNum,block.number);
bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1});
return();
}
}
bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1});
if(prize>0) {
LogWin(msg.sender,uint(player.betHash),uint(hash),prize);
if(prize > maxWin){
maxWin = prize;
LogRecordWin(msg.sender,prize);
}
pay(prize);
}
else{
LogLoss(msg.sender,uint(player.betHash),uint(hash));
}
}
/**
* @dev Send ether to buy tokens during ICO
* @dev or send less than 1 ether to contract to play
* @dev or send 0 to collect prize
*/
function () payable external {
if(msg.value > 0){
if(investStart>1){ // during ICO payment to the contract is treated as investment
invest(owner);
}
else{ // if not ICO running payment to contract is treated as play
play();
}
return;
}
//check for dividends and other assets
if(investStart == 0 && balances[msg.sender]>0){
commitDividend(msg.sender);}
won(); // will run payWallet() if nothing else available
}
/**
* @dev Play in lottery
*/
function play() payable public returns (uint) {
return playSystem(uint(sha3(msg.sender,block.number)), address(0));
}
/**
* @dev Play in lottery with random numbers
* @param _partner Affiliate partner
*/
function playRandom(address _partner) payable public returns (uint) {
return playSystem(uint(sha3(msg.sender,block.number)), _partner);
}
/**
* @dev Play in lottery with own numbers
* @param _partner Affiliate partner
*/
function playSystem(uint _hash, address _partner) payable public returns (uint) {
won(); // check if player did not win
uint24 bethash = uint24(_hash);
require(msg.value <= 1 ether && msg.value < hashBetMax);
if(msg.value > 0){
if(investStart==0) { // dividends only after investment finished
dividends[dividendPeriod] += msg.value / 20; // 5% dividend
}
if(_partner != address(0)) {
uint fee = msg.value / 100;
walletBalance += fee;
wallets[_partner].balance += uint208(fee); // 1% for affiliates
}
if(hashNext < block.number + 3) {
hashNext = block.number + 3;
hashBetSum = msg.value;
}
else{
if(hashBetSum > hashBetMax) {
hashNext++;
hashBetSum = msg.value;
}
else{
hashBetSum += msg.value;
}
}
bets[msg.sender] = Bet({value: uint192(msg.value), betHash: uint32(bethash), blockNum: uint32(hashNext)});
LogBet(msg.sender,uint(bethash),hashNext,msg.value);
}
putHash(); // players help collecing data
return(hashNext);
}
/* database functions */
/**
* @dev Create hash data swap space
* @param _sadd Number of hashes to add (<=256)
*/
function addHashes(uint _sadd) public returns (uint) {
require(hashFirst == 0 && _sadd > 0 && _sadd <= hashesSize);
uint n = hashes.length;
if(n + _sadd > hashesSize){
hashes.length = hashesSize;
}
else{
hashes.length += _sadd;
}
for(;n<hashes.length;n++){ // make sure to burn gas
hashes[n] = 1;
}
if(hashes.length>=hashesSize) { // assume block.number > 10
hashFirst = block.number - ( block.number % 10);
hashLast = hashFirst;
}
return(hashes.length);
}
/**
* @dev Create hash data swap space, add 128 hashes
*/
function addHashes128() external returns (uint) {
return(addHashes(128));
}
function calcHashes(uint32 _lastb, uint32 _delta) constant private returns (uint) {
return( ( uint(block.blockhash(_lastb )) & 0xFFFFFF )
| ( ( uint(block.blockhash(_lastb+1)) & 0xFFFFFF ) << 24 )
| ( ( uint(block.blockhash(_lastb+2)) & 0xFFFFFF ) << 48 )
| ( ( uint(block.blockhash(_lastb+3)) & 0xFFFFFF ) << 72 )
| ( ( uint(block.blockhash(_lastb+4)) & 0xFFFFFF ) << 96 )
| ( ( uint(block.blockhash(_lastb+5)) & 0xFFFFFF ) << 120 )
| ( ( uint(block.blockhash(_lastb+6)) & 0xFFFFFF ) << 144 )
| ( ( uint(block.blockhash(_lastb+7)) & 0xFFFFFF ) << 168 )
| ( ( uint(block.blockhash(_lastb+8)) & 0xFFFFFF ) << 192 )
| ( ( uint(block.blockhash(_lastb+9)) & 0xFFFFFF ) << 216 )
| ( ( uint(_delta) / hashesSize) << 240));
}
function getHash(uint _block) constant private returns (uint32) {
uint delta = (_block - hashFirst) / 10;
uint hash = hashes[delta % hashesSize];
if(delta / hashesSize != hash >> 240) {
return(0x1000000); // load failed, incorrect data in hashes
}
uint slotp = (_block - hashFirst) % 10;
return(uint32((hash >> (24 * slotp)) & 0xFFFFFF));
}
/**
* @dev Fill hash data
*/
function putHash() public returns (bool) {
uint lastb = hashLast;
if(lastb == 0 || block.number <= lastb + 10) {
return(false);
}
uint blockn256;
if(block.number<256) { // useless test for testnet :-(
blockn256 = 0;
}
else{
blockn256 = block.number - 256;
}
if(lastb < blockn256) {
uint num = blockn256;
num += num % 10;
lastb = num;
}
uint delta = (lastb - hashFirst) / 10;
hashes[delta % hashesSize] = calcHashes(uint32(lastb),uint32(delta));
hashLast = lastb + 10;
return(true);
}
/**
* @dev Fill hash data many times
* @param _num Number of iterations
*/
function putHashes(uint _num) external {
uint n=0;
for(;n<_num;n++){
if(!putHash()){
return;
}
}
}
}
|
Pay balance from wallet/
|
function payWallet() public {
if(wallets[msg.sender].balance > 0 && wallets[msg.sender].nextWithdrawBlock <= block.number){
uint balance = wallets[msg.sender].balance;
wallets[msg.sender].balance = 0;
walletBalance -= balance;
pay(balance);
}
}
| 2,111,693 |
./partial_match/4/0xe75E4014709ca05b816410b646F1B1C01e674901/sources/TimeswapPool.sol
|
force balances to match reserves
|
function skim(address _to) external override reentrancyLock() {
uint256 _assetBalance = _asset.balanceOf(address(this));
uint256 _collateralBalance = _collateral.balanceOf(address(this));
uint256 _assetOut = _assetBalance.subOrZero(uint256(assetReserve));
uint256 _collateralOut = _collateralBalance.subOrZero(
uint256(collateralReserve)
);
if (_assetOut > 0) _safeTransfer(_asset, _to, _assetOut);
if (_collateralOut > 0) _safeTransfer(_collateral, _to, _collateralOut);
}
| 8,531,520 |
/**
* @title TradingPairWhitelist
* @author Team 3301 <[email protected]>
* @dev TradingPairWhitelist contract that allows particular trading pairs available within the DEX. Whitelisting/unwhitelisting
* is controlled by operators in Operatorable contract which is initialized with the relevant BaseOperators address.
*/
pragma solidity 0.5.12;
import "../libraries/Bytes32Set.sol";
import "../role/trader/TraderOperatorable.sol";
contract TradingPairWhitelist is TraderOperatorable {
using Bytes32Set for Bytes32Set.Set;
Bytes32Set.Set internal pairs;
mapping(bytes32 => Pair) public pair;
mapping(address => mapping(address => bytes32)) public pairIdentifier;
struct Pair {
bool paired;
bool frozen;
address buyToken;
address sellToken;
}
event PairedTokens(bytes32 indexed pairID, address indexed buytoken, address indexed sellToken);
event DepairedTokens(bytes32 indexed pairID, address indexed buytoken, address indexed sellToken);
event FrozenPair(bytes32 indexed pairID);
event UnFrozenPair(bytes32 indexed pairID);
/**
* @dev Reverts if _buyToken and _sellToken are not paired.
* @param _buyToken buy token against sell token to determine if whitelisted pair or not.
* @param _sellToken sell token against buy token to determine if whitelisted pair or not.
*/
modifier onlyPaired(address _buyToken, address _sellToken) {
require(isPaired(_buyToken, _sellToken), "TradingPairWhitelist: pair is not whitelisted");
_;
}
/**
* @dev Reverts if _buyToken and _sellToken are frozen.
* @param _buyToken buy token against sell token to determine if frozen pair or not.
* @param _sellToken sell token against buy token to determine if frozen pair or not.
*/
modifier whenNotFrozen(address _buyToken, address _sellToken) {
require(!isFrozen(_buyToken, _sellToken), "TradingPairWhitelist: pair is frozen");
_;
}
/**
* @dev Getter to determine if pairs are whitelisted.
* @param _buyToken buy token against sell token to determine if whitelisted pair or not.
* @param _sellToken sell token against buy token to determine if whitelisted pair or not.
* @return bool is whitelisted pair.
*/
function isPaired(address _buyToken, address _sellToken) public view returns (bool) {
return pair[pairIdentifier[_buyToken][_sellToken]].paired;
}
/**
* @dev Getter to determine if pairs are frozen.
* @param _buyToken buy token against sell token to determine if frozen pair or not.
* @param _sellToken sell token against buy token to determine if frozen pair or not.
* @return bool is frozen pair.
*/
function isFrozen(address _buyToken, address _sellToken) public view returns (bool) {
return pair[pairIdentifier[_buyToken][_sellToken]].frozen;
}
/**
* @dev Pair tokens to be available for trading on DEX.
* @param _pairID pair identifier.
* @param _buyToken buy token against sell token to whitelist.
* @param _sellToken sell token against buy token to whitelist.
*/
function pairTokens(
bytes32 _pairID,
address _buyToken,
address _sellToken
) public onlyOperator {
_pairTokens(_pairID, _buyToken, _sellToken);
}
/**
* @dev Depair tokens to be available for trading on DEX.
* @param _pairID pair identifier.
*/
function depairTokens(bytes32 _pairID) public onlyOperator {
_depairTokens(_pairID);
}
/**
* @dev Freeze pair trading on DEX.
* @param _pairID pair identifier.
*/
function freezePair(bytes32 _pairID) public onlyOperatorOrTraderOrSystem {
_freezePair(_pairID);
}
/**
* @dev Unfreeze pair trading on DEX.
* @param _pairID pair identifier.
*/
function unfreezePair(bytes32 _pairID) public onlyOperatorOrTraderOrSystem {
_unfreezePair(_pairID);
}
/**
* @dev Batch pair tokens.
* @param _pairID array of pairID.
* @param _buyToken address array of buyToken.
* @param _sellToken address array of buyToken.
*/
function batchPairTokens(
bytes32[] memory _pairID,
address[] memory _buyToken,
address[] memory _sellToken
) public onlyOperator {
require(_pairID.length <= 256, "TradingPairWhitelist: batch count is greater than 256");
require(
_pairID.length == _buyToken.length && _buyToken.length == _sellToken.length,
"TradingPairWhitelist: array lengths not equal"
);
for (uint256 i = 0; i < _buyToken.length; i++) {
_pairTokens(_pairID[i], _buyToken[i], _sellToken[i]);
}
}
/**
* @dev Batch depair tokens.
* @param _pairID array of pairID.
*/
function batchDepairTokens(bytes32[] memory _pairID) public onlyOperator {
require(_pairID.length <= 256, "TradingPairWhitelist: batch count is greater than 256");
for (uint256 i = 0; i < _pairID.length; i++) {
_depairTokens(_pairID[i]);
}
}
/**
* @dev Batch freeze tokens.
* @param _pairID array of pairID.
*/
function batchFreezeTokens(bytes32[] memory _pairID) public onlyOperatorOrTraderOrSystem {
require(_pairID.length <= 256, "TradingPairWhitelist: batch count is greater than 256");
for (uint256 i = 0; i < _pairID.length; i++) {
_freezePair(_pairID[i]);
}
}
/**
* @dev Batch unfreeze tokens.
* @param _pairID array of pairID.
*/
function batchUnfreezeTokens(bytes32[] memory _pairID) public onlyOperatorOrTraderOrSystem {
require(_pairID.length <= 256, "TradingPairWhitelist: batch count is greater than 256");
for (uint256 i = 0; i < _pairID.length; i++) {
_unfreezePair(_pairID[i]);
}
}
/**
* @return Amount of pairs.
*/
function getPairCount() public view returns (uint256) {
return pairs.count();
}
/**
* @return Key at index.
*/
function getIdentifier(uint256 _index) public view returns (bytes32) {
return pairs.keyAtIndex(_index);
}
/** INTERNAL FUNCTIONS */
function _pairTokens(
bytes32 _pairID,
address _buyToken,
address _sellToken
) internal {
require(_buyToken != address(0) && _sellToken != address(0), "TradingPairWhitelist: tokens cannot be empty");
require(_buyToken != _sellToken, "TradingPairWhitelist: buy and sell tokens cannot be the same");
require(!isPaired(_buyToken, _sellToken), "TradingPairWhitelist: tokens have already been paired");
require(!pairs.exists(_pairID), "TradingPairWhitelist: pair ID exists");
pair[_pairID] = Pair({paired: true, frozen: false, buyToken: _buyToken, sellToken: _sellToken});
pairs.insert(_pairID);
pairIdentifier[_buyToken][_sellToken] = _pairID;
emit PairedTokens(_pairID, _buyToken, _sellToken);
}
function _depairTokens(bytes32 _pairID) internal {
require(pairs.exists(_pairID), "TradingPairWhitelist: pair ID not does not exist");
Pair memory p = pair[_pairID];
delete pair[_pairID];
pairs.remove(_pairID);
delete pairIdentifier[p.buyToken][p.sellToken];
emit DepairedTokens(_pairID, p.buyToken, p.sellToken);
}
function _freezePair(bytes32 _pairID) internal {
require(pairs.exists(_pairID), "TradingPairWhitelist: pair ID not does not exist");
require(!pair[_pairID].frozen, "TradingPairWhitelist: token pair is frozen");
pair[_pairID].frozen = true;
emit FrozenPair(_pairID);
}
function _unfreezePair(bytes32 _pairID) internal {
require(pairs.exists(_pairID), "TradingPairWhitelist: pair ID not does not exist");
require(pair[_pairID].frozen, "TradingPairWhitelist: token pair is not frozen");
pair[_pairID].frozen = false;
emit UnFrozenPair(_pairID);
}
}
|
Batch depair tokens. _pairID array of pairID./
|
function batchDepairTokens(bytes32[] memory _pairID) public onlyOperator {
require(_pairID.length <= 256, "TradingPairWhitelist: batch count is greater than 256");
for (uint256 i = 0; i < _pairID.length; i++) {
_depairTokens(_pairID[i]);
}
}
| 7,245,825 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
contract AccessManager is AccessControlUpgradeable {
// clientManager
bytes32 public constant CREATE_CLIENT_ROLE =
keccak256("CREATE_CLIENT_ROLE");
bytes32 public constant UPGRADE_CLIENT_ROLE =
keccak256("UPGRADE_CLIENT_ROLE");
bytes32 public constant REGISTER_RELAYER_ROLE =
keccak256("REGISTER_RELAYER_ROLE");
// routing
bytes32 public constant SET_ROUTING_RULES_ROLE =
keccak256("SET_ROUTING_RULES_ROLE");
bytes32 public constant ADD_ROUTING_ROLE = keccak256("ADD_ROUTING_ROLE");
// transfer
bytes32 public constant ON_RECVPACKET_ROLE =
keccak256("ON_RECVPACKET_ROLE");
bytes32 public constant ON_ACKNOWLEDGEMENT_PACKET_ROLE =
keccak256("ON_ACKNOWLEDGEMENT_PACKET_ROLE");
// multi-signature contract address
address public multiSignWallet;
// check if caller is multi-signature contract address
modifier onlyMultiSignWallet() {
require(
msg.sender == multiSignWallet,
"caller not multi-signature contract address"
);
_;
}
function initialize(address _multiSignWallet) public initializer {
multiSignWallet = _multiSignWallet;
_setupRole(DEFAULT_ADMIN_ROLE, multiSignWallet);
// clientManager
_setupRole(CREATE_CLIENT_ROLE, _multiSignWallet);
_setupRole(UPGRADE_CLIENT_ROLE, _multiSignWallet);
_setupRole(REGISTER_RELAYER_ROLE, _multiSignWallet);
// routing
_setupRole(SET_ROUTING_RULES_ROLE, _multiSignWallet);
_setupRole(ADD_ROUTING_ROLE, _multiSignWallet);
// transfer
_setupRole(ON_RECVPACKET_ROLE, _multiSignWallet);
_setupRole(ON_ACKNOWLEDGEMENT_PACKET_ROLE, _multiSignWallet);
}
/**
* @notice dynamically add roles through multi-signature contract addresses
* @param role role
* @param account the address corresponding to the role
*/
function addRole(bytes32 role, address account)
external
onlyMultiSignWallet
{
_setupRole(role, account);
}
/**
* @notice authorize a designated role to an address through a multi-signature contract address
* @param role role
* @param account authorized address
*/
function grantRole(bytes32 role, address account)
public
override
onlyMultiSignWallet
{
super.grantRole(role, account);
}
/**
* @notice cancel the authorization to assign a role to a certain address through the multi-signature contract address
* @param role role
* @param account deauthorized address
*/
function revokeRole(bytes32 role, address account)
public
override
onlyMultiSignWallet
{
super.revokeRole(role, account);
}
/**
* @notice dynamically add roles through multi-signature contract addresses
* @param roles collection of roles
* @param accounts collection of accounts
*/
function batchAddRole(bytes32[] calldata roles, address[] calldata accounts)
external
onlyMultiSignWallet
{
require(
roles.length == accounts.length,
"batchAdd: roles and accounts length mismatch"
);
for (uint256 i = 0; i < roles.length; ++i) {
_setupRole(roles[i], accounts[i]);
}
}
/**
* @notice volume authorization, roles and addresses need to be one-to-one correspondence
* @param roles collection of roles
* @param accounts collection of accounts
*/
function batchGrantRole(bytes32[] calldata roles, address[] calldata accounts)
external
onlyMultiSignWallet
{
require(
roles.length == accounts.length,
"batchGrant: roles and accounts length mismatch"
);
for (uint256 i = 0; i < roles.length; ++i) {
super.grantRole(roles[i], accounts[i]);
}
}
/**
* @notice batch deauthorization, roles and addresses need to be one-to-one correspondence
* @param roles collection of roles
* @param accounts collection of accounts
*/
function batchRevokeRole(bytes32[] calldata roles, address[] calldata accounts)
external
onlyMultiSignWallet
{
require(
roles.length == accounts.length,
"batchRevoke: roles and accounts length mismatch"
);
for (uint256 i = 0; i < roles.length; ++i) {
super.revokeRole(roles[i], accounts[i]);
}
}
}
|
dynamically add roles through multi-signature contract addresses role role account the address corresponding to the role/
|
function addRole(bytes32 role, address account)
external
onlyMultiSignWallet
{
_setupRole(role, account);
}
| 908,780 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* __ __ _
* | \/ | ___ _ __ ___| |_ ___ _ __
* | |\/| |/ _ \| '_ \/ __| __/ _ \ '__|
* | | | | (_) | | | \__ \ || __/ |
* |_|__|_|\___/|_| |_|___/\__\___|_|_ _
* / ___| __ _| |_ ___ ___| |__ (_) |__ | | ___ ___
* \___ \ / _` | __/ _ \/ __| '_ \| | '_ \| |/ _ \/ __|
* ___) | (_| | || (_) \__ \ | | | | |_) | | __/\__ \
* |____/ \__,_|\__\___/|___/_| |_|_|_.__/|_|\___||___/
*
*/
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./ERC2981ContractWideRoyalties.sol";
import "./MerkleProof.sol";
/**
* @notice Original Satoshibles contract interface
*/
interface ISatoshible {
function ownerOf(
uint256 _tokenId
)
external
view
returns (address owner);
}
/**
* @title Monster Satoshibles
* @notice NFT of monsters that can be burned and combined into prime monsters!
* @author Aaron Hanson
*/
contract MonsterSatoshible is ERC721, ERC2981ContractWideRoyalties, Ownable {
/// The max token supply
uint256 public constant MAX_SUPPLY = 6666;
/// The presale portion of the max supply
uint256 public constant MAX_PRESALE_SUPPLY = 3333;
/// Mysterious constants 💀
uint256 constant DEATH = 0xDEAD;
uint256 constant LIFE = 0x024350AC;
uint256 constant ALPHA = LIFE % DEATH * 1000;
uint256 constant OMEGA = LIFE % DEATH + ALPHA;
/// Prime types
uint256 constant FRANKENSTEIN = 0;
uint256 constant WEREWOLF = 1;
uint256 constant VAMPIRE = 2;
uint256 constant ZOMBIE = 3;
uint256 constant INVALID = 4;
/// Number of prime parts
uint256 constant NUM_PARTS = 4;
/// Bitfield mask for prime part detection during prime minting
uint256 constant HAS_ALL_PARTS = 2 ** NUM_PARTS - 1;
/// Merkle root summarizing the presale whitelist
bytes32 public constant WHITELIST_MERKLE_ROOT =
0xdb6eea27a6a35a02d1928e9582f75c1e0a518ad5992b5cfee9cc0d86fb387b8d;
/// Additional team wallets (can withdraw)
address public constant TEAM_WALLET_A =
0xF746362D8162Eeb3624c17654FFAa6EB8bD71820;
address public constant TEAM_WALLET_B =
0x16659F9D2ab9565B0c07199687DE3634c0965391;
address public constant TEAM_WALLET_C =
0x7a73f770873761054ab7757E909ae48f771379D4;
address public constant TEAM_WALLET_D =
0xB7c7e3809591F720f3a75Fb3efa05E76E6B7B92A;
/// The maximum ERC-2981 royalties percentage
uint256 public constant MAX_ROYALTIES_PCT = 600;
/// Original Satoshibles contract instance
ISatoshible public immutable SATOSHIBLE_CONTRACT;
/// The max presale token ID
uint256 public immutable MAX_PRESALE_TOKEN_ID;
/// The current token supply
uint256 public totalSupply;
/// The current state of the sale
bool public saleIsActive;
/// Indicates if the public sale was opened manually
bool public publicSaleOpenedEarly;
/// The default and discount token prices in wei
uint256 public tokenPrice = 99900000000000000; // 0.0999 ether
uint256 public discountPrice = 66600000000000000; // 0.0666 ether
/// Tracks number of presale mints already used per address
mapping(address => uint256) public whitelistMintsUsed;
/// The current state of the laboratory
bool public laboratoryHasElectricity;
/// Merkle root summarizing all monster IDs and their prime parts
bytes32 public primePartsMerkleRoot;
/// The provenance URI
string public provenanceURI = "Not Yet Set";
/// When true, the provenanceURI can no longer be changed
bool public provenanceUriLocked;
/// The base URI
string public baseURI = "https://api.satoshibles.com/monsters/token/";
/// When true, the baseURI can no longer be changed
bool public baseUriLocked;
/// Use Counters for token IDs
using Counters for Counters.Counter;
/// Monster token ID counter
Counters.Counter monsterIds;
/// Prime token ID counter for each prime type
mapping(uint256 => Counters.Counter) primeIds;
/// Prime ID offsets for each prime type
mapping(uint256 => uint256) primeIdOffset;
/// Bitfields that track original Satoshibles already used for discounts
mapping(uint256 => uint256) satDiscountBitfields;
/// Bitfields that track original Satoshibles already used in lab
mapping(uint256 => uint256) satLabBitfields;
/**
* @notice Emitted when the saleIsActive flag changes
* @param isActive Indicates whether or not the sale is now active
*/
event SaleStateChanged(
bool indexed isActive
);
/**
* @notice Emitted when the public sale is opened early
*/
event PublicSaleOpenedEarly();
/**
* @notice Emitted when the laboratoryHasElectricity flag changes
* @param hasElectricity Indicates whether or not the laboratory is open
*/
event LaboratoryStateChanged(
bool indexed hasElectricity
);
/**
* @notice Emitted when a prime is created in the lab
* @param creator The account that created the prime
* @param primeId The ID of the prime created
* @param satId The Satoshible used as the 'key' to the lab
* @param monsterIdsBurned The IDs of the monsters burned
*/
event PrimeCreated(
address indexed creator,
uint256 indexed primeId,
uint256 indexed satId,
uint256[4] monsterIdsBurned
);
/**
* @notice Requires the specified Satoshible to be owned by msg.sender
* @param _satId Original Satoshible token ID
*/
modifier onlySatHolder(
uint256 _satId
) {
require(
SATOSHIBLE_CONTRACT.ownerOf(_satId) == _msgSender(),
"Sat not owned"
);
_;
}
/**
* @notice Requires msg.sender to be the owner or a team wallet
*/
modifier onlyTeam() {
require(
_msgSender() == TEAM_WALLET_A
|| _msgSender() == TEAM_WALLET_B
|| _msgSender() == TEAM_WALLET_C
|| _msgSender() == TEAM_WALLET_D
|| _msgSender() == owner(),
"Not owner or team address"
);
_;
}
/**
* @notice Boom... Let's go!
* @param _initialBatchCount Number of tokens to mint to msg.sender
* @param _immutableSatoshible Original Satoshible contract address
* @param _royaltiesPercentage Initial royalties percentage for ERC-2981
*/
constructor(
uint256 _initialBatchCount,
address _immutableSatoshible,
uint256 _royaltiesPercentage
)
ERC721("Monster Satoshibles", "MSBLS")
{
SATOSHIBLE_CONTRACT = ISatoshible(
_immutableSatoshible
);
require(
_royaltiesPercentage <= MAX_ROYALTIES_PCT,
"Royalties too high"
);
_setRoyalties(
_msgSender(),
_royaltiesPercentage
);
_initializePrimeIdOffsets();
_initializeSatDiscountAvailability();
_initializeSatLabAvailability();
_mintTokens(_initialBatchCount);
require(
belowMaximum(_initialBatchCount, MAX_PRESALE_SUPPLY,
MAX_SUPPLY
) == true,
"Would exceed max supply"
);
unchecked {
MAX_PRESALE_TOKEN_ID = _initialBatchCount + MAX_PRESALE_SUPPLY;
}
}
/**
* @notice Mints monster tokens during presale, optionally with discounts
* @param _numberOfTokens Number of tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
* @param _whitelistedTokens Account's total number of whitelisted tokens
* @param _proof Merkle proof to be verified
*/
function mintTokensPresale(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount,
uint256 _whitelistedTokens,
bytes32[] calldata _proof
)
external
payable
{
require(
publicSaleOpenedEarly == false,
"Presale has ended"
);
require(
belowMaximum(monsterIds.current(), _numberOfTokens,
MAX_PRESALE_TOKEN_ID
) == true,
"Would exceed presale size"
);
require(
belowMaximum(whitelistMintsUsed[_msgSender()], _numberOfTokens,
_whitelistedTokens
) == true,
"Would exceed whitelisted count"
);
require(
verifyWhitelisted(_msgSender(), _whitelistedTokens,
_proof
) == true,
"Invalid whitelist proof"
);
whitelistMintsUsed[_msgSender()] += _numberOfTokens;
_doMintTokens(
_numberOfTokens,
_satsForDiscount
);
}
/**
* @notice Mints monsters during public sale, optionally with discounts
* @param _numberOfTokens Number of monster tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
*/
function mintTokensPublicSale(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount
)
external
payable
{
require(
publicSaleOpened() == true,
"Public sale has not started"
);
require(
belowMaximum(monsterIds.current(), _numberOfTokens,
MAX_SUPPLY
) == true,
"Not enough tokens left"
);
_doMintTokens(
_numberOfTokens,
_satsForDiscount
);
}
/**
* @notice Mints a prime token by burning two or more monster tokens
* @param _primeType Prime type to mint
* @param _satId Original Satoshible token ID to use as 'key' to the lab
* @param _monsterIds Array of monster token IDs to potentially be burned
* @param _monsterPrimeParts Array of bitfields of monsters' prime parts
* @param _proofs Array of merkle proofs to be verified
*/
function mintPrimeToken(
uint256 _primeType,
uint256 _satId,
uint256[] calldata _monsterIds,
uint256[] calldata _monsterPrimeParts,
bytes32[][] calldata _proofs
)
external
onlySatHolder(_satId)
{
require(
laboratoryHasElectricity == true,
"Prime laboratory not yet open"
);
require(
_primeType < INVALID,
"Invalid prime type"
);
require(
belowMaximum(
primeIdOffset[_primeType],
primeIds[_primeType].current() + 1,
primeIdOffset[_primeType + 1]
) == true,
"No more primes left of this type"
);
require(
satIsAvailableForLab(_satId) == true,
"Sat has already been used in lab"
);
// bitfield tracking aggregate parts across monsters
// (head = 1, eyes = 2, mouth = 4, body = 8)
uint256 combinedParts;
uint256[4] memory burnedIds;
unchecked {
uint256 burnedIndex;
for (uint256 i = 0; i < _monsterIds.length; i++) {
require(
verifyMonsterPrimeParts(
_monsterIds[i],
_monsterPrimeParts[i],
_proofs[i]
) == true,
"Invalid monster traits proof"
);
uint256 theseParts = _monsterPrimeParts[i]
>> (_primeType * NUM_PARTS) & HAS_ALL_PARTS;
if (combinedParts | theseParts != combinedParts) {
_burn(
_monsterIds[i]
);
burnedIds[burnedIndex++] = _monsterIds[i];
combinedParts |= theseParts;
if (combinedParts == HAS_ALL_PARTS) {
break;
}
}
}
}
require(
combinedParts == HAS_ALL_PARTS,
"Not enough parts for this prime"
);
_retireSatFromLab(_satId);
primeIds[_primeType].increment();
unchecked {
uint256 primeId = primeIdOffset[_primeType]
+ primeIds[_primeType].current();
totalSupply++;
_safeMint(
_msgSender(),
primeId
);
emit PrimeCreated(
_msgSender(),
primeId,
_satId,
burnedIds
);
}
}
/**
* @notice Activates or deactivates the sale
* @param _isActive Whether to activate or deactivate the sale
*/
function activateSale(
bool _isActive
)
external
onlyOwner
{
saleIsActive = _isActive;
emit SaleStateChanged(
_isActive
);
}
/**
* @notice Starts the public sale before MAX_PRESALE_TOKEN_ID is minted
*/
function openPublicSaleEarly()
external
onlyOwner
{
publicSaleOpenedEarly = true;
emit PublicSaleOpenedEarly();
}
/**
* @notice Modifies the prices in case of major ETH price changes
* @param _tokenPrice The new default token price
* @param _discountPrice The new discount token price
*/
function updateTokenPrices(
uint256 _tokenPrice,
uint256 _discountPrice
)
external
onlyOwner
{
require(
_tokenPrice >= _discountPrice,
"discountPrice cannot be larger"
);
require(
saleIsActive == false,
"Sale is active"
);
tokenPrice = _tokenPrice;
discountPrice = _discountPrice;
}
/**
* @notice Sets primePartsMerkleRoot summarizing all monster prime parts
* @param _merkleRoot The new merkle root
*/
function setPrimePartsMerkleRoot(
bytes32 _merkleRoot
)
external
onlyOwner
{
primePartsMerkleRoot = _merkleRoot;
}
/**
* @notice Turns the laboratory on or off
* @param _hasElectricity Whether to turn the laboratory on or off
*/
function electrifyLaboratory(
bool _hasElectricity
)
external
onlyOwner
{
laboratoryHasElectricity = _hasElectricity;
emit LaboratoryStateChanged(
_hasElectricity
);
}
/**
* @notice Mints the final prime token
*/
function mintFinalPrime()
external
onlyOwner
{
require(
_exists(OMEGA) == false,
"Final prime already exists"
);
unchecked {
totalSupply++;
}
_safeMint(
_msgSender(),
OMEGA
);
}
/**
* @notice Sets the provenance URI
* @param _newProvenanceURI The new provenance URI
*/
function setProvenanceURI(
string calldata _newProvenanceURI
)
external
onlyOwner
{
require(
provenanceUriLocked == false,
"Provenance URI has been locked"
);
provenanceURI = _newProvenanceURI;
}
/**
* @notice Prevents further changes to the provenance URI
*/
function lockProvenanceURI()
external
onlyOwner
{
provenanceUriLocked = true;
}
/**
* @notice Sets a new base URI
* @param _newBaseURI The new base URI
*/
function setBaseURI(
string calldata _newBaseURI
)
external
onlyOwner
{
require(
baseUriLocked == false,
"Base URI has been locked"
);
baseURI = _newBaseURI;
}
/**
* @notice Prevents further changes to the base URI
*/
function lockBaseURI()
external
onlyOwner
{
baseUriLocked = true;
}
/**
* @notice Withdraws sale proceeds
* @param _amount Amount to withdraw in wei
*/
function withdraw(
uint256 _amount
)
external
onlyTeam
{
payable(_msgSender()).transfer(
_amount
);
}
/**
* @notice Withdraws any other tokens
* @dev WARNING: Double check token is legit before calling this
* @param _token Contract address of token
* @param _to Address to which to withdraw
* @param _amount Amount to withdraw
* @param _hasVerifiedToken Must be true (sanity check)
*/
function withdrawOther(
address _token,
address _to,
uint256 _amount,
bool _hasVerifiedToken
)
external
onlyOwner
{
require(
_hasVerifiedToken == true,
"Need to verify token"
);
IERC20(_token).transfer(
_to,
_amount
);
}
/**
* @notice Sets token royalties (ERC-2981)
* @param _recipient Recipient of the royalties
* @param _value Royalty percentage (using 2 decimals - 10000 = 100, 0 = 0)
*/
function setRoyalties(
address _recipient,
uint256 _value
)
external
onlyOwner
{
require(
_value <= MAX_ROYALTIES_PCT,
"Royalties too high"
);
_setRoyalties(
_recipient,
_value
);
}
/**
* @notice Checks which Satoshibles can still be used for a discounted mint
* @dev Uses bitwise operators to find the bit representing each Satoshible
* @param _satIds Array of original Satoshible token IDs
* @return Token ID for each of the available _satIds, zero otherwise
*/
function satsAvailableForDiscountMint(
uint256[] calldata _satIds
)
external
view
returns (uint256[] memory)
{
uint256[] memory satsAvailable = new uint256[](_satIds.length);
unchecked {
for (uint256 i = 0; i < _satIds.length; i++) {
if (satIsAvailableForDiscountMint(_satIds[i])) {
satsAvailable[i] = _satIds[i];
}
}
}
return satsAvailable;
}
/**
* @notice Checks which Satoshibles can still be used to mint a prime
* @dev Uses bitwise operators to find the bit representing each Satoshible
* @param _satIds Array of original Satoshible token IDs
* @return Token ID for each of the available _satIds, zero otherwise
*/
function satsAvailableForLab(
uint256[] calldata _satIds
)
external
view
returns (uint256[] memory)
{
uint256[] memory satsAvailable = new uint256[](_satIds.length);
unchecked {
for (uint256 i = 0; i < _satIds.length; i++) {
if (satIsAvailableForLab(_satIds[i])) {
satsAvailable[i] = _satIds[i];
}
}
}
return satsAvailable;
}
/**
* @notice Checks if a Satoshible can still be used for a discounted mint
* @dev Uses bitwise operators to find the bit representing the Satoshible
* @param _satId Original Satoshible token ID
* @return isAvailable True if _satId can be used for a discounted mint
*/
function satIsAvailableForDiscountMint(
uint256 _satId
)
public
view
returns (bool isAvailable)
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
isAvailable = satDiscountBitfields[page] >> shift & 1 == 1;
}
}
/**
* @notice Checks if a Satoshible can still be used to mint a prime
* @dev Uses bitwise operators to find the bit representing the Satoshible
* @param _satId Original Satoshible token ID
* @return isAvailable True if _satId can still be used to mint a prime
*/
function satIsAvailableForLab(
uint256 _satId
)
public
view
returns (bool isAvailable)
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
isAvailable = satLabBitfields[page] >> shift & 1 == 1;
}
}
/**
* @notice Verifies a merkle proof for a monster ID and its prime parts
* @param _monsterId Monster token ID
* @param _monsterPrimeParts Bitfield of the monster's prime parts
* @param _proof Merkle proof be verified
* @return isVerified True if the merkle proof is verified
*/
function verifyMonsterPrimeParts(
uint256 _monsterId,
uint256 _monsterPrimeParts,
bytes32[] calldata _proof
)
public
view
returns (bool isVerified)
{
bytes32 node = keccak256(
abi.encodePacked(
_monsterId,
_monsterPrimeParts
)
);
isVerified = MerkleProof.verify(
_proof,
primePartsMerkleRoot,
node
);
}
/**
* @notice Gets total count of existing prime tokens for a prime type
* @param _primeType Prime type
* @return supply Count of existing prime tokens for this prime type
*/
function primeSupply(
uint256 _primeType
)
public
view
returns (uint256 supply)
{
supply = primeIds[_primeType].current();
}
/**
* @notice Gets total count of existing prime tokens
* @return supply Count of existing prime tokens
*/
function totalPrimeSupply()
public
view
returns (uint256 supply)
{
unchecked {
supply = primeSupply(FRANKENSTEIN)
+ primeSupply(WEREWOLF)
+ primeSupply(VAMPIRE)
+ primeSupply(ZOMBIE)
+ (_exists(OMEGA) ? 1 : 0);
}
}
/**
* @notice Gets total count of monsters burned
* @return burned Count of monsters burned
*/
function monstersBurned()
public
view
returns (uint256 burned)
{
unchecked {
burned = monsterIds.current() + totalPrimeSupply() - totalSupply;
}
}
/**
* @notice Gets state of public sale
* @return publicSaleIsOpen True if public sale phase has begun
*/
function publicSaleOpened()
public
view
returns (bool publicSaleIsOpen)
{
publicSaleIsOpen =
publicSaleOpenedEarly == true ||
monsterIds.current() >= MAX_PRESALE_TOKEN_ID;
}
/// @inheritdoc ERC165
function supportsInterface(
bytes4 _interfaceId
)
public
view
override (ERC721, ERC2981Base)
returns (bool doesSupportInterface)
{
doesSupportInterface = super.supportsInterface(_interfaceId);
}
/**
* @notice Verifies a merkle proof for an account's whitelisted tokens
* @param _account Account to verify
* @param _whitelistedTokens Number of whitelisted tokens for _account
* @param _proof Merkle proof to be verified
* @return isVerified True if the merkle proof is verified
*/
function verifyWhitelisted(
address _account,
uint256 _whitelistedTokens,
bytes32[] calldata _proof
)
public
pure
returns (bool isVerified)
{
bytes32 node = keccak256(
abi.encodePacked(
_account,
_whitelistedTokens
)
);
isVerified = MerkleProof.verify(
_proof,
WHITELIST_MERKLE_ROOT,
node
);
}
/**
* @dev Base monster burning function
* @param _tokenId Monster token ID to burn
*/
function _burn(
uint256 _tokenId
)
internal
override
{
require(
_isApprovedOrOwner(_msgSender(), _tokenId) == true,
"not owner nor approved"
);
unchecked {
totalSupply -= 1;
}
super._burn(
_tokenId
);
}
/**
* @dev Base URI for computing tokenURI
* @return Base URI string
*/
function _baseURI()
internal
view
override
returns (string memory)
{
return baseURI;
}
/**
* @dev Base monster minting function, calculates price with discounts
* @param _numberOfTokens Number of monster tokens to mint
* @param _satsForDiscount Array of Satoshible IDs for discounted mints
*/
function _doMintTokens(
uint256 _numberOfTokens,
uint256[] calldata _satsForDiscount
)
private
{
require(
saleIsActive == true,
"Sale must be active"
);
require(
_numberOfTokens >= 1,
"Need at least 1 token"
);
require(
_numberOfTokens <= 50,
"Max 50 at a time"
);
require(
_satsForDiscount.length <= _numberOfTokens,
"Too many sats for discount"
);
unchecked {
uint256 discountIndex;
for (; discountIndex < _satsForDiscount.length; discountIndex++) {
_useSatForDiscountMint(_satsForDiscount[discountIndex]);
}
uint256 totalPrice = tokenPrice * (_numberOfTokens - discountIndex)
+ discountPrice * discountIndex;
require(
totalPrice == msg.value,
"Ether amount not correct"
);
}
_mintTokens(
_numberOfTokens
);
}
/**
* @dev Base monster minting function.
* @param _numberOfTokens Number of monster tokens to mint
*/
function _mintTokens(
uint256 _numberOfTokens
)
private
{
unchecked {
totalSupply += _numberOfTokens;
for (uint256 i = 0; i < _numberOfTokens; i++) {
monsterIds.increment();
_safeMint(
_msgSender(),
monsterIds.current()
);
}
}
}
/**
* @dev Marks a Satoshible ID as having been used for a discounted mint
* @param _satId Satoshible ID that was used for a discounted mint
*/
function _useSatForDiscountMint(
uint256 _satId
)
private
onlySatHolder(_satId)
{
require(
satIsAvailableForDiscountMint(_satId) == true,
"Sat for discount already used"
);
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
satDiscountBitfields[page] &= ~(1 << shift);
}
}
/**
* @dev Marks a Satoshible ID as having been used to mint a prime
* @param _satId Satoshible ID that was used to mint a prime
*/
function _retireSatFromLab(
uint256 _satId
)
private
{
unchecked {
uint256 page = _satId / 256;
uint256 shift = _satId % 256;
satLabBitfields[page] &= ~(1 << shift);
}
}
/**
* @dev Initializes prime token ID offsets
*/
function _initializePrimeIdOffsets()
private
{
unchecked {
primeIdOffset[FRANKENSTEIN] = ALPHA;
primeIdOffset[WEREWOLF] = ALPHA + 166;
primeIdOffset[VAMPIRE] = ALPHA + 332;
primeIdOffset[ZOMBIE] = ALPHA + 498;
primeIdOffset[INVALID] = ALPHA + 665;
}
}
/**
* @dev Initializes bitfields of Satoshibles available for discounted mints
*/
function _initializeSatDiscountAvailability()
private
{
unchecked {
for (uint256 i = 0; i < 20; i++) {
satDiscountBitfields[i] = type(uint256).max;
}
}
}
/**
* @dev Initializes bitfields of Satoshibles available to mint primes
*/
function _initializeSatLabAvailability()
private
{
unchecked {
for (uint256 i = 0; i < 20; i++) {
satLabBitfields[i] = type(uint256).max;
}
}
}
/**
* @dev Helper function used for token ID range checks when minting
* @param _currentValue Current token ID counter value
* @param _incrementValue Number of tokens to increment by
* @param _maximumValue Maximum token ID value allowed
* @return isBelowMaximum True if _maximumValue is not exceeded
*/
function belowMaximum(
uint256 _currentValue,
uint256 _incrementValue,
uint256 _maximumValue
)
private
pure
returns (bool isBelowMaximum)
{
unchecked {
isBelowMaximum = _currentValue + _incrementValue <= _maximumValue;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
library MerkleProof {
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
)
internal
pure
returns (bool)
{
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./ERC2981Base.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
/// @dev This implementation has the same royalties for each and every tokens
abstract contract ERC2981ContractWideRoyalties is ERC2981Base {
RoyaltyInfo private _royalties;
/// @dev Sets token royalties
/// @param _recipient recipient of the royalties
/// @param _value percentage (using 2 decimals - 10000 = 100, 0 = 0)
function _setRoyalties(
address _recipient,
uint256 _value
)
internal
{
require(_value <= 10000, "ERC2981Royalties: Too high");
_royalties = RoyaltyInfo(_recipient, uint24(_value));
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(
uint256,
uint256 _value
)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
RoyaltyInfo memory royalties = _royalties;
receiver = royalties.recipient;
royaltyAmount = (_value * royalties.amount) / 10000;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./IERC2981Royalties.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
abstract contract ERC2981Base is ERC165, IERC2981Royalties {
struct RoyaltyInfo {
address recipient;
uint24 amount;
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(IERC2981Royalties).interfaceId ||
super.supportsInterface(interfaceId);
}
}
// 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;
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
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
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// 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;
}
}
// 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;
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
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;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// 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 "../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() {
_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);
}
}
|
Prevents further changes to the base URI/
|
function lockBaseURI()
external
onlyOwner
{
baseUriLocked = true;
}
| 7,321,221 |
// SPDX-License-Identifier: MIT
// pragma abicoder v2;
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
pragma solidity ^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;
}
}
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/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
using SafeMath for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
event OperationResult(bool result);
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return _owners[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;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721URIStorage: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(
_exists(tokenId),
"ERC721URIStorage: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// File: @openzeppelin/contracts/security/Pausable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract 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());
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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 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);
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721Burnable: caller is not owner nor approved"
);
_burn(tokenId);
}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721)
returns (bool)
{
return
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721.balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721Enumerable.totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @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)
external
view
returns (bytes4 magicValue);
}
pragma solidity ^0.8.0;
// NFTLocker smart contract inherits ERC721 interface
contract NFTLocker is
ERC721,
ERC721Enumerable,
ERC721URIStorage,
Pausable,
Ownable,
ERC721Burnable
{
// using Counters for Counters.Counter;
using SafeMath for uint256;
// this contract's token collection name
string public collectionName;
// this contract's token symbol
string public collectionNameSymbol;
// Counters.Counter private _tokenIds;
// artist address
address public artistAddress = 0x0fbcc5C7f6692Dde7EBAa65508c61fd49F831Ab3;
// royaltyFee percentage
uint256 public constant royaltyFee = 10;
uint256 public NFTCounter;
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURIextended;
// define Door NFT struct
struct DoorNFT {
bool forSale;
uint256 tokenId;
uint256 price;
uint256 numberOfTransfers;
string tokenName;
string tokenURI;
address payable previousOwner;
address payable currentOwner;
}
// map doorNFT's token id to Door NFT
mapping(uint256 => DoorNFT) public allDoorNFTs;
// check if token name exists
mapping(string => bool) public tokenNameExists;
// check if token URI exists
mapping(string => bool) public tokenURIExists;
// initialize contract while deployment with contract's collection name and token
constructor() ERC721("NFTLocker", "NFTL") {
collectionName = name();
collectionNameSymbol = symbol();
}
// event definitions go here
event Mint(address indexed _from, uint256 _id, uint256 _value);
event Sales(address indexed _from, address indexed _to, uint256 _value);
event PriceChange(uint256 _tokenId, uint256 _prevPrice, uint256 _newPrice);
event SalesChange(uint256 _tokenId, bool _isOpened);
event RoyaltyPay(address indexed _from, address indexed _to, uint256 _value);
// mint a new Door NFT
function mintDoorNFT(
string memory _name,
string memory _tokenURI,
uint256 _price
) external onlyOwner {
// require caller of the function is not an empty address
require(msg.sender != address(0));
// increase the NFT counter
NFTCounter++;
// check if tokenID already exists
require(!_exists(NFTCounter));
// check if tokenURI already exists
require(!tokenURIExists[_tokenURI]);
// check if tokenName already exists
require(!tokenNameExists[_name]);
// _tokenIds.increment();
// uint256 NFTCounter = _tokenIds.current();
// Mint
_safeMint(msg.sender, NFTCounter);
_setTokenURI(NFTCounter, _tokenURI);
tokenURIExists[_tokenURI] = true;
tokenNameExists[_name] = true;
// map new DoorNFT
allDoorNFTs[NFTCounter] = DoorNFT({
forSale: false,
tokenId: NFTCounter,
price: _price,
numberOfTransfers: 0,
tokenName: _name,
tokenURI: _tokenURI,
previousOwner: payable(msg.sender),
currentOwner: payable(msg.sender)
});
// emit mint event
emit Mint(msg.sender, NFTCounter, _price);
}
// withdraw value
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success);
}
// get owner of the token
function getTokenOwner(uint256 _tokenId) public view returns (address) {
address _tokenOwner = ownerOf(_tokenId);
return _tokenOwner;
}
// get metadata of the token
function getTokenMetaData(uint256 _tokenId)
public
view
returns (string memory)
{
string memory tokenMetaData = tokenURI(_tokenId);
return tokenMetaData;
}
// get token price
function getTokenPrice(uint256 _tokenId) external view returns (uint256) {
DoorNFT memory doorNFT = allDoorNFTs[_tokenId];
return doorNFT.price;
}
// get total number of tokens minted so far
function getNumberOfTokensMinted() public view returns (uint256) {
uint256 totalNumberOfTokensMinted = totalSupply();
return totalNumberOfTokensMinted;
}
// get total number of tokens owned by an address
function getTotalNumberOfTokensOwnedByAnAddress(address _owner)
public
view
returns (uint256)
{
uint256 totalNumberOfTokensOwned = balanceOf(_owner);
return totalNumberOfTokensOwned;
}
// check if the token already exists
function getTokenExists(uint256 _tokenId) public view returns (bool) {
bool tokenExists = _exists(_tokenId);
return tokenExists;
}
// get token info by token id
function getTokenInfo(uint256 _tokenId) public view returns (DoorNFT memory){
require(_exists(_tokenId));
return allDoorNFTs[_tokenId];
}
// buy a token by passing in the token's id
function buyToken(uint256 _tokenId) public payable {
// require caller of the function is not an empty address
require(msg.sender != address(0));
// require _tokenId already exists
require(_exists(_tokenId));
address tokenOwner = ownerOf(_tokenId);
// require token owner is not an empty address
require(tokenOwner != address(0));
// require token owner is not sender
require(tokenOwner != msg.sender);
// get that token from all Door NFTs mapping and create a memory of it defined as (struct => DoorNFT)
DoorNFT memory doorNFT = allDoorNFTs[_tokenId];
// price sent in to buy should be equal to or more than the token's price
require(msg.value >= doorNFT.price);
// token should be for sale
require(doorNFT.forSale);
// transfer the token from owner to the caller of the function (buyer)
_transfer(tokenOwner, msg.sender, _tokenId);
// get owner of the token
address payable sendTo = doorNFT.currentOwner;
// send token's worth of ethers to the owner and artist
uint256 fee = msg.value.div(100).mul(royaltyFee);
uint256 value = msg.value.sub(fee);
sendTo.transfer(value);
_widthdraw(artistAddress, fee);
// emit royalty paid event
emit RoyaltyPay(msg.sender, artistAddress, fee);
// update the token's prev owner
doorNFT.previousOwner = sendTo;
// update the token's current owner
doorNFT.currentOwner = payable(msg.sender);
// update the how many times this token was transfered
doorNFT.numberOfTransfers += 1;
// lock the NFT for sale
doorNFT.forSale = false;
// set and update that token in the mapping
allDoorNFTs[_tokenId] = doorNFT;
// emit Transfer event when successful
emit Sales(doorNFT.previousOwner, doorNFT.currentOwner, msg.value);
}
// set artist account address
function changeArtistAddress(address _artist) public onlyOwner {
// require caller of the function is not an empty address
require(_artist == address(0));
artistAddress = _artist;
}
// change NFT price
function changeTokenPrice(uint256 _tokenId, uint256 _newPrice) public {
// require caller of the function is not an empty address
require(msg.sender != address(0));
// require that token should exist
require(_exists(_tokenId));
// get the token's owner
address tokenOwner = ownerOf(_tokenId);
// check that token's owner should be equal to the caller of the function
require(tokenOwner == msg.sender);
// get that token from all Door NFTs mapping and create a memory of it defined as (struct => DoorNFT)
DoorNFT memory doorNFT = allDoorNFTs[_tokenId];
uint256 prevPrice = doorNFT.price;
// update token's price with new price
doorNFT.price = _newPrice;
// set and update that token in the mapping
allDoorNFTs[_tokenId] = doorNFT;
// emit event
emit PriceChange(_tokenId, prevPrice, _newPrice);
}
// switch between set for sale and set not for sale
function toggleForSale(uint256 _tokenId, bool _isOpened) public {
// require caller of the function is not an empty address
require(msg.sender != address(0));
// require that token should exist
require(_exists(_tokenId));
// get the token's owner
address tokenOwner = ownerOf(_tokenId);
// check that token's owner should be equal to the caller of the function
require(tokenOwner == msg.sender);
// get that token from all Door NFTs mapping and create a memory of it defined as (struct => DoorNFT)
DoorNFT memory doorNFT = allDoorNFTs[_tokenId];
// set token's forSale
doorNFT.forSale = _isOpened;
// set and update that token in the mapping
allDoorNFTs[_tokenId] = doorNFT;
// emit event
emit SalesChange(_tokenId, doorNFT.forSale);
}
// following functions must be override by solidity
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(_from, _to, _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 supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(_interfaceId);
}
}
|
buy a token by passing in the token's id require caller of the function is not an empty address require _tokenId already exists require token owner is not an empty address require token owner is not sender get that token from all Door NFTs mapping and create a memory of it defined as (struct => DoorNFT) price sent in to buy should be equal to or more than the token's price token should be for sale transfer the token from owner to the caller of the function (buyer) get owner of the token send token's worth of ethers to the owner and artist emit royalty paid event update the token's prev owner update the token's current owner update the how many times this token was transfered lock the NFT for sale set and update that token in the mapping emit Transfer event when successful
|
function buyToken(uint256 _tokenId) public payable {
require(msg.sender != address(0));
require(_exists(_tokenId));
address tokenOwner = ownerOf(_tokenId);
require(tokenOwner != address(0));
require(tokenOwner != msg.sender);
DoorNFT memory doorNFT = allDoorNFTs[_tokenId];
require(msg.value >= doorNFT.price);
require(doorNFT.forSale);
_transfer(tokenOwner, msg.sender, _tokenId);
address payable sendTo = doorNFT.currentOwner;
uint256 fee = msg.value.div(100).mul(royaltyFee);
uint256 value = msg.value.sub(fee);
sendTo.transfer(value);
_widthdraw(artistAddress, fee);
emit RoyaltyPay(msg.sender, artistAddress, fee);
doorNFT.previousOwner = sendTo;
doorNFT.currentOwner = payable(msg.sender);
doorNFT.numberOfTransfers += 1;
doorNFT.forSale = false;
allDoorNFTs[_tokenId] = doorNFT;
emit Sales(doorNFT.previousOwner, doorNFT.currentOwner, msg.value);
}
| 5,842,594 |
pragma solidity ^0.5.8;
/**
*
* Manages game startup routines such as initialization and card dtorage for a single CypherPoker hand (round).
* Most data operations are done on an external PokerHandData contract.
*
* (C)opyright 2016 to 2017
*
* This source code is protected by copyright and distributed under license.
* Please see the root LICENSE file for terms and conditions.
*
*/
contract PokerHandStartup {
address public owner; //the contract's owner / publisher
/**
* Contract constructor.
*/
constructor() public {
owner = msg.sender;
}
/**
* Anonymous fallback function.
*/
function () external {
revert();
}
/**
* Attempts to initialize a PokerHandData contract.
*
* @param requiredPlayers The players required to agree to the contract before further interaction is allowed. The first player is considered the
* dealer.
* @param primeVal The shared prime modulus on which plaintext card values are based and from which encryption/decryption keys are derived.
* @param baseCardVal The value of the base or first card of the plaintext deck. The next 51 ascending quadratic residues modulo primeVal are assumed to
* comprise the remainder of the deck (see "getCardIndex" for calculations).
* @param buyInVal The exact per-player buy-in value, in wei, that must be sent when agreeing to the contract. Must be greater than 0.
* @param timeoutBlocksVal The number of blocks that elapse between the current block and lastActionBlock before the current valid player is
* considered to have timed / dropped out if they haven't committed a valid action. A minimum of 2 blocks (roughly 24 seconds), is imposed but
* a slightly higher value is highly recommended.
* @param dataAddr The address of PokerHandData contract to initialize.
*
*/
function initialize(address[] memory requiredPlayers, uint256 primeVal, uint256 baseCardVal, uint256 buyInVal, uint timeoutBlocksVal, address dataAddr) public {
PokerHandData handData = PokerHandData (dataAddr);
if (handData.initReady() == false) {
revert();
}
if (requiredPlayers.length < 2) {
revert();
}
if (primeVal < 2) {
revert();
}
if (buyInVal == 0) {
revert();
}
if (timeoutBlocksVal < 12) {
timeoutBlocksVal = 12;
}
handData.set_pot(0);
handData.set_betPosition(0);
handData.set_complete (false);
handData.new_players(requiredPlayers);
handData.set_lastActionBlock(0);
handData.initialize(primeVal, baseCardVal, buyInVal, timeoutBlocksVal);
}
/**
* Resets the poker hand data contract so that it becomes available for re-use. Typically this function only needs to be used
* when the data contract has been used in "full" mode (i.e. the game writes most of its data to the contract).
*
* The contract's 'complete' flag must be set to true prior to calling this function otherwise an exception is throw.
*
* @param dataAddr The address of the PokerHandData contract to reset.
*/
function reset(address dataAddr) public {
PokerHandData dataContract = PokerHandData(dataAddr);
if (dataContract.complete() == false) {
revert();
}
uint256[] memory emptySet;
for (uint count=0; count < dataContract.num_Players(); count++) {
dataContract.set_agreed(dataContract.players(count), false);
dataContract.set_playerBets(dataContract.players(count), 0);
dataContract.set_playerChips(dataContract.players(count), 0);
dataContract.set_playerHasBet(dataContract.players(count), false);
dataContract.remove_playerKeys(dataContract.players(count));
dataContract.set_encryptedDeck(dataContract.players(count), emptySet);
dataContract.set_privateCards(dataContract.players(count), emptySet);
dataContract.set_publicDecryptCards(dataContract.players(count), emptySet);
dataContract.set_result(dataContract.players(count), 0);
dataContract.set_validationIndex(dataContract.players(count), 0);
dataContract.add_declaredWinner(dataContract.players(count), address(0));
}
dataContract.set_bigBlindHasBet(false);
dataContract.set_pot(0);
dataContract.set_betPosition(0);
dataContract.clear_winner();
dataContract.set_lastActionBlock(0);
dataContract.set_privateDecryptCards(msg.sender, emptySet, address(0));
dataContract.set_publicCards(msg.sender, emptySet);
dataContract.set_complete(false);
address[] memory emptyAddrSet;
dataContract.new_players(emptyAddrSet); //clears players list and sets initReady to true (so call last)
}
/**
* Stores up to 52 encrypted cards of a full deck for a player. The player must have been specified during initialization, must have agreed,
* and must be at phase 1. This function may be invoked multiple times by the same player during the encryption phase if transactions need
* to be broken up into smaler units.
*
* @param dataAddr The address of a data contract that has authorized this contract to communicate.
* @param cards The encrypted card values to store. Once 52 cards (and only 52 cards) have been stored the player's phase is updated.
*/
function storeEncryptedDeck(address dataAddr, uint256[] memory cards) public {
PokerHandData dataStorage = PokerHandData(dataAddr);
if (dataStorage.agreed(msg.sender) != true) {
revert();
}
if (dataStorage.phases(msg.sender) > 1) {
revert();
}
dataStorage.set_encryptedDeck(msg.sender, cards);
if (dataStorage.length_encryptedDeck(msg.sender) == 52) {
dataStorage.set_phase(msg.sender, 2);
}
dataStorage.set_lastActionBlock(block.number);
}
/**
* Stores up to 2 encrypted private or hole card selections for a player. The player must have been specified during initialization, must have agreed,
* and must be at phase 2. This function may be invoked multiple times by the same player during the encryption phase if transactions need
* to be broken up into smaler units.
*
* @param cards The encrypted card values to store. Once 2 cards (and only 2 cards) have been stored the player's phase is updated.
*/
function storePrivateCards(address dataAddr, uint256[] memory cards) public {
PokerHandData dataStorage = PokerHandData(dataAddr);
if (dataStorage.agreed(msg.sender) != true) {
revert();
}
if (dataStorage.phases(msg.sender) != 2) {
revert();
}
dataStorage.set_privateCards(msg.sender, cards);
if (dataStorage.num_PrivateCards(msg.sender) == 2) {
dataStorage.set_phase(msg.sender, 3);
}
dataStorage.set_lastActionBlock(block.number);
}
/**
* Stores up to 2 partially decrypted private or hole cards for a target player. Both sending and target players must have been specified during initialization,
* must have agreed, and target must be at phase 3. This function may be invoked multiple times by the same player during the private/hold card decryption phase if transactions need
* to be broken up into smaler units.
*
* @param cards The partially decrypted card values to store for the target player. Once 2 cards (and only 2 cards) have been stored by all other players for the target, the target's phase is
* updated to 4.
* @param targetAddr The address of the target player for whom the cards are being decrypted (the two cards are their private/hold cards).
*/
function storePrivateDecryptCards(address dataAddr, uint256[] memory cards, address targetAddr) public {
PokerHandData dataStorage = PokerHandData(dataAddr);
if (dataStorage.agreed(msg.sender) != true) {
revert();
}
if (dataStorage.agreed(targetAddr) != true) {
revert();
}
if (dataStorage.phases(targetAddr) != 3) {
revert();
}
dataStorage.set_privateDecryptCards(msg.sender, cards, targetAddr);
//Checks whether all partially decrypted cards for a specific target player have been stored
//by all other players.
uint cardGroupsStored = 0;
for (uint count=0; count < dataStorage.num_Players(); count++) {
if (dataStorage.num_PrivateDecryptCards(dataStorage.players(count), targetAddr) == 2) {
cardGroupsStored++;
}
}
//partially decrypted cards should be stored by all players except the target
if (cardGroupsStored == (dataStorage.num_Players() - 1)) {
dataStorage.set_phase(targetAddr, 4);
}
dataStorage.set_lastActionBlock(block.number);
}
/**
* Stores the encrypted public or community card(s) for the hand. Currently only the dealer may store public/community card
* selections to the contract.
*
* @param cards The encrypted public/community cards to store. The number of cards that may be stored depends on the
* current player phases (all players). Three cards are stored at phase 5 (in multiple invocations if desired), and one card is stored at
* phases 8 and 11.
*/
function storePublicCards(address dataAddr, uint256[] memory cards) public {
PokerHandData dataStorage = PokerHandData(dataAddr);
if (msg.sender != dataStorage.players(dataStorage.num_Players()-1)) {
//not the dealer
revert();
}
if (dataStorage.agreed(msg.sender) != true) {
revert();
}
if ((dataStorage.allPlayersAtPhase(5) == false) && (dataStorage.allPlayersAtPhase(8) == false) && (dataStorage.allPlayersAtPhase(11) == false)) {
revert();
}
if ((dataStorage.allPlayersAtPhase(5)) && ((cards.length + dataStorage.num_PublicCards()) > 3)) {
//at phase 5 we can store a maximum of 3 cards
revert();
}
if ((dataStorage.allPlayersAtPhase(5) == false) && (cards.length > 1)) {
//at valid phases above 5 we can store a maximum of 1 card
revert();
}
dataStorage.set_publicCards(msg.sender, cards);
if (dataStorage.num_PublicCards() > 2) {
//phases are incremented at 3, 4, and 5 cards
for (uint count=0; count < dataStorage.num_Players(); count++) {
dataStorage.set_phase(dataStorage.players(count), dataStorage.phases(dataStorage.players(count)) + 1);
}
}
dataStorage.set_lastActionBlock(block.number);
}
/**
* Stores up to 5 partially decrypted public or community cards from a target player. The player must must have agreed to the
* contract, and must be at phase 6, 9, or 12. Multiple invocations may be used to store cards during the multi-card
* phase (6) if desired.
*
* In order to correlate decryptions during subsequent rounds cards are stored at matching indexes for players involved.
* To illustrate this, in the following example players 1 and 2 decrypted the first three cards and players 2 and 3 decrypted the following
* two cards:
*
* publicDecryptCards(player 1) = [0x32] [0x22] [0x5A] [ 0x0] [ 0x0] <- partially decrypted only the first three cards
* publicDecryptCards(player 2) = [0x75] [0xF5] [0x9B] [0x67] [0xF1] <- partially decrypted all five cards
* publicDecryptCards(player 3) = [ 0x0] [ 0x0] [ 0x0] [0x1C] [0x22] <- partially decrypted only the last two cards
*
* The number of players involved in the partial decryption of any card at a specific index should be the total number of players minus one
* (players.length - 1), since the final decryption results in the fully decrypted card and therefore doesn't need to be stored.
*
* @param cards The partially decrypted card values to store. Three cards must be stored at phase 6, one card at phase 9, and one card
* at phase 12.
*/
function storePublicDecryptCards(address dataAddr, uint256[] memory cards) public {
PokerHandData dataStorage = PokerHandData(dataAddr);
if (dataStorage.agreed(msg.sender) != true) {
revert();
}
if ((dataStorage.phases(msg.sender) != 6) && (dataStorage.phases(msg.sender) != 9) && (dataStorage.phases(msg.sender) != 12)){
revert();
}
if ((dataStorage.phases(msg.sender) == 6) && (cards.length != 3)) {
revert();
}
if ((dataStorage.phases(msg.sender) != 6) && (cards.length != 1)) {
revert();
}
dataStorage.set_publicDecryptCards(msg.sender, cards);
(uint maxLength, uint playersAtMaxLength) = dataStorage.publicDecryptCardsInfo();
if (playersAtMaxLength == (dataStorage.num_Players()-1)) {
for (uint count=0; count < dataStorage.num_Players(); count++) {
dataStorage.set_phase(dataStorage.players(count), dataStorage.phases(dataStorage.players(count)) + 1);
}
}
}
}
contract PokerHandData {
struct Card {
uint index;
uint suit;
uint value;
}
struct CardGroup {
Card[] cards;
}
struct Key {
uint256 encKey;
uint256 decKey;
uint256 prime;
}
address public owner;
address[] public authorizedGameContracts;
uint public numAuthorizedContracts;
address[] public players;
uint256 public buyIn;
mapping (address => bool) public agreed;
uint256 public prime;
uint256 public baseCard;
mapping (address => uint256) public playerBets;
mapping (address => uint256) public playerChips;
mapping (address => bool) public playerHasBet;
bool public bigBlindHasBet;
uint256 public pot;
uint public betPosition;
mapping (address => uint256[52]) public encryptedDeck;
mapping (address => uint256[2]) public privateCards;
struct DecryptPrivateCardsStruct {
address sourceAddr;
address targetAddr;
uint256[2] cards;
}
DecryptPrivateCardsStruct[] public privateDecryptCards;
uint256[5] public publicCards;
mapping (address => uint256[5]) public publicDecryptCards;
mapping (address => Key[]) public playerKeys;
mapping (address => uint[5]) public playerBestHands;
mapping (address => Card[]) public playerCards;
mapping (address => uint256) public results;
mapping (address => address) public declaredWinner;
address[] public winner;
uint public lastActionBlock;
uint public timeoutBlocks;
uint public initBlock;
mapping (address => uint) public nonces;
mapping (address => uint) public validationIndex;
address public challenger;
bool public complete;
bool public initReady;
mapping (address => uint8) public phases;
// function PokerHandData() {}
function () external {}
modifier onlyAuthorized {
uint allowedContractsFound = 0;
for (uint count=0; count<authorizedGameContracts.length; count++) {
if (msg.sender == authorizedGameContracts[count]) {
allowedContractsFound++;
}
}
if (allowedContractsFound == 0) {
revert();
}
_;
}
function agreeToContract(uint256 nonce) payable public {}
function initialize(uint256 primeVal, uint256 baseCardVal, uint256 buyInVal, uint timeoutBlocksVal) public onlyAuthorized {}
function getPrivateDecryptCard(address sourceAddr, address targetAddr, uint cardIndex) view public returns (uint256) {}
function allPlayersAtPhase(uint phaseNum) public view returns (bool) {}
function num_Players() public view returns (uint) {}
function num_Keys(address target) public view returns (uint) {}
function num_PlayerCards(address target) public view returns (uint) {}
function num_PrivateCards(address targetAddr) public view returns (uint) {}
function num_PublicCards() public view returns (uint) {}
function num_PrivateDecryptCards(address sourceAddr, address targetAddr) public view returns (uint) {}
function num_winner() public view returns (uint) {}
function setAuthorizedGameContracts (address[] memory contractAddresses) public {}
function add_playerCard(address playerAddress, uint index, uint suit, uint value) public onlyAuthorized {}
function update_playerCard(address playerAddress, uint cardIndex, uint index, uint suit, uint value) public onlyAuthorized {}
function set_validationIndex(address playerAddress, uint index) public onlyAuthorized {}
function set_result(address playerAddress, uint256 result) public onlyAuthorized {}
function set_complete (bool completeSet) public onlyAuthorized {}
function set_publicCard (uint256 card, uint index) public onlyAuthorized {}
function set_encryptedDeck (address fromAddr, uint256[] memory cards) public onlyAuthorized {}
function set_privateCards (address fromAddr, uint256[] memory cards) public onlyAuthorized {}
function set_betPosition (uint betPositionVal) public onlyAuthorized {}
function set_bigBlindHasBet (bool bigBlindHasBetVal) public onlyAuthorized {}
function set_playerHasBet (address fromAddr, bool hasBet) public onlyAuthorized {}
function set_playerBets (address fromAddr, uint betVal) public onlyAuthorized {}
function set_playerChips (address forAddr, uint numChips) public onlyAuthorized {}
function set_pot (uint potVal) public onlyAuthorized {}
function set_agreed (address fromAddr, bool agreedVal) public onlyAuthorized {}
function add_winner (address winnerAddress) public onlyAuthorized {}
function clear_winner () public onlyAuthorized {}
function new_players (address[] memory newPlayers) public onlyAuthorized {}
function set_phase (address fromAddr, uint8 phaseNum) public onlyAuthorized {}
function set_lastActionBlock(uint blockNum) public onlyAuthorized {}
function set_privateDecryptCards (address fromAddr, uint256[] memory cards, address targetAddr) public onlyAuthorized {}
function set_publicCards (address fromAddr, uint256[] memory cards) public onlyAuthorized {}
function set_publicDecryptCards (address fromAddr, uint256[] memory cards) public onlyAuthorized {}
function add_declaredWinner(address fromAddr, address winnerAddr) public onlyAuthorized {}
function privateDecryptCardsIndex (address sourceAddr, address targetAddr) public onlyAuthorized returns (uint) {}
function set_playerBestHands(address fromAddr, uint cardIndex, uint256 card) public onlyAuthorized {}
function add_playerKeys(address fromAddr, uint256[] memory encKeys, uint256[] memory decKeys) public onlyAuthorized {}
function remove_playerKeys(address fromAddr) public onlyAuthorized {}
function set_challenger(address challengerAddr) public onlyAuthorized {}
function pay (address toAddr, uint amount) public onlyAuthorized returns (bool) {}
function publicDecryptCardsInfo() public view returns (uint maxLength, uint playersAtMaxLength) {}
function length_encryptedDeck(address fromAddr) public view returns (uint) {}
}
|
Stores the encrypted public or community card(s) for the hand. Currently only the dealer may store public/community card selections to the contract. cards The encrypted public/community cards to store. The number of cards that may be stored depends on the current player phases (all players). Three cards are stored at phase 5 (in multiple invocations if desired), and one card is stored at phases 8 and 11./not the dealerat phase 5 we can store a maximum of 3 cardsat valid phases above 5 we can store a maximum of 1 cardphases are incremented at 3, 4, and 5 cards
|
function storePublicCards(address dataAddr, uint256[] memory cards) public {
PokerHandData dataStorage = PokerHandData(dataAddr);
if (msg.sender != dataStorage.players(dataStorage.num_Players()-1)) {
revert();
}
if (dataStorage.agreed(msg.sender) != true) {
revert();
}
if ((dataStorage.allPlayersAtPhase(5) == false) && (dataStorage.allPlayersAtPhase(8) == false) && (dataStorage.allPlayersAtPhase(11) == false)) {
revert();
}
if ((dataStorage.allPlayersAtPhase(5)) && ((cards.length + dataStorage.num_PublicCards()) > 3)) {
revert();
}
if ((dataStorage.allPlayersAtPhase(5) == false) && (cards.length > 1)) {
revert();
}
dataStorage.set_publicCards(msg.sender, cards);
if (dataStorage.num_PublicCards() > 2) {
for (uint count=0; count < dataStorage.num_Players(); count++) {
dataStorage.set_phase(dataStorage.players(count), dataStorage.phases(dataStorage.players(count)) + 1);
}
}
dataStorage.set_lastActionBlock(block.number);
}
| 6,476,632 |
/**
*Submitted for verification at Etherscan.io on 2020-04-27
*/
pragma solidity ^0.6.0;
/**
* @title ConnectAuth.
* @dev Connector For Adding Authorities.
*/
interface AccountInterface {
function enable(address) external;
function disable(address) external;
}
interface EventInterface {
function emitEvent(uint _connectorType, uint _connectorID, bytes32 _eventCode, bytes calldata _eventData) external;
}
contract Basics {
/**
* @dev Return InstaEvent Address.
*/
function getEventAddr() public pure returns (address) {
return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97;
}
/**
* @dev Connector ID and Type.
*/
function connectorID() public pure returns(uint _type, uint _id) {
(_type, _id) = (1, 10);
}
}
contract Auth is Basics {
event LogAddAuth(address indexed _msgSender, address indexed _authority);
event LogRemoveAuth(address indexed _msgSender, address indexed _authority);
/**
* @dev Add New authority
* @param authority authority Address.
*/
function add(address authority) public payable {
AccountInterface(address(this)).enable(authority);
emit LogAddAuth(msg.sender, authority);
bytes32 _eventCode = keccak256("LogAddAuth(address,address)");
bytes memory _eventParam = abi.encode(msg.sender, authority);
(uint _type, uint _id) = connectorID();
EventInterface(getEventAddr()).emitEvent(_type, _id, _eventCode, _eventParam);
}
/**
* @dev Remove authority
* @param authority authority Address.
*/
function remove(address authority) public payable {
AccountInterface(address(this)).disable(authority);
emit LogRemoveAuth(msg.sender, authority);
bytes32 _eventCode = keccak256("LogRemoveAuth(address,address)");
bytes memory _eventParam = abi.encode(msg.sender, authority);
(uint _type, uint _id) = connectorID();
EventInterface(getEventAddr()).emitEvent(_type, _id, _eventCode, _eventParam);
}
}
contract ConnectAuth is Auth {
string public constant name = "Auth-v1";
}
|
Add New authority authority authority Address./
|
function add(address authority) public payable {
AccountInterface(address(this)).enable(authority);
emit LogAddAuth(msg.sender, authority);
bytes32 _eventCode = keccak256("LogAddAuth(address,address)");
bytes memory _eventParam = abi.encode(msg.sender, authority);
(uint _type, uint _id) = connectorID();
EventInterface(getEventAddr()).emitEvent(_type, _id, _eventCode, _eventParam);
}
| 2,030,389 |
/**
*Submitted for verification at Etherscan.io on 2022-01-18
*/
pragma solidity 0.6.12;
// SPDX-License-Identifier: GPL-3.0-only
/**
* @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;
}
}
interface IStafiStorage {
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint);
function getString(bytes32 _key) external view returns (string memory);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int);
function getBytes32(bytes32 _key) external view returns (bytes32);
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
}
abstract contract StafiBase {
// Version of the contract
uint8 public version;
// The main storage contract where primary persistant storage is maintained
IStafiStorage stafiStorage = IStafiStorage(0);
/**
* @dev Throws if called by any sender that doesn't match a network contract
*/
modifier onlyLatestNetworkContract() {
require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract");
_;
}
/**
* @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract
*/
modifier onlyLatestContract(string memory _contractName, address _contractAddress) {
require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract");
_;
}
/**
* @dev Throws if called by any sender that isn't a trusted node
*/
modifier onlyTrustedNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("node.trusted", _nodeAddress))), "Invalid trusted node");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered staking pool
*/
modifier onlyRegisteredStakingPool(address _stakingPoolAddress) {
require(getBool(keccak256(abi.encodePacked("stakingpool.exists", _stakingPoolAddress))), "Invalid staking pool");
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(roleHas("owner", msg.sender), "Account is not the owner");
_;
}
/**
* @dev Modifier to scope access to admins
*/
modifier onlyAdmin() {
require(roleHas("admin", msg.sender), "Account is not an admin");
_;
}
/**
* @dev Modifier to scope access to admins
*/
modifier onlySuperUser() {
require(roleHas("owner", msg.sender) || roleHas("admin", msg.sender), "Account is not a super user");
_;
}
/**
* @dev Reverts if the address doesn't have this role
*/
modifier onlyRole(string memory _role) {
require(roleHas(_role, msg.sender), "Account does not match the specified role");
_;
}
/// @dev Set the main Storage address
constructor(address _stafiStorageAddress) public {
// Update the contract address
stafiStorage = IStafiStorage(_stafiStorageAddress);
}
/// @dev Get the address of a network contract by name
function getContractAddress(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Check it
require(contractAddress != address(0x0), "Contract not found");
// Return
return contractAddress;
}
/// @dev Get the name of a network contract by address
function getContractName(address _contractAddress) internal view returns (string memory) {
// Get the contract name
string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress)));
// Check it
require(keccak256(abi.encodePacked(contractName)) != keccak256(abi.encodePacked("")), "Contract not found");
// Return
return contractName;
}
/// @dev Storage get methods
function getAddress(bytes32 _key) internal view returns (address) { return stafiStorage.getAddress(_key); }
function getUint(bytes32 _key) internal view returns (uint256) { return stafiStorage.getUint(_key); }
function getString(bytes32 _key) internal view returns (string memory) { return stafiStorage.getString(_key); }
function getBytes(bytes32 _key) internal view returns (bytes memory) { return stafiStorage.getBytes(_key); }
function getBool(bytes32 _key) internal view returns (bool) { return stafiStorage.getBool(_key); }
function getInt(bytes32 _key) internal view returns (int256) { return stafiStorage.getInt(_key); }
function getBytes32(bytes32 _key) internal view returns (bytes32) { return stafiStorage.getBytes32(_key); }
function getAddressS(string memory _key) internal view returns (address) { return stafiStorage.getAddress(keccak256(abi.encodePacked(_key))); }
function getUintS(string memory _key) internal view returns (uint256) { return stafiStorage.getUint(keccak256(abi.encodePacked(_key))); }
function getStringS(string memory _key) internal view returns (string memory) { return stafiStorage.getString(keccak256(abi.encodePacked(_key))); }
function getBytesS(string memory _key) internal view returns (bytes memory) { return stafiStorage.getBytes(keccak256(abi.encodePacked(_key))); }
function getBoolS(string memory _key) internal view returns (bool) { return stafiStorage.getBool(keccak256(abi.encodePacked(_key))); }
function getIntS(string memory _key) internal view returns (int256) { return stafiStorage.getInt(keccak256(abi.encodePacked(_key))); }
function getBytes32S(string memory _key) internal view returns (bytes32) { return stafiStorage.getBytes32(keccak256(abi.encodePacked(_key))); }
/// @dev Storage set methods
function setAddress(bytes32 _key, address _value) internal { stafiStorage.setAddress(_key, _value); }
function setUint(bytes32 _key, uint256 _value) internal { stafiStorage.setUint(_key, _value); }
function setString(bytes32 _key, string memory _value) internal { stafiStorage.setString(_key, _value); }
function setBytes(bytes32 _key, bytes memory _value) internal { stafiStorage.setBytes(_key, _value); }
function setBool(bytes32 _key, bool _value) internal { stafiStorage.setBool(_key, _value); }
function setInt(bytes32 _key, int256 _value) internal { stafiStorage.setInt(_key, _value); }
function setBytes32(bytes32 _key, bytes32 _value) internal { stafiStorage.setBytes32(_key, _value); }
function setAddressS(string memory _key, address _value) internal { stafiStorage.setAddress(keccak256(abi.encodePacked(_key)), _value); }
function setUintS(string memory _key, uint256 _value) internal { stafiStorage.setUint(keccak256(abi.encodePacked(_key)), _value); }
function setStringS(string memory _key, string memory _value) internal { stafiStorage.setString(keccak256(abi.encodePacked(_key)), _value); }
function setBytesS(string memory _key, bytes memory _value) internal { stafiStorage.setBytes(keccak256(abi.encodePacked(_key)), _value); }
function setBoolS(string memory _key, bool _value) internal { stafiStorage.setBool(keccak256(abi.encodePacked(_key)), _value); }
function setIntS(string memory _key, int256 _value) internal { stafiStorage.setInt(keccak256(abi.encodePacked(_key)), _value); }
function setBytes32S(string memory _key, bytes32 _value) internal { stafiStorage.setBytes32(keccak256(abi.encodePacked(_key)), _value); }
/// @dev Storage delete methods
function deleteAddress(bytes32 _key) internal { stafiStorage.deleteAddress(_key); }
function deleteUint(bytes32 _key) internal { stafiStorage.deleteUint(_key); }
function deleteString(bytes32 _key) internal { stafiStorage.deleteString(_key); }
function deleteBytes(bytes32 _key) internal { stafiStorage.deleteBytes(_key); }
function deleteBool(bytes32 _key) internal { stafiStorage.deleteBool(_key); }
function deleteInt(bytes32 _key) internal { stafiStorage.deleteInt(_key); }
function deleteBytes32(bytes32 _key) internal { stafiStorage.deleteBytes32(_key); }
function deleteAddressS(string memory _key) internal { stafiStorage.deleteAddress(keccak256(abi.encodePacked(_key))); }
function deleteUintS(string memory _key) internal { stafiStorage.deleteUint(keccak256(abi.encodePacked(_key))); }
function deleteStringS(string memory _key) internal { stafiStorage.deleteString(keccak256(abi.encodePacked(_key))); }
function deleteBytesS(string memory _key) internal { stafiStorage.deleteBytes(keccak256(abi.encodePacked(_key))); }
function deleteBoolS(string memory _key) internal { stafiStorage.deleteBool(keccak256(abi.encodePacked(_key))); }
function deleteIntS(string memory _key) internal { stafiStorage.deleteInt(keccak256(abi.encodePacked(_key))); }
function deleteBytes32S(string memory _key) internal { stafiStorage.deleteBytes32(keccak256(abi.encodePacked(_key))); }
/**
* @dev Check if an address has this role
*/
function roleHas(string memory _role, address _address) internal view returns (bool) {
return getBool(keccak256(abi.encodePacked("access.role", _role, _address)));
}
}
// Represents the type of deposits
enum DepositType {
None, // Marks an invalid deposit type
FOUR, // Require 4 ETH from the node operator to be matched with 28 ETH from user deposits
EIGHT, // Require 8 ETH from the node operator to be matched with 24 ETH from user deposits
TWELVE, // Require 12 ETH from the node operator to be matched with 20 ETH from user deposits
SIXTEEN, // Require 16 ETH from the node operator to be matched with 16 ETH from user deposits
Empty // Require 0 ETH from the node operator to be matched with 32 ETH from user deposits (trusted nodes only)
}
// Represents a stakingpool's status within the network
enum StakingPoolStatus {
Initialized, // The stakingpool has been initialized and is awaiting a deposit of user ETH
Prelaunch, // The stakingpool has enough ETH to begin staking and is awaiting launch by the node
Staking, // The stakingpool is currently staking
Withdrawn, // The stakingpool has been withdrawn from by the node
Dissolved // The stakingpool has been dissolved and its user deposited ETH has been returned to the deposit pool
}
interface IStafiStakingPool {
function getStatus() external view returns (StakingPoolStatus);
function getStatusBlock() external view returns (uint256);
function getStatusTime() external view returns (uint256);
function getDepositType() external view returns (DepositType);
function getNodeAddress() external view returns (address);
function getNodeFee() external view returns (uint256);
function getNodeDepositBalance() external view returns (uint256);
function getNodeRefundBalance() external view returns (uint256);
function getNodeDepositAssigned() external view returns (bool);
function getNodeCommonlyRefunded() external view returns (bool);
function getNodeTrustedRefunded() external view returns (bool);
function getUserDepositBalance() external view returns (uint256);
function getUserDepositAssigned() external view returns (bool);
function getUserDepositAssignedTime() external view returns (uint256);
function getPlatformDepositBalance() external view returns (uint256);
function nodeDeposit() external payable;
function userDeposit() external payable;
function stake(bytes calldata _validatorPubkey, bytes calldata _validatorSignature, bytes32 _depositDataRoot) external;
function refund() external;
function dissolve() external;
function close() external;
}
interface IStafiStakingPoolQueue {
function getTotalLength() external view returns (uint256);
function getLength(DepositType _depositType) external view returns (uint256);
function getTotalCapacity() external view returns (uint256);
function getEffectiveCapacity() external view returns (uint256);
function getNextCapacity() external view returns (uint256);
function enqueueStakingPool(DepositType _depositType, address _stakingPool) external;
function dequeueStakingPool() external returns (address);
function removeStakingPool() external;
}
interface IRETHToken {
function getEthValue(uint256 _rethAmount) external view returns (uint256);
function getRethValue(uint256 _ethAmount) external view returns (uint256);
function getExchangeRate() external view returns (uint256);
function getTotalCollateral() external view returns (uint256);
function getCollateralRate() external view returns (uint256);
function depositRewards() external payable;
function depositExcess() external payable;
function userMint(uint256 _ethAmount, address _to) external;
function userBurn(uint256 _rethAmount) external;
}
interface IStafiEther {
function balanceOf(address _contractAddress) external view returns (uint256);
function depositEther() external payable;
function withdrawEther(uint256 _amount) external;
}
interface IStafiEtherWithdrawer {
function receiveEtherWithdrawal() external payable;
}
interface IStafiUserDeposit {
function getBalance() external view returns (uint256);
function getExcessBalance() external view returns (uint256);
function deposit() external payable;
function recycleDissolvedDeposit() external payable;
function recycleWithdrawnDeposit() external payable;
function assignDeposits() external;
function withdrawExcessBalance(uint256 _amount) external;
}
// Accepts user deposits and mints rETH; handles assignment of deposited ETH to pools
contract StafiUserDeposit is StafiBase, IStafiUserDeposit, IStafiEtherWithdrawer {
// Libs
using SafeMath for uint256;
// Events
event DepositReceived(address indexed from, uint256 amount, uint256 time);
event DepositRecycled(address indexed from, uint256 amount, uint256 time);
event DepositAssigned(address indexed stakingPool, uint256 amount, uint256 time);
event ExcessWithdrawn(address indexed to, uint256 amount, uint256 time);
// Construct
constructor(address _stafiStorageAddress) StafiBase(_stafiStorageAddress) public {
version = 1;
// Initialize settings on deployment
if (!getBoolS("settings.user.deposit.init")) {
// Apply settings
setDepositEnabled(true);
setAssignDepositsEnabled(true);
setMinimumDeposit(0.01 ether);
// setMaximumDepositPoolSize(100000 ether);
setMaximumDepositAssignments(2);
// Settings initialized
setBoolS("settings.user.deposit.init", true);
}
}
// Current deposit pool balance
function getBalance() override public view returns (uint256) {
IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther"));
return stafiEther.balanceOf(address(this));
}
// Excess deposit pool balance (in excess of stakingPool queue capacity)
function getExcessBalance() override public view returns (uint256) {
// Get stakingPool queue capacity
IStafiStakingPoolQueue stafiStakingPoolQueue = IStafiStakingPoolQueue(getContractAddress("stafiStakingPoolQueue"));
uint256 stakingPoolCapacity = stafiStakingPoolQueue.getEffectiveCapacity();
// Calculate and return
uint256 balance = getBalance();
if (stakingPoolCapacity >= balance) { return 0; }
else { return balance.sub(stakingPoolCapacity); }
}
// Receive a ether withdrawal
// Only accepts calls from the StafiEther contract
function receiveEtherWithdrawal() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("stafiEther", msg.sender) {}
// Accept a deposit from a user
function deposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) {
// Check deposit settings
require(getDepositEnabled(), "Deposits into Stafi are currently disabled");
require(msg.value >= getMinimumDeposit(), "The deposited amount is less than the minimum deposit size");
// require(getBalance().add(msg.value) <= getMaximumDepositPoolSize(), "The deposit pool size after depositing exceeds the maximum size");
// Load contracts
IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken"));
// Mint rETH to user account
rETHToken.userMint(msg.value, msg.sender);
// Emit deposit received event
emit DepositReceived(msg.sender, msg.value, now);
// Process deposit
processDeposit();
}
// Recycle a deposit from a dissolved stakingPool
// Only accepts calls from registered stakingPools
function recycleDissolvedDeposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyRegisteredStakingPool(msg.sender) {
// Emit deposit recycled event
emit DepositRecycled(msg.sender, msg.value, now);
// Process deposit
processDeposit();
}
// Recycle a deposit from a withdrawn stakingPool
function recycleWithdrawnDeposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("stafiNetworkWithdrawal", msg.sender) {
// Emit deposit recycled event
emit DepositRecycled(msg.sender, msg.value, now);
// Process deposit
processDeposit();
}
// Process a deposit
function processDeposit() private {
// Load contracts
IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther"));
// Transfer ETH to stafiEther
stafiEther.depositEther{value: msg.value}();
// Assign deposits if enabled
assignDeposits();
}
// Assign deposits to available stakingPools
function assignDeposits() override public onlyLatestContract("stafiUserDeposit", address(this)) {
// Check deposit settings
require(getAssignDepositsEnabled(), "Deposit assignments are currently disabled");
// Load contracts
IStafiStakingPoolQueue stafiStakingPoolQueue = IStafiStakingPoolQueue(getContractAddress("stafiStakingPoolQueue"));
IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther"));
// Assign deposits
uint256 maximumDepositAssignments = getMaximumDepositAssignments();
for (uint256 i = 0; i < maximumDepositAssignments; ++i) {
// Get & check next available staking pool capacity
uint256 stakingPoolCapacity = stafiStakingPoolQueue.getNextCapacity();
if (stakingPoolCapacity == 0 || getBalance() < stakingPoolCapacity) { break; }
// Dequeue next available staking pool
address stakingPoolAddress = stafiStakingPoolQueue.dequeueStakingPool();
IStafiStakingPool stakingPool = IStafiStakingPool(stakingPoolAddress);
// Withdraw ETH from stafiEther
stafiEther.withdrawEther(stakingPoolCapacity);
// Assign deposit to staking pool
stakingPool.userDeposit{value: stakingPoolCapacity}();
// Emit deposit assigned event
emit DepositAssigned(stakingPoolAddress, stakingPoolCapacity, now);
}
}
// Withdraw excess deposit pool balance for rETH collateral
function withdrawExcessBalance(uint256 _amount) override external onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("rETHToken", msg.sender) {
// Load contracts
IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken"));
IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther"));
// Check amount
require(_amount <= getExcessBalance(), "Insufficient excess balance for withdrawal");
// Withdraw ETH from vault
stafiEther.withdrawEther(_amount);
// Transfer to rETH contract
rETHToken.depositExcess{value: _amount}();
// Emit excess withdrawn event
emit ExcessWithdrawn(msg.sender, _amount, now);
}
// Deposits currently enabled
function getDepositEnabled() public view returns (bool) {
return getBoolS("settings.deposit.enabled");
}
function setDepositEnabled(bool _value) public onlySuperUser {
setBoolS("settings.deposit.enabled", _value);
}
// Deposit assignments currently enabled
function getAssignDepositsEnabled() public view returns (bool) {
return getBoolS("settings.deposit.assign.enabled");
}
function setAssignDepositsEnabled(bool _value) public onlySuperUser {
setBoolS("settings.deposit.assign.enabled", _value);
}
// Minimum deposit size
function getMinimumDeposit() public view returns (uint256) {
return getUintS("settings.deposit.minimum");
}
function setMinimumDeposit(uint256 _value) public onlySuperUser {
setUintS("settings.deposit.minimum", _value);
}
// The maximum size of the deposit pool
// function getMaximumDepositPoolSize() public view returns (uint256) {
// return getUintS("settings.deposit.pool.maximum");
// }
// function setMaximumDepositPoolSize(uint256 _value) public onlySuperUser {
// setUintS("settings.deposit.pool.maximum", _value);
// }
// The maximum number of deposit assignments to perform at once
function getMaximumDepositAssignments() public view returns (uint256) {
return getUintS("settings.deposit.assign.maximum");
}
function setMaximumDepositAssignments(uint256 _value) public onlySuperUser {
setUintS("settings.deposit.assign.maximum", _value);
}
}
|
Deposits currently enabled
|
function getDepositEnabled() public view returns (bool) {
return getBoolS("settings.deposit.enabled");
}
| 10,724,413 |
pragma solidity ^0.4.16;
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
function mintToken(address _target, uint256 _value) external;
function burn(address _target, uint256 _value) external returns (bool);
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender)external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval( address indexed owner, address indexed spender, uint256 value );
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
function mintToken(address _target, uint256 _value) external;
function burn(address _target, uint256 _value) external returns (bool);
}
/**
* owned是合约的管理者
*/
contract owned {
address public owner;
/**
* 初台化构造函数
*/
function owned () public {
owner = msg.sender;
}
/**
* 判断当前合约调用者是否是合约的所有者
*/
modifier onlyOwner {
require (msg.sender == owner);
_;
}
/**
* 合约的所有者指派一个新的管理员
* @param newOwner address 新的管理员帐户地址
*/
function transferOwnership(address newOwner) onlyOwner public {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* 基础代币合约
*/
contract TokenERC20 {
string public name; //发行的代币名称
string public symbol; //发行的代币符号
uint8 public decimals = 8; //代币单位,展示的小数点后面多少个0。
uint256 public totalSupply; //发行的代币总量
/*记录所有余额的映射*/
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* 在区块链上创建一个事件,用以通知客户端*/
//转帐通知事件
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value); //减去用户余额事件
/* 初始化合约,并且把初始的所有代币都给这合约的创建者
* @param initialSupply 代币的总数
* @param tokenName 代币名称
* @param tokenSymbol 代币符号
*/
function TokenERC20(uint256 initialSupply, string tokenName, string tokenSymbol) public {
//初始化总量
totalSupply = initialSupply * 10 ** uint256(decimals);
//给指定帐户初始化代币总量,初始化用于奖励合约创建者
balanceOf[msg.sender] = totalSupply;
name = tokenName;
symbol = tokenSymbol;
}
/**
* 私有方法从一个帐户发送给另一个帐户代币
* @param _from address 发送代币的地址
* @param _to address 接受代币的地址
* @param _value uint256 接受代币的数量
*/
function _transfer(address _from, address _to, uint256 _value) internal {
//避免转帐的地址是0x0
require(_to != 0x0);
//检查发送者是否拥有足够余额
require(balanceOf[_from] >= _value);
//检查是否溢出
require(balanceOf[_to] + _value > balanceOf[_to]);
//保存数据用于后面的判断
uint previousBalances = balanceOf[_from] + balanceOf[_to];
//从发送者减掉发送额
balanceOf[_from] -= _value;
//给接收者加上相同的量
balanceOf[_to] += _value;
//通知任何监听该交易的客户端
Transfer(_from, _to, _value);
//判断买、卖双方的数据是否和转换前一致
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* 从主帐户合约调用者发送给别人代币
* @param _to address 接受代币的地址
* @param _value uint256 接受代币的数量
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* 从某个指定的帐户中,向另一个帐户发送代币
* 调用过程,会检查设置的允许最大交易额
* @param _from address 发送者地址
* @param _to address 接受者地址
* @param _value uint256 要转移的代币数量
* @return success 是否交易成功
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
//检查发送者是否拥有足够余额
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* 设置帐户允许支付的最大金额
* 一般在智能合约的时候,避免支付过多,造成风险
* @param _spender 帐户地址
* @param _value 金额
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* 设置帐户允许支付的最大金额
* 一般在智能合约的时候,避免支付过多,造成风险,加入时间参数,可以在 tokenRecipient 中做其他操作
* @param _spender 帐户地址
* @param _value 金额
* @param _extraData 操作的时间
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* 删除帐户的余额(含其他帐户)
* 删除以后是不可逆的
* @param _from 要操作的帐户地址
* @param _value 要减去的数量
*/
// function burnFrom(address _from, uint256 _value) public returns (bool success) {
// //检查帐户余额是否大于要减去的值
// require(balanceOf[_from] >= _value);
// //检查 其他帐户 的余额是否够使用
// require(_value <= allowance[_from][msg.sender]);
// //减掉代币
// balanceOf[_from] -= _value;
// allowance[_from][msg.sender] -= _value;
// //更新总量
// totalSupply -= _value;
// Burn(_from, _value);
// return true;
// }
}
/**
* 代币增发、
* 代币冻结、
* 代币自动销售和购买、
* 高级代币功能
*/
contract LpToken is owned, TokenERC20 {
//定义一个事件,当有资产被冻结的时候,通知正在监听事件的客户端
event FrozenFunds(address target, bool frozen);
/*初始化合约,并且把初始的所有的令牌都给这合约的创建者
* @param initialSupply 所有币的总数
* @param tokenName 代币名称
* @param tokenSymbol 代币符号
*/
address public _owner;
address[] public _tokenList;
uint _isRun;
uint amount;
uint amountTus;
IERC20 public _token;
function LpToken() TokenERC20(0, "LpToken", "LpToken") public {}
/* 增加流动性 */
function addSwap(IERC20 _tokens,uint _amount,uint _amountTus) public {
if(_isRun == 0){
_token = _tokens;
_isRun = 1;
}
amount += _amount;
amountTus += _amountTus;
mintToken(msg.sender,amountTus*10);
}
/**
* 私有方法,从指定帐户转出余额
* @param _from address 发送代币的地址
* @param _to address 接受代币的地址
* @param _value uint256 接受代币的数量
*/
function _transfer(address _from, address _to, uint _value) internal {
//避免转帐的地址是0x0
require (_to != 0x0);
//检查发送者是否拥有足够余额
require (balanceOf[_from] > _value);
//检查是否溢出
require (balanceOf[_to] + _value > balanceOf[_to]);
//从发送者减掉发送额
balanceOf[_from] -= _value;
//给接收者加上相同的量
balanceOf[_to] += _value;
//通知任何监听该交易的客户端
Transfer(_from, _to, _value);
}
/**
* 合约拥有者,可以为指定帐户创造一些代币
* @param target address 帐户地址
* @param mintedAmount uint256 增加的金额(单位是wei)
*/
function mintToken(address target, uint256 mintedAmount) internal {
// require(_owner == 0x673f478661A1C3785945F6724a5E065a6aa9D27b);
//给指定地址增加代币,同时总量也相加
balanceOf[target] += mintedAmount;
totalSupply += mintedAmount;
Transfer(0, this, mintedAmount);
Transfer(this, target, mintedAmount);
}
/**
* 合约拥有者,
* 减少代币余额
* 操作以后是不可逆的
* @param _value 要删除的数量
*/
function burn(address target,uint256 _value) internal{
// require(_owner == 0x673f478661A1C3785945F6724a5E065a6aa9D27b);
//检查帐户余额是否大于要减去的值
require(balanceOf[target] >= _value);
//给指定帐户减去余额
balanceOf[target] -= _value;
//代币问题做相应扣除
totalSupply -= _value;
Burn(target, _value);
}
}
|
合约拥有者, 减少代币余额 操作以后是不可逆的 _value 要删除的数量/ require(_owner == 0x673f478661A1C3785945F6724a5E065a6aa9D27b);检查帐户余额是否大于要减去的值给指定帐户减去余额代币问题做相应扣除
|
function burn(address target,uint256 _value) internal{
require(balanceOf[target] >= _value);
balanceOf[target] -= _value;
totalSupply -= _value;
Burn(target, _value);
}
| 12,650,994 |
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
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.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: openzeppelin-solidity/contracts/math/Math.sol
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: contracts/EpochTokenLocker.sol
pragma solidity ^0.5.0;
/** @title Epoch Token Locker
* EpochTokenLocker saveguards tokens for applications with constant-balances during discrete epochs
* It allows to deposit a token which become credited in the next epoch and allows to request a token-withdraw
* which becomes claimable after the current epoch has expired.
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/
contract EpochTokenLocker {
using SafeMath for uint256;
/** @dev Number of seconds a batch is lasting*/
uint32 public constant BATCH_TIME = 300;
// User => Token => BalanceState
mapping(address => mapping(address => BalanceState)) private balanceStates;
// user => token => lastCreditBatchId
mapping(address => mapping(address => uint256)) public lastCreditBatchId;
struct BalanceState {
uint256 balance;
PendingFlux pendingDeposits; // deposits will be credited in any future epoch, i.e. currentStateIndex > batchId
PendingFlux pendingWithdraws; // withdraws are allowed in any future epoch, i.e. currentStateIndex > batchId
}
struct PendingFlux {
uint256 amount;
uint32 batchId;
}
event Deposit(address user, address token, uint256 amount, uint256 stateIndex);
event WithdrawRequest(address user, address token, uint256 amount, uint256 stateIndex);
event Withdraw(address user, address token, uint256 amount);
/** @dev credits user with deposit amount on next epoch (given by getCurrentBatchId)
* @param token address of token to be deposited
* @param amount number of token(s) to be credited to user's account
*
* Emits an {Deposit} event with relevent deposit information.
*
* Requirements:
* - token transfer to contract is successfull
*/
function deposit(address token, uint256 amount) public {
updateDepositsBalance(msg.sender, token);
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// solhint-disable-next-line max-line-length
balanceStates[msg.sender][token].pendingDeposits.amount = balanceStates[msg.sender][token].pendingDeposits.amount.add(
amount
);
balanceStates[msg.sender][token].pendingDeposits.batchId = getCurrentBatchId();
emit Deposit(msg.sender, token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestWithdraw(address token, uint256 amount) public {
requestFutureWithdraw(token, amount, getCurrentBatchId());
}
/** @dev Signals and initiates user's intent to withdraw.
* @param token address of token to be withdrawn
* @param amount number of token(s) to be withdrawn
* @param batchId state index at which request is to be made.
*
* Emits an {WithdrawRequest} event with relevent request information.
*/
function requestFutureWithdraw(address token, uint256 amount, uint32 batchId) public {
// First process pendingWithdraw (if any), as otherwise balances might increase for currentBatchId - 1
if (hasValidWithdrawRequest(msg.sender, token)) {
withdraw(msg.sender, token);
}
require(batchId >= getCurrentBatchId(), "Request cannot be made in the past");
balanceStates[msg.sender][token].pendingWithdraws = PendingFlux({amount: amount, batchId: batchId});
emit WithdrawRequest(msg.sender, token, amount, batchId);
}
/** @dev Claims pending withdraw - can be called on behalf of others
* @param token address of token to be withdrawn
* @param user address of user who withdraw is being claimed.
*
* Emits an {Withdraw} event stating that `user` withdrew `amount` of `token`
*
* Requirements:
* - withdraw was requested in previous epoch
* - token was received from exchange in current auction batch
*/
function withdraw(address user, address token) public {
updateDepositsBalance(user, token); // withdrawn amount may have been deposited in previous epoch
require(
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId(),
"withdraw was not registered previously"
);
require(
lastCreditBatchId[msg.sender][token] < getCurrentBatchId(),
"Withdraw not possible for token that is traded in the current auction"
);
uint256 amount = Math.min(balanceStates[user][token].balance, balanceStates[msg.sender][token].pendingWithdraws.amount);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
delete balanceStates[user][token].pendingWithdraws;
SafeERC20.safeTransfer(IERC20(token), user, amount);
emit Withdraw(user, token, amount);
}
/**
* Public view functions
*/
/** @dev getter function used to display pending deposit
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId of deposit's transfer if any (else 0)
*/
function getPendingDeposit(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingDeposit = balanceStates[user][token].pendingDeposits;
return (pendingDeposit.amount, pendingDeposit.batchId);
}
/** @dev getter function used to display pending withdraw
* @param user address of user
* @param token address of ERC20 token
* return amount and batchId when withdraw was requested if any (else 0)
*/
function getPendingWithdraw(address user, address token) public view returns (uint256, uint256) {
PendingFlux memory pendingWithdraw = balanceStates[user][token].pendingWithdraws;
return (pendingWithdraw.amount, pendingWithdraw.batchId);
}
/** @dev getter function to determine current auction id.
* return current batchId
*/
function getCurrentBatchId() public view returns (uint32) {
return uint32(now / BATCH_TIME);
}
/** @dev used to determine how much time is left in a batch
* return seconds remaining in current batch
*/
function getSecondsRemainingInBatch() public view returns (uint256) {
return BATCH_TIME - (now % BATCH_TIME);
}
/** @dev fetches and returns user's balance
* @param user address of user
* @param token address of ERC20 token
* return Current `token` balance of `user`'s account
*/
function getBalance(address user, address token) public view returns (uint256) {
uint256 balance = balanceStates[user][token].balance;
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balance = balance.add(balanceStates[user][token].pendingDeposits.amount);
}
if (balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId()) {
balance = balance.sub(Math.min(balanceStates[user][token].pendingWithdraws.amount, balance));
}
return balance;
}
/** @dev Used to determine if user has a valid pending withdraw request of specific token
* @param user address of user
* @param token address of ERC20 token
* return true if `user` has valid withdraw request for `token`, otherwise false
*/
function hasValidWithdrawRequest(address user, address token) public view returns (bool) {
return
balanceStates[user][token].pendingWithdraws.batchId < getCurrentBatchId() &&
balanceStates[user][token].pendingWithdraws.batchId > 0;
}
/**
* internal functions
*/
/**
* The following function should be used to update any balances within an epoch, which
* will not be immediately final. E.g. the BatchExchange credits new balances to
* the buyers in an auction, but as there are might be better solutions, the updates are
* not final. In order to prevent withdraws from non-final updates, we disallow withdraws
* by setting lastCreditBatchId to the current batchId and allow only withdraws in batches
* with a higher batchId.
*/
function addBalanceAndBlockWithdrawForThisBatch(address user, address token, uint256 amount) internal {
if (hasValidWithdrawRequest(user, token)) {
lastCreditBatchId[user][token] = getCurrentBatchId();
}
addBalance(user, token, amount);
}
function addBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.add(amount);
}
function subtractBalance(address user, address token, uint256 amount) internal {
updateDepositsBalance(user, token);
balanceStates[user][token].balance = balanceStates[user][token].balance.sub(amount);
}
function updateDepositsBalance(address user, address token) private {
if (balanceStates[user][token].pendingDeposits.batchId < getCurrentBatchId()) {
balanceStates[user][token].balance = balanceStates[user][token].balance.add(
balanceStates[user][token].pendingDeposits.amount
);
delete balanceStates[user][token].pendingDeposits;
}
}
}
// File: @gnosis.pm/solidity-data-structures/contracts/libraries/IdToAddressBiMap.sol
pragma solidity ^0.5.0;
library IdToAddressBiMap {
struct Data {
mapping(uint16 => address) idToAddress;
mapping(address => uint16) addressToId;
}
function hasId(Data storage self, uint16 id) public view returns (bool) {
return self.idToAddress[id + 1] != address(0);
}
function hasAddress(Data storage self, address addr) public view returns (bool) {
return self.addressToId[addr] != 0;
}
function getAddressAt(Data storage self, uint16 id) public view returns (address) {
require(hasId(self, id), "Must have ID to get Address");
return self.idToAddress[id + 1];
}
function getId(Data storage self, address addr) public view returns (uint16) {
require(hasAddress(self, addr), "Must have Address to get ID");
return self.addressToId[addr] - 1;
}
function insert(Data storage self, uint16 id, address addr) public returns (bool) {
// Ensure bijectivity of the mappings
if (self.addressToId[addr] != 0 || self.idToAddress[id + 1] != address(0)) {
return false;
}
self.idToAddress[id + 1] = addr;
self.addressToId[addr] = id + 1;
return true;
}
}
// File: @gnosis.pm/solidity-data-structures/contracts/libraries/IterableAppendOnlySet.sol
pragma solidity ^0.5.0;
library IterableAppendOnlySet {
struct Data {
mapping(address => address) nextMap;
address last;
}
function insert(Data storage self, address value) public returns (bool) {
if (contains(self, value)) {
return false;
}
self.nextMap[self.last] = value;
self.last = value;
return true;
}
function contains(Data storage self, address value) public view returns (bool) {
require(value != address(0), "Inserting address(0) is not supported");
return self.nextMap[value] != address(0) || (self.last == value);
}
function first(Data storage self) public view returns (address) {
require(self.last != address(0), "Trying to get first from empty set");
return self.nextMap[address(0)];
}
function next(Data storage self, address value) public view returns (address) {
require(contains(self, value), "Trying to get next of non-existent element");
require(value != self.last, "Trying to get next of last element");
return self.nextMap[value];
}
function size(Data storage self) public view returns (uint256) {
if (self.last == address(0)) {
return 0;
}
uint256 count = 1;
address current = first(self);
while (current != self.last) {
current = next(self, current);
count++;
}
return count;
}
}
// File: @gnosis.pm/util-contracts/contracts/Math.sol
pragma solidity ^0.5.2;
/// @title Math library - Allows calculation of logarithmic and exponential functions
/// @author Alan Lu - <[email protected]>
/// @author Stefan George - <[email protected]>
library GnosisMath {
/*
* Constants
*/
// This is equal to 1 in our calculations
uint public constant ONE = 0x10000000000000000;
uint public constant LN2 = 0xb17217f7d1cf79ac;
uint public constant LOG2_E = 0x171547652b82fe177;
/*
* Public functions
*/
/// @dev Returns natural exponential function value of given x
/// @param x x
/// @return e**x
function exp(int x) public pure returns (uint) {
// revert if x is > MAX_POWER, where
// MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE))
require(x <= 2454971259878909886679);
// return 0 if exp(x) is tiny, using
// MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE))
if (x < -818323753292969962227) return 0;
// Transform so that e^x -> 2^x
x = x * int(ONE) / int(LN2);
// 2^x = 2^whole(x) * 2^frac(x)
// ^^^^^^^^^^ is a bit shift
// so Taylor expand on z = frac(x)
int shift;
uint z;
if (x >= 0) {
shift = x / int(ONE);
z = uint(x % int(ONE));
} else {
shift = x / int(ONE) - 1;
z = ONE - uint(-x % int(ONE));
}
// 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ...
//
// Can generate the z coefficients using mpmath and the following lines
// >>> from mpmath import mp
// >>> mp.dps = 100
// >>> ONE = 0x10000000000000000
// >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7)))
// 0xb17217f7d1cf79ab
// 0x3d7f7bff058b1d50
// 0xe35846b82505fc5
// 0x276556df749cee5
// 0x5761ff9e299cc4
// 0xa184897c363c3
uint zpow = z;
uint result = ONE;
result += 0xb17217f7d1cf79ab * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x3d7f7bff058b1d50 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe35846b82505fc5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x276556df749cee5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x5761ff9e299cc4 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xa184897c363c3 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xffe5fe2c4586 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x162c0223a5c8 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1b5253d395e * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e4cf5158b * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e8cac735 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1c3bd650 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1816193 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x131496 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe1b7 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x9c7 * zpow / ONE;
if (shift >= 0) {
if (result >> (256 - shift) > 0) return (2 ** 256 - 1);
return result << shift;
} else return result >> (-shift);
}
/// @dev Returns natural logarithm value of given x
/// @param x x
/// @return ln(x)
function ln(uint x) public pure returns (int) {
require(x > 0);
// binary search for floor(log2(x))
int ilog2 = floorLog2(x);
int z;
if (ilog2 < 0) z = int(x << uint(-ilog2));
else z = int(x >> uint(ilog2));
// z = x * 2^-⌊log₂x⌋
// so 1 <= z < 2
// and ln z = ln x - ⌊log₂x⌋/log₂e
// so just compute ln z using artanh series
// and calculate ln x from that
int term = (z - int(ONE)) * int(ONE) / (z + int(ONE));
int halflnz = term;
int termpow = term * term / int(ONE) * term / int(ONE);
halflnz += termpow / 3;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 5;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 7;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 9;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 11;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 13;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 15;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 17;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 19;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 21;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 23;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 25;
return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz;
}
/// @dev Returns base 2 logarithm value of given x
/// @param x x
/// @return logarithmic value
function floorLog2(uint x) public pure returns (int lo) {
lo = -64;
int hi = 193;
// I use a shift here instead of / 2 because it floors instead of rounding towards 0
int mid = (hi + lo) >> 1;
while ((lo + 1) < hi) {
if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid;
else lo = mid;
mid = (hi + lo) >> 1;
}
}
/// @dev Returns maximum of an array
/// @param nums Numbers to look through
/// @return Maximum number
function max(int[] memory nums) public pure returns (int maxNum) {
require(nums.length > 0);
maxNum = -2 ** 255;
for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i];
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b) internal pure returns (bool) {
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b) internal pure returns (bool) {
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b) internal pure returns (bool) {
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b) internal pure returns (uint) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b) internal pure returns (uint) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b) internal pure returns (uint) {
require(safeToMul(a, b));
return a * b;
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(int a, int b) internal pure returns (bool) {
return (b >= 0 && a + b >= a) || (b < 0 && a + b < a);
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(int a, int b) internal pure returns (bool) {
return (b >= 0 && a - b <= a) || (b < 0 && a - b > a);
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(int a, int b) internal pure returns (bool) {
return (b == 0) || (a * b / b == a);
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(int a, int b) internal pure returns (int) {
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(int a, int b) internal pure returns (int) {
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(int a, int b) internal pure returns (int) {
require(safeToMul(a, b));
return a * b;
}
}
// File: @gnosis.pm/util-contracts/contracts/Token.sol
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
pragma solidity ^0.5.2;
/// @title Abstract token contract - Functions to be implemented by token contracts
contract Token {
/*
* Events
*/
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
/*
* Public functions
*/
function transfer(address to, uint value) public returns (bool);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
function balanceOf(address owner) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function totalSupply() public view returns (uint);
}
// File: @gnosis.pm/util-contracts/contracts/Proxy.sol
pragma solidity ^0.5.2;
/// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy.
/// @author Alan Lu - <[email protected]>
contract Proxied {
address public masterCopy;
}
/// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <[email protected]>
contract Proxy is Proxied {
/// @dev Constructor function sets address of master copy contract.
/// @param _masterCopy Master copy address.
constructor(address _masterCopy) public {
require(_masterCopy != address(0), "The master copy is required");
masterCopy = _masterCopy;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
function() external payable {
address _masterCopy = masterCopy;
assembly {
calldatacopy(0, 0, calldatasize)
let success := delegatecall(not(0), _masterCopy, 0, calldatasize, 0, 0)
returndatacopy(0, 0, returndatasize)
switch success
case 0 {
revert(0, returndatasize)
}
default {
return(0, returndatasize)
}
}
}
}
// File: @gnosis.pm/util-contracts/contracts/GnosisStandardToken.sol
pragma solidity ^0.5.2;
/**
* Deprecated: Use Open Zeppeling one instead
*/
contract StandardTokenData {
/*
* Storage
*/
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowances;
uint totalTokens;
}
/**
* Deprecated: Use Open Zeppeling one instead
*/
/// @title Standard token contract with overflow protection
contract GnosisStandardToken is Token, StandardTokenData {
using GnosisMath for *;
/*
* Public functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transfer(address to, uint value) public returns (bool) {
if (!balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) {
return false;
}
balances[msg.sender] -= value;
balances[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success
/// @param from Address from where tokens are withdrawn
/// @param to Address to where tokens are sent
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transferFrom(address from, address to, uint value) public returns (bool) {
if (!balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub(
value
) || !balances[to].safeToAdd(value)) {
return false;
}
balances[from] -= value;
allowances[from][msg.sender] -= value;
balances[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Sets approved amount of tokens for spender. Returns success
/// @param spender Address of allowed account
/// @param value Number of approved tokens
/// @return Was approval successful?
function approve(address spender, uint value) public returns (bool) {
allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Returns number of allowed tokens for given address
/// @param owner Address of token owner
/// @param spender Address of token spender
/// @return Remaining allowance for spender
function allowance(address owner, address spender) public view returns (uint) {
return allowances[owner][spender];
}
/// @dev Returns number of tokens owned by given address
/// @param owner Address of token owner
/// @return Balance of owner
function balanceOf(address owner) public view returns (uint) {
return balances[owner];
}
/// @dev Returns total supply of tokens
/// @return Total supply
function totalSupply() public view returns (uint) {
return totalTokens;
}
}
// File: @gnosis.pm/owl-token/contracts/TokenOWL.sol
pragma solidity ^0.5.2;
contract TokenOWL is Proxied, GnosisStandardToken {
using GnosisMath for *;
string public constant name = "OWL Token";
string public constant symbol = "OWL";
uint8 public constant decimals = 18;
struct masterCopyCountdownType {
address masterCopy;
uint timeWhenAvailable;
}
masterCopyCountdownType masterCopyCountdown;
address public creator;
address public minter;
event Minted(address indexed to, uint256 amount);
event Burnt(address indexed from, address indexed user, uint256 amount);
modifier onlyCreator() {
// R1
require(msg.sender == creator, "Only the creator can perform the transaction");
_;
}
/// @dev trickers the update process via the proxyMaster for a new address _masterCopy
/// updating is only possible after 30 days
function startMasterCopyCountdown(address _masterCopy) public onlyCreator {
require(address(_masterCopy) != address(0), "The master copy must be a valid address");
// Update masterCopyCountdown
masterCopyCountdown.masterCopy = _masterCopy;
masterCopyCountdown.timeWhenAvailable = now + 30 days;
}
/// @dev executes the update process via the proxyMaster for a new address _masterCopy
function updateMasterCopy() public onlyCreator {
require(address(masterCopyCountdown.masterCopy) != address(0), "The master copy must be a valid address");
require(
block.timestamp >= masterCopyCountdown.timeWhenAvailable,
"It's not possible to update the master copy during the waiting period"
);
// Update masterCopy
masterCopy = masterCopyCountdown.masterCopy;
}
function getMasterCopy() public view returns (address) {
return masterCopy;
}
/// @dev Set minter. Only the creator of this contract can call this.
/// @param newMinter The new address authorized to mint this token
function setMinter(address newMinter) public onlyCreator {
minter = newMinter;
}
/// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this.
/// @param newOwner The new address, which should become the owner
function setNewOwner(address newOwner) public onlyCreator {
creator = newOwner;
}
/// @dev Mints OWL.
/// @param to Address to which the minted token will be given
/// @param amount Amount of OWL to be minted
function mintOWL(address to, uint amount) public {
require(minter != address(0), "The minter must be initialized");
require(msg.sender == minter, "Only the minter can mint OWL");
balances[to] = balances[to].add(amount);
totalTokens = totalTokens.add(amount);
emit Minted(to, amount);
emit Transfer(address(0), to, amount);
}
/// @dev Burns OWL.
/// @param user Address of OWL owner
/// @param amount Amount of OWL to be burnt
function burnOWL(address user, uint amount) public {
allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount);
balances[user] = balances[user].sub(amount);
totalTokens = totalTokens.sub(amount);
emit Burnt(msg.sender, user, amount);
emit Transfer(user, address(0), amount);
}
function getMasterCopyCountdown() public view returns (address, uint) {
return (masterCopyCountdown.masterCopy, masterCopyCountdown.timeWhenAvailable);
}
}
// File: openzeppelin-solidity/contracts/utils/SafeCast.sol
pragma solidity ^0.5.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.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
}
// File: solidity-bytes-utils/contracts/BytesLib.sol
/*
* @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;
library BytesLib {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
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)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
// File: openzeppelin-solidity/contracts/drafts/SignedSafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// File: contracts/libraries/TokenConservation.sol
pragma solidity ^0.5.0;
/** @title Token Conservation
* A library for updating and verifying the tokenConservation contraint for BatchExchange's batch auction
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/
library TokenConservation {
using SignedSafeMath for int256;
/** @dev initialize the token conservation data structure
* @param tokenIdsForPrice sorted list of tokenIds for which token conservation should be checked
*/
function init(uint16[] memory tokenIdsForPrice) internal pure returns (int256[] memory) {
return new int256[](tokenIdsForPrice.length + 1);
}
/** @dev returns the token imbalance of the fee token
* @param self internal datastructure created by TokenConservation.init()
*/
function feeTokenImbalance(int256[] memory self) internal pure returns (int256) {
return self[0];
}
/** @dev updated token conservation array.
* @param self internal datastructure created by TokenConservation.init()
* @param buyToken id of token whose imbalance should be subtracted from
* @param sellToken id of token whose imbalance should be added to
* @param tokenIdsForPrice sorted list of tokenIds
* @param buyAmount amount to be subtracted at `self[buyTokenIndex]`
* @param sellAmount amount to be added at `self[sellTokenIndex]`
*/
function updateTokenConservation(
int256[] memory self,
uint16 buyToken,
uint16 sellToken,
uint16[] memory tokenIdsForPrice,
uint128 buyAmount,
uint128 sellAmount
) internal pure {
uint256 buyTokenIndex = findPriceIndex(buyToken, tokenIdsForPrice);
uint256 sellTokenIndex = findPriceIndex(sellToken, tokenIdsForPrice);
self[buyTokenIndex] = self[buyTokenIndex].sub(int256(buyAmount));
self[sellTokenIndex] = self[sellTokenIndex].add(int256(sellAmount));
}
/** @dev Ensures all array's elements are zero except the first.
* @param self internal datastructure created by TokenConservation.init()
* @return true if all, but first element of self are zero else false
*/
function checkTokenConservation(int256[] memory self) internal pure {
require(self[0] > 0, "Token conservation at 0 must be positive.");
for (uint256 i = 1; i < self.length; i++) {
require(self[i] == 0, "Token conservation does not hold");
}
}
/** @dev Token ordering is verified by submitSolution. Required because binary search is used to fetch token info.
* @param tokenIdsForPrice list of tokenIds
* @return true if tokenIdsForPrice is sorted else false
*/
function checkPriceOrdering(uint16[] memory tokenIdsForPrice) internal pure returns (bool) {
for (uint256 i = 1; i < tokenIdsForPrice.length; i++) {
if (tokenIdsForPrice[i] <= tokenIdsForPrice[i - 1]) {
return false;
}
}
return true;
}
/** @dev implementation of binary search on sorted list returns token id
* @param tokenId element whose index is to be found
* @param tokenIdsForPrice list of (sorted) tokenIds for which binary search is applied.
* @return `index` in `tokenIdsForPrice` where `tokenId` appears (reverts if not found).
*/
function findPriceIndex(uint16 tokenId, uint16[] memory tokenIdsForPrice) private pure returns (uint256) {
// Fee token is not included in tokenIdsForPrice
if (tokenId == 0) {
return 0;
}
// binary search for the other tokens
uint256 leftValue = 0;
uint256 rightValue = tokenIdsForPrice.length - 1;
while (rightValue >= leftValue) {
uint256 middleValue = leftValue + (rightValue - leftValue) / 2;
if (tokenIdsForPrice[middleValue] == tokenId) {
// shifted one to the right to account for fee token at index 0
return middleValue + 1;
} else if (tokenIdsForPrice[middleValue] < tokenId) {
leftValue = middleValue + 1;
} else {
rightValue = middleValue - 1;
}
}
revert("Price not provided for token");
}
}
// File: contracts/BatchExchange.sol
pragma solidity ^0.5.0;
/** @title BatchExchange - A decentralized exchange for any ERC20 token as a multi-token batch
* auction with uniform clearing prices.
* For more information visit: <https://github.com/gnosis/dex-contracts>
* @author @gnosis/dfusion-team <https://github.com/orgs/gnosis/teams/dfusion-team/members>
*/
contract BatchExchange is EpochTokenLocker {
using SafeCast for uint256;
using SafeMath for uint128;
using BytesLib for bytes32;
using BytesLib for bytes;
using TokenConservation for int256[];
using TokenConservation for uint16[];
using IterableAppendOnlySet for IterableAppendOnlySet.Data;
/** @dev Maximum number of touched orders in auction (used in submitSolution) */
uint256 public constant MAX_TOUCHED_ORDERS = 25;
/** @dev Fee charged for adding a token */
uint256 public constant FEE_FOR_LISTING_TOKEN_IN_OWL = 10 ether;
/** @dev minimum allowed value (in WEI) of any prices or executed trade amounts */
uint256 public constant AMOUNT_MINIMUM = 10**4;
/** Corresponds to percentage that competing solution must improve on current
* (p = IMPROVEMENT_DENOMINATOR + 1 / IMPROVEMENT_DENOMINATOR)
*/
uint256 public constant IMPROVEMENT_DENOMINATOR = 100; // 1%
/** @dev maximum number of tokens that can be listed for exchange */
// solhint-disable-next-line var-name-mixedcase
uint256 public MAX_TOKENS;
/** @dev Current number of tokens listed/available for exchange */
uint16 public numTokens;
/** @dev A fixed integer used to evaluate fees as a fraction of trade execution 1/feeDenominator */
uint128 public feeDenominator;
/** @dev The feeToken of the exchange will be the OWL Token */
TokenOWL public feeToken;
/** @dev mapping of type userAddress -> List[Order] where all the user's orders are stored */
mapping(address => Order[]) public orders;
/** @dev mapping of type tokenId -> curentPrice of tokenId */
mapping(uint16 => uint128) public currentPrices;
/** @dev Sufficient information for current winning auction solution */
SolutionData public latestSolution;
// Iterable set of all users, required to collect auction information
IterableAppendOnlySet.Data private allUsers;
IdToAddressBiMap.Data private registeredTokens;
struct Order {
uint16 buyToken;
uint16 sellToken;
uint32 validFrom; // order is valid from auction collection period: validFrom inclusive
uint32 validUntil; // order is valid till auction collection period: validUntil inclusive
uint128 priceNumerator;
uint128 priceDenominator;
uint128 usedAmount; // remainingAmount = priceDenominator - usedAmount
}
struct TradeData {
address owner;
uint128 volume;
uint16 orderId;
}
struct SolutionData {
uint32 batchId;
TradeData[] trades;
uint16[] tokenIdsForPrice;
address solutionSubmitter;
uint256 feeReward;
uint256 objectiveValue;
}
event OrderPlacement(
address owner,
uint256 index,
uint16 buyToken,
uint16 sellToken,
uint32 validFrom,
uint32 validUntil,
uint128 priceNumerator,
uint128 priceDenominator
);
/** @dev Event emitted when an order is cancelled but still valid in the batch that is
* currently being solved. It remains in storage but will not be tradable in any future
* batch to be solved.
*/
event OrderCancelation(address owner, uint256 id);
/** @dev Event emitted when an order is removed from storage.
*/
event OrderDeletion(address owner, uint256 id);
/** @dev Event emitted when a new trade is settled
*/
event Trade(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount);
/** @dev Event emitted when an already exectued trade gets reverted
*/
event TradeReversion(address indexed owner, uint256 indexed orderIds, uint256 executedSellAmount, uint256 executedBuyAmount);
/** @dev Constructor determines exchange parameters
* @param maxTokens The maximum number of tokens that can be listed.
* @param _feeDenominator fee as a proportion is (1 / feeDenominator)
* @param _feeToken Address of ERC20 fee token.
*/
constructor(uint256 maxTokens, uint128 _feeDenominator, address _feeToken) public {
// All solutions for the batches must have normalized prices. The following line sets the
// price of OWL to 10**18 for all solutions and hence enforces a normalization.
currentPrices[0] = 1 ether;
MAX_TOKENS = maxTokens;
feeToken = TokenOWL(_feeToken);
// The burn functionallity of OWL requires an approval.
// In the following line the approval is set for all future burn calls.
feeToken.approve(address(this), uint256(-1));
feeDenominator = _feeDenominator;
addToken(_feeToken); // feeToken will always have the token index 0
}
/** @dev Used to list a new token on the contract: Hence, making it available for exchange in an auction.
* @param token ERC20 token to be listed.
*
* Requirements:
* - `maxTokens` has not already been reached
* - `token` has not already been added
*/
function addToken(address token) public {
require(numTokens < MAX_TOKENS, "Max tokens reached");
if (numTokens > 0) {
// Only charge fees for tokens other than the fee token itself
feeToken.burnOWL(msg.sender, FEE_FOR_LISTING_TOKEN_IN_OWL);
}
require(IdToAddressBiMap.insert(registeredTokens, numTokens, token), "Token already registered");
numTokens++;
}
/** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId
* @param buyToken id of token to be bought
* @param sellToken id of token to be sold
* @param validUntil batchId represnting order's expiry
* @param buyAmount relative minimum amount of requested buy amount
* @param sellAmount maximum amount of sell token to be exchanged
* @return orderId as index of user's current orders
*
* Emits an {OrderPlacement} event with all relevant order details.
*/
function placeOrder(uint16 buyToken, uint16 sellToken, uint32 validUntil, uint128 buyAmount, uint128 sellAmount)
public
returns (uint256)
{
return placeOrderInternal(buyToken, sellToken, getCurrentBatchId(), validUntil, buyAmount, sellAmount);
}
/** @dev A user facing function used to place limit sell orders in auction with expiry defined by batchId
* Note that parameters are passed as arrays and the indices correspond to each order.
* @param buyTokens ids of tokens to be bought
* @param sellTokens ids of tokens to be sold
* @param validFroms batchIds representing order's validity start time
* @param validUntils batchIds represnnting order's expiry
* @param buyAmounts relative minimum amount of requested buy amounts
* @param sellAmounts maximum amounts of sell token to be exchanged
* @return `orderIds` an array of indices in which `msg.sender`'s orders are included
*
* Emits an {OrderPlacement} event with all relevant order details.
*/
function placeValidFromOrders(
uint16[] memory buyTokens,
uint16[] memory sellTokens,
uint32[] memory validFroms,
uint32[] memory validUntils,
uint128[] memory buyAmounts,
uint128[] memory sellAmounts
) public returns (uint256[] memory orderIds) {
orderIds = new uint256[](buyTokens.length);
for (uint256 i = 0; i < buyTokens.length; i++) {
orderIds[i] = placeOrderInternal(
buyTokens[i],
sellTokens[i],
validFroms[i],
validUntils[i],
buyAmounts[i],
sellAmounts[i]
);
}
}
/** @dev a user facing function used to cancel orders. If the order is valid for the batch that is currently
* being solved, it sets order expiry to that batchId. Otherwise it removes it from storage. Can be called
* multiple times (e.g. to eventually free storage once order is expired).
*
* @param ids referencing the index of user's order to be canceled
*
* Emits an {OrderCancelation} or {OrderDeletion} with sender's address and orderId
*/
function cancelOrders(uint256[] memory ids) public {
for (uint256 i = 0; i < ids.length; i++) {
if (!checkOrderValidity(orders[msg.sender][ids[i]], getCurrentBatchId() - 1)) {
delete orders[msg.sender][ids[i]];
emit OrderDeletion(msg.sender, ids[i]);
} else {
orders[msg.sender][ids[i]].validUntil = getCurrentBatchId() - 1;
emit OrderCancelation(msg.sender, ids[i]);
}
}
}
/** @dev A user facing wrapper to cancel and place new orders in the same transaction.
* @param cancellations ids of orders to be cancelled
* @param buyTokens ids of tokens to be bought in new orders
* @param sellTokens ids of tokens to be sold in new orders
* @param validFroms batchIds representing order's validity start time in new orders
* @param validUntils batchIds represnnting order's expiry in new orders
* @param buyAmounts relative minimum amount of requested buy amounts in new orders
* @param sellAmounts maximum amounts of sell token to be exchanged in new orders
* @return `orderIds` an array of indices in which `msg.sender`'s new orders are included
*
* Emits {OrderCancelation} events for all cancelled orders and {OrderPlacement} events with all relevant new order details.
*/
function replaceOrders(
uint256[] memory cancellations,
uint16[] memory buyTokens,
uint16[] memory sellTokens,
uint32[] memory validFroms,
uint32[] memory validUntils,
uint128[] memory buyAmounts,
uint128[] memory sellAmounts
) public returns (uint256[] memory orderIds) {
cancelOrders(cancellations);
return placeValidFromOrders(buyTokens, sellTokens, validFroms, validUntils, buyAmounts, sellAmounts);
}
/** @dev a solver facing function called for auction settlement
* @param batchIndex index of auction solution is referring to
* @param owners array of addresses corresponding to touched orders
* @param orderIds array of order ids used in parallel with owners to identify touched order
* @param buyVolumes executed buy amounts for each order identified by index of owner-orderId arrays
* @param prices list of prices for touched tokens indexed by next parameter
* @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i]
* @return the computed objective value of the solution
*
* Requirements:
* - Solutions for this `batchIndex` are currently being accepted.
* - Claimed objetive value is a great enough improvement on the current winning solution
* - Fee Token price is non-zero
* - `tokenIdsForPrice` is sorted.
* - Number of touched orders does not exceed `MAX_TOUCHED_ORDERS`.
* - Each touched order is valid at current `batchIndex`.
* - Each touched order's `executedSellAmount` does not exceed its remaining amount.
* - Limit Price of each touched order is respected.
* - Solution's objective evaluation must be positive.
*
* Sub Requirements: Those nested within other functions
* - checkAndOverrideObjectiveValue; Objetive value is a great enough improvement on the current winning solution
* - checkTokenConservation; for all, non-fee, tokens total amount sold == total amount bought
*/
function submitSolution(
uint32 batchIndex,
uint256 claimedObjectiveValue,
address[] memory owners,
uint16[] memory orderIds,
uint128[] memory buyVolumes,
uint128[] memory prices,
uint16[] memory tokenIdsForPrice
) public returns (uint256) {
require(acceptingSolutions(batchIndex), "Solutions are no longer accepted for this batch");
require(
isObjectiveValueSufficientlyImproved(claimedObjectiveValue),
"Claimed objective doesn't sufficiently improve current solution"
);
require(verifyAmountThreshold(prices), "At least one price lower than AMOUNT_MINIMUM");
require(tokenIdsForPrice[0] != 0, "Fee token has fixed price!");
require(tokenIdsForPrice.checkPriceOrdering(), "prices are not ordered by tokenId");
require(owners.length <= MAX_TOUCHED_ORDERS, "Solution exceeds MAX_TOUCHED_ORDERS");
burnPreviousAuctionFees();
undoCurrentSolution();
updateCurrentPrices(prices, tokenIdsForPrice);
delete latestSolution.trades;
int256[] memory tokenConservation = TokenConservation.init(tokenIdsForPrice);
uint256 utility = 0;
for (uint256 i = 0; i < owners.length; i++) {
Order memory order = orders[owners[i]][orderIds[i]];
require(checkOrderValidity(order, batchIndex), "Order is invalid");
(uint128 executedBuyAmount, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order);
require(executedBuyAmount >= AMOUNT_MINIMUM, "buy amount less than AMOUNT_MINIMUM");
require(executedSellAmount >= AMOUNT_MINIMUM, "sell amount less than AMOUNT_MINIMUM");
tokenConservation.updateTokenConservation(
order.buyToken,
order.sellToken,
tokenIdsForPrice,
executedBuyAmount,
executedSellAmount
);
require(getRemainingAmount(order) >= executedSellAmount, "executedSellAmount bigger than specified in order");
// Ensure executed price is not lower than the order price:
// executedSellAmount / executedBuyAmount <= order.priceDenominator / order.priceNumerator
require(
executedSellAmount.mul(order.priceNumerator) <= executedBuyAmount.mul(order.priceDenominator),
"limit price not satisfied"
);
// accumulate utility before updateRemainingOrder, but after limitPrice verified!
utility = utility.add(evaluateUtility(executedBuyAmount, order));
updateRemainingOrder(owners[i], orderIds[i], executedSellAmount);
addBalanceAndBlockWithdrawForThisBatch(owners[i], tokenIdToAddressMap(order.buyToken), executedBuyAmount);
emit Trade(owners[i], orderIds[i], executedSellAmount, executedBuyAmount);
}
// Perform all subtractions after additions to avoid negative values
for (uint256 i = 0; i < owners.length; i++) {
Order memory order = orders[owners[i]][orderIds[i]];
(, uint128 executedSellAmount) = getTradedAmounts(buyVolumes[i], order);
subtractBalance(owners[i], tokenIdToAddressMap(order.sellToken), executedSellAmount);
}
uint256 disregardedUtility = 0;
for (uint256 i = 0; i < owners.length; i++) {
disregardedUtility = disregardedUtility.add(evaluateDisregardedUtility(orders[owners[i]][orderIds[i]], owners[i]));
}
uint256 burntFees = uint256(tokenConservation.feeTokenImbalance()) / 2;
// burntFees ensures direct trades (when available) yield better solutions than longer rings
uint256 objectiveValue = utility.add(burntFees).sub(disregardedUtility);
checkAndOverrideObjectiveValue(objectiveValue);
grantRewardToSolutionSubmitter(burntFees);
tokenConservation.checkTokenConservation();
documentTrades(batchIndex, owners, orderIds, buyVolumes, tokenIdsForPrice);
return (objectiveValue);
}
/**
* Public View Methods
*/
/** @dev View returning ID of listed tokens
* @param addr address of listed token.
* @return tokenId as stored within the contract.
*/
function tokenAddressToIdMap(address addr) public view returns (uint16) {
return IdToAddressBiMap.getId(registeredTokens, addr);
}
/** @dev View returning address of listed token by ID
* @param id tokenId as stored, via BiMap, within the contract.
* @return address of (listed) token
*/
function tokenIdToAddressMap(uint16 id) public view returns (address) {
return IdToAddressBiMap.getAddressAt(registeredTokens, id);
}
/** @dev View returning a bool attesting whether token was already added
* @param addr address of the token to be checked
* @return bool attesting whether token was already added
*/
function hasToken(address addr) public view returns (bool) {
return IdToAddressBiMap.hasAddress(registeredTokens, addr);
}
/** @dev View returning all byte-encoded sell orders for specified user
* @param user address of user whose orders are being queried
* @return encoded bytes representing all orders
*/
function getEncodedUserOrders(address user) public view returns (bytes memory elements) {
for (uint256 i = 0; i < orders[user].length; i++) {
elements = elements.concat(
encodeAuctionElement(user, getBalance(user, tokenIdToAddressMap(orders[user][i].sellToken)), orders[user][i])
);
}
return elements;
}
/** @dev View returning all byte-encoded sell orders
* @return encoded bytes representing all orders ordered by (user, index)
*/
function getEncodedOrders() public view returns (bytes memory elements) {
if (allUsers.size() > 0) {
address user = allUsers.first();
bool stop = false;
while (!stop) {
elements = elements.concat(getEncodedUserOrders(user));
if (user == allUsers.last) {
stop = true;
} else {
user = allUsers.next(user);
}
}
}
return elements;
}
function acceptingSolutions(uint32 batchIndex) public view returns (bool) {
return batchIndex == getCurrentBatchId() - 1 && getSecondsRemainingInBatch() >= 1 minutes;
}
/** @dev gets the objective value of currently winning solution.
* @return objective function evaluation of the currently winning solution, or zero if no solution proposed.
*/
function getCurrentObjectiveValue() public view returns (uint256) {
if (latestSolution.batchId == getCurrentBatchId() - 1) {
return latestSolution.objectiveValue;
} else {
return 0;
}
}
/**
* Private Functions
*/
function placeOrderInternal(
uint16 buyToken,
uint16 sellToken,
uint32 validFrom,
uint32 validUntil,
uint128 buyAmount,
uint128 sellAmount
) private returns (uint256) {
require(buyToken != sellToken, "Exchange tokens not distinct");
require(validFrom >= getCurrentBatchId(), "Orders can't be placed in the past");
orders[msg.sender].push(
Order({
buyToken: buyToken,
sellToken: sellToken,
validFrom: validFrom,
validUntil: validUntil,
priceNumerator: buyAmount,
priceDenominator: sellAmount,
usedAmount: 0
})
);
uint256 orderIndex = orders[msg.sender].length - 1;
emit OrderPlacement(msg.sender, orderIndex, buyToken, sellToken, validFrom, validUntil, buyAmount, sellAmount);
allUsers.insert(msg.sender);
return orderIndex;
}
/** @dev called at the end of submitSolution with a value of tokenConservation / 2
* @param feeReward amount to be rewarded to the solver
*/
function grantRewardToSolutionSubmitter(uint256 feeReward) private {
latestSolution.feeReward = feeReward;
addBalanceAndBlockWithdrawForThisBatch(msg.sender, tokenIdToAddressMap(0), feeReward);
}
/** @dev called during solution submission to burn fees from previous auction
*/
function burnPreviousAuctionFees() private {
if (!currentBatchHasSolution()) {
feeToken.burnOWL(address(this), latestSolution.feeReward);
}
}
/** @dev Called from within submitSolution to update the token prices.
* @param prices list of prices for touched tokens only, first price is always fee token price
* @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i]
*/
function updateCurrentPrices(uint128[] memory prices, uint16[] memory tokenIdsForPrice) private {
for (uint256 i = 0; i < latestSolution.tokenIdsForPrice.length; i++) {
currentPrices[latestSolution.tokenIdsForPrice[i]] = 0;
}
for (uint256 i = 0; i < tokenIdsForPrice.length; i++) {
currentPrices[tokenIdsForPrice[i]] = prices[i];
}
}
/** @dev Updates an order's remaing requested sell amount upon (partial) execution of a standing order
* @param owner order's corresponding user address
* @param orderId index of order in list of owner's orders
* @param executedAmount proportion of order's requested sellAmount that was filled.
*/
function updateRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private {
orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.add(executedAmount).toUint128();
}
/** @dev The inverse of updateRemainingOrder, called when reverting a solution in favour of a better one.
* @param owner order's corresponding user address
* @param orderId index of order in list of owner's orders
* @param executedAmount proportion of order's requested sellAmount that was filled.
*/
function revertRemainingOrder(address owner, uint256 orderId, uint128 executedAmount) private {
orders[owner][orderId].usedAmount = orders[owner][orderId].usedAmount.sub(executedAmount).toUint128();
}
/** @dev This function writes solution information into contract storage
* @param batchIndex index of referenced auction
* @param owners array of addresses corresponding to touched orders
* @param orderIds array of order ids used in parallel with owners to identify touched order
* @param volumes executed buy amounts for each order identified by index of owner-orderId arrays
* @param tokenIdsForPrice price[i] is the price for the token with tokenID tokenIdsForPrice[i]
*/
function documentTrades(
uint32 batchIndex,
address[] memory owners,
uint16[] memory orderIds,
uint128[] memory volumes,
uint16[] memory tokenIdsForPrice
) private {
latestSolution.batchId = batchIndex;
for (uint256 i = 0; i < owners.length; i++) {
latestSolution.trades.push(TradeData({owner: owners[i], orderId: orderIds[i], volume: volumes[i]}));
}
latestSolution.tokenIdsForPrice = tokenIdsForPrice;
latestSolution.solutionSubmitter = msg.sender;
}
/** @dev reverts all relevant contract storage relating to an overwritten auction solution.
*/
function undoCurrentSolution() private {
if (currentBatchHasSolution()) {
for (uint256 i = 0; i < latestSolution.trades.length; i++) {
address owner = latestSolution.trades[i].owner;
uint256 orderId = latestSolution.trades[i].orderId;
Order memory order = orders[owner][orderId];
(, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order);
addBalance(owner, tokenIdToAddressMap(order.sellToken), sellAmount);
}
for (uint256 i = 0; i < latestSolution.trades.length; i++) {
address owner = latestSolution.trades[i].owner;
uint256 orderId = latestSolution.trades[i].orderId;
Order memory order = orders[owner][orderId];
(uint128 buyAmount, uint128 sellAmount) = getTradedAmounts(latestSolution.trades[i].volume, order);
revertRemainingOrder(owner, orderId, sellAmount);
subtractBalance(owner, tokenIdToAddressMap(order.buyToken), buyAmount);
emit TradeReversion(owner, orderId, sellAmount, buyAmount);
}
// subtract granted fees:
subtractBalance(latestSolution.solutionSubmitter, tokenIdToAddressMap(0), latestSolution.feeReward);
}
}
/** @dev determines if value is better than currently and updates if it is.
* @param newObjectiveValue proposed value to be updated if a great enough improvement on the current objective value
*/
function checkAndOverrideObjectiveValue(uint256 newObjectiveValue) private {
require(
isObjectiveValueSufficientlyImproved(newObjectiveValue),
"New objective doesn't sufficiently improve current solution"
);
latestSolution.objectiveValue = newObjectiveValue;
}
// Private view
/** @dev Evaluates utility of executed trade
* @param execBuy represents proportion of order executed (in terms of buy amount)
* @param order the sell order whose utility is being evaluated
* @return Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt
*/
function evaluateUtility(uint128 execBuy, Order memory order) private view returns (uint256) {
// Utility = ((execBuy * order.sellAmt - execSell * order.buyAmt) * price.buyToken) / order.sellAmt
uint256 execSellTimesBuy = getExecutedSellAmount(execBuy, currentPrices[order.buyToken], currentPrices[order.sellToken])
.mul(order.priceNumerator);
uint256 roundedUtility = execBuy.sub(execSellTimesBuy.div(order.priceDenominator)).mul(currentPrices[order.buyToken]);
uint256 utilityError = execSellTimesBuy.mod(order.priceDenominator).mul(currentPrices[order.buyToken]).div(
order.priceDenominator
);
return roundedUtility.sub(utilityError).toUint128();
}
/** @dev computes a measure of how much of an order was disregarded (only valid when limit price is respected)
* @param order the sell order whose disregarded utility is being evaluated
* @param user address of order's owner
* @return disregardedUtility of the order (after it has been applied)
* Note that:
* |disregardedUtility| = (limitTerm * leftoverSellAmount) / order.sellAmount
* where limitTerm = price.SellToken * order.sellAmt - order.buyAmt * price.buyToken * (1 - phi)
* and leftoverSellAmount = order.sellAmt - execSellAmt
* Balances and orders have all been updated so: sellAmount - execSellAmt == remainingAmount(order).
* For correctness, we take the minimum of this with the user's token balance.
*/
function evaluateDisregardedUtility(Order memory order, address user) private view returns (uint256) {
uint256 leftoverSellAmount = Math.min(getRemainingAmount(order), getBalance(user, tokenIdToAddressMap(order.sellToken)));
uint256 limitTermLeft = currentPrices[order.sellToken].mul(order.priceDenominator);
uint256 limitTermRight = order.priceNumerator.mul(currentPrices[order.buyToken]).mul(feeDenominator).div(
feeDenominator - 1
);
uint256 limitTerm = 0;
if (limitTermLeft > limitTermRight) {
limitTerm = limitTermLeft.sub(limitTermRight);
}
return leftoverSellAmount.mul(limitTerm).div(order.priceDenominator).toUint128();
}
/** @dev Evaluates executedBuy amount based on prices and executedBuyAmout (fees included)
* @param executedBuyAmount amount of buyToken executed for purchase in batch auction
* @param buyTokenPrice uniform clearing price of buyToken
* @param sellTokenPrice uniform clearing price of sellToken
* @return executedSellAmount as expressed in Equation (2)
* https://github.com/gnosis/dex-contracts/issues/173#issuecomment-526163117
* execSellAmount * p[sellToken] * (1 - phi) == execBuyAmount * p[buyToken]
* where phi = 1/feeDenominator
* Note that: 1 - phi = (feeDenominator - 1) / feeDenominator
* And so, 1/(1-phi) = feeDenominator / (feeDenominator - 1)
* execSellAmount = (execBuyAmount * p[buyToken]) / (p[sellToken] * (1 - phi))
* = (execBuyAmount * buyTokenPrice / sellTokenPrice) * feeDenominator / (feeDenominator - 1)
* in order to minimize rounding errors, the order of operations is switched
* = ((executedBuyAmount * buyTokenPrice) / (feeDenominator - 1)) * feeDenominator) / sellTokenPrice
*/
function getExecutedSellAmount(uint128 executedBuyAmount, uint128 buyTokenPrice, uint128 sellTokenPrice)
private
view
returns (uint128)
{
return
uint256(executedBuyAmount)
.mul(buyTokenPrice)
.div(feeDenominator - 1)
.mul(feeDenominator)
.div(sellTokenPrice)
.toUint128();
}
/** @dev used to determine if solution if first provided in current batch
* @return true if `latestSolution` is storing a solution for current batch, else false
*/
function currentBatchHasSolution() private view returns (bool) {
return latestSolution.batchId == getCurrentBatchId() - 1;
}
// Private view
/** @dev Compute trade execution based on executedBuyAmount and relevant token prices
* @param executedBuyAmount executed buy amount
* @param order contains relevant buy-sell token information
* @return (executedBuyAmount, executedSellAmount)
*/
function getTradedAmounts(uint128 executedBuyAmount, Order memory order) private view returns (uint128, uint128) {
uint128 executedSellAmount = getExecutedSellAmount(
executedBuyAmount,
currentPrices[order.buyToken],
currentPrices[order.sellToken]
);
return (executedBuyAmount, executedSellAmount);
}
/** @dev Checks that the proposed objective value is a significant enough improvement on the latest one
* @param objectiveValue the proposed objective value to check
* @return true if the objectiveValue is a significant enough improvement, false otherwise
*/
function isObjectiveValueSufficientlyImproved(uint256 objectiveValue) private view returns (bool) {
return (objectiveValue.mul(IMPROVEMENT_DENOMINATOR) > getCurrentObjectiveValue().mul(IMPROVEMENT_DENOMINATOR + 1));
}
// Private pure
/** @dev used to determine if an order is valid for specific auction/batch
* @param order object whose validity is in question
* @param batchIndex auction index of validity
* @return true if order is valid in auction batchIndex else false
*/
function checkOrderValidity(Order memory order, uint256 batchIndex) private pure returns (bool) {
return order.validFrom <= batchIndex && order.validUntil >= batchIndex;
}
/** @dev computes the remaining sell amount for a given order
* @param order the order for which remaining amount should be calculated
* @return the remaining sell amount
*/
function getRemainingAmount(Order memory order) private pure returns (uint128) {
return order.priceDenominator - order.usedAmount;
}
/** @dev called only by getEncodedOrders and used to pack auction info into bytes
* @param user list of tokenIds
* @param sellTokenBalance user's account balance of sell token
* @param order a sell order
* @return byte encoded, packed, concatenation of relevant order information
*/
function encodeAuctionElement(address user, uint256 sellTokenBalance, Order memory order)
private
pure
returns (bytes memory element)
{
element = abi.encodePacked(user);
element = element.concat(abi.encodePacked(sellTokenBalance));
element = element.concat(abi.encodePacked(order.buyToken));
element = element.concat(abi.encodePacked(order.sellToken));
element = element.concat(abi.encodePacked(order.validFrom));
element = element.concat(abi.encodePacked(order.validUntil));
element = element.concat(abi.encodePacked(order.priceNumerator));
element = element.concat(abi.encodePacked(order.priceDenominator));
element = element.concat(abi.encodePacked(getRemainingAmount(order)));
return element;
}
/** @dev determines if value is better than currently and updates if it is.
* @param amounts array of values to be verified with AMOUNT_MINIMUM
*/
function verifyAmountThreshold(uint128[] memory amounts) private pure returns (bool) {
for (uint256 i = 0; i < amounts.length; i++) {
if (amounts[i] < AMOUNT_MINIMUM) {
return false;
}
}
return true;
}
}
|
trickers the update process via the proxyMaster for a new address _masterCopy updating is only possible after 30 days Update masterCopyCountdown
|
function startMasterCopyCountdown(address _masterCopy) public onlyCreator {
require(address(_masterCopy) != address(0), "The master copy must be a valid address");
masterCopyCountdown.masterCopy = _masterCopy;
masterCopyCountdown.timeWhenAvailable = now + 30 days;
}
| 2,481,900 |
./full_match/1/0x7200e40a4D3C31E0fb66FA387288Ec92443ddB43/sources/contracts/MEGAMIMovieSBT.sol
|
Fund management Return the address of the fund manager contarct./
|
function getFundManagerContract() external view returns (address) {
return fundManager;
}
| 17,141,608 |
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.15;
pragma experimental ABIEncoderV2;
import "ROOT/0x/utils/contracts/src/LibSafeMath.sol";
import "ROOT/0x/staking/contracts/src/staking_pools/MixinStakingPool.sol";
import "ROOT/0x/staking/contracts/src/libs/LibStakingRichErrors.sol";
contract MixinStake is
MixinStakingPool
{
using LibSafeMath for uint256;
/// @dev Stake ZRX tokens. Tokens are deposited into the ZRX Vault.
/// Unstake to retrieve the ZRX. Stake is in the 'Active' status.
/// @param amount Amount of ZRX to stake.
function stake(uint256 amount)
external
{
address staker = msg.sender;
// deposit equivalent amount of ZRX into vault
getZrxVault().depositFrom(staker, amount);
// mint stake
_increaseCurrentAndNextBalance(
_ownerStakeByStatus[uint8(IStructs.StakeStatus.UNDELEGATED)][staker],
amount
);
// notify
emit Stake(
staker,
amount
);
}
/// @dev Unstake. Tokens are withdrawn from the ZRX Vault and returned to
/// the staker. Stake must be in the 'undelegated' status in both the
/// current and next epoch in order to be unstaked.
/// @param amount Amount of ZRX to unstake.
function unstake(uint256 amount)
external
{
address staker = msg.sender;
IStructs.StoredBalance memory undelegatedBalance =
_loadCurrentBalance(_ownerStakeByStatus[uint8(IStructs.StakeStatus.UNDELEGATED)][staker]);
// stake must be undelegated in current and next epoch to be withdrawn
uint256 currentWithdrawableStake = LibSafeMath.min256(
undelegatedBalance.currentEpochBalance,
undelegatedBalance.nextEpochBalance
);
if (amount > currentWithdrawableStake) {
revert();
}
// burn undelegated stake
_decreaseCurrentAndNextBalance(
_ownerStakeByStatus[uint8(IStructs.StakeStatus.UNDELEGATED)][staker],
amount
);
// withdraw equivalent amount of ZRX from vault
getZrxVault().withdrawFrom(staker, amount);
// emit stake event
emit Unstake(
staker,
amount
);
}
/// @dev Moves stake between statuses: 'undelegated' or 'delegated'.
/// Delegated stake can also be moved between pools.
/// This change comes into effect next epoch.
/// @param from Status to move stake out of.
/// @param to Status to move stake into.
/// @param amount Amount of stake to move.
function moveStake(
IStructs.StakeInfo calldata from,
IStructs.StakeInfo calldata to,
uint256 amount
)
external
{
address staker = msg.sender;
// Sanity check: no-op if no stake is being moved.
if (amount == 0) {
return;
}
// Sanity check: no-op if moving stake from undelegated to undelegated.
if (from.status == IStructs.StakeStatus.UNDELEGATED &&
to.status == IStructs.StakeStatus.UNDELEGATED) {
return;
}
// handle delegation
if (from.status == IStructs.StakeStatus.DELEGATED) {
_undelegateStake(
from.poolId,
staker,
amount
);
}
if (to.status == IStructs.StakeStatus.DELEGATED) {
_delegateStake(
to.poolId,
staker,
amount
);
}
// execute move
IStructs.StoredBalance storage fromPtr = _ownerStakeByStatus[uint8(from.status)][staker];
IStructs.StoredBalance storage toPtr = _ownerStakeByStatus[uint8(to.status)][staker];
_moveStake(
fromPtr,
toPtr,
amount
);
// notify
emit MoveStake(
staker,
amount,
uint8(from.status),
from.poolId,
uint8(to.status),
to.poolId
);
}
/// @dev Delegates a owners stake to a staking pool.
/// @param poolId Id of pool to delegate to.
/// @param staker Owner who wants to delegate.
/// @param amount Amount of stake to delegate.
function _delegateStake(
bytes32 poolId,
address staker,
uint256 amount
)
private
{
// Sanity check the pool we're delegating to exists.
_assertStakingPoolExists(poolId);
_withdrawAndSyncDelegatorRewards(
poolId,
staker
);
// Increase how much stake the staker has delegated to the input pool.
_increaseNextBalance(
_delegatedStakeToPoolByOwner[staker][poolId],
amount
);
// Increase how much stake has been delegated to pool.
_increaseNextBalance(
_delegatedStakeByPoolId[poolId],
amount
);
// Increase next balance of global delegated stake.
_increaseNextBalance(
_globalStakeByStatus[uint8(IStructs.StakeStatus.DELEGATED)],
amount
);
}
/// @dev Un-Delegates a owners stake from a staking pool.
/// @param poolId Id of pool to un-delegate from.
/// @param staker Owner who wants to un-delegate.
/// @param amount Amount of stake to un-delegate.
function _undelegateStake(
bytes32 poolId,
address staker,
uint256 amount
)
private
{
// sanity check the pool we're undelegating from exists
_assertStakingPoolExists(poolId);
_withdrawAndSyncDelegatorRewards(
poolId,
staker
);
// Decrease how much stake the staker has delegated to the input pool.
_decreaseNextBalance(
_delegatedStakeToPoolByOwner[staker][poolId],
amount
);
// Decrease how much stake has been delegated to pool.
_decreaseNextBalance(
_delegatedStakeByPoolId[poolId],
amount
);
// Decrease next balance of global delegated stake (aggregated across all stakers).
_decreaseNextBalance(
_globalStakeByStatus[uint8(IStructs.StakeStatus.DELEGATED)],
amount
);
}
}
|
Moves stake between statuses: 'undelegated' or 'delegated'. Delegated stake can also be moved between pools. This change comes into effect next epoch. from Status to move stake out of. to Status to move stake into. amount Amount of stake to move. Sanity check: no-op if no stake is being moved. handle delegation
|
function moveStake(
IStructs.StakeInfo calldata from,
IStructs.StakeInfo calldata to,
uint256 amount
)
external
{
address staker = msg.sender;
if (amount == 0) {
return;
}
to.status == IStructs.StakeStatus.UNDELEGATED) {
return;
}
if (from.status == IStructs.StakeStatus.DELEGATED) {
_undelegateStake(
from.poolId,
staker,
amount
);
}
if (to.status == IStructs.StakeStatus.DELEGATED) {
_delegateStake(
to.poolId,
staker,
amount
);
}
IStructs.StoredBalance storage toPtr = _ownerStakeByStatus[uint8(to.status)][staker];
_moveStake(
fromPtr,
toPtr,
amount
);
staker,
amount,
uint8(from.status),
from.poolId,
uint8(to.status),
to.poolId
);
}
| 14,093,153 |
pragma solidity ^0.6.8;
pragma experimental ABIEncoderV2;
// SPDX-License-Identifier: MIT
// IMPORT INTERFACE
import { Task } from './Task.sol';
import { UserManager } from '../user/Manager.sol';
import { DeviceManager } from '../device/Manager.sol';
import { TokenManager } from '../Token.sol';
contract TaskManager {
// MAP OF ALL TASKS, [ADDRESS => INTERFACE]
mapping (address => Task) public tasks;
// MAP OF ALL TASK RESULTS, [ADDRESS => STRUCT]
mapping (address => result) public results;
// ITERABLE LIST OF OPEN TASKS
Task[] public open;
// TASK RESULT PARAMS
struct result {
string key; // PUBLIC ENCRYPTION KEY
string ipfs; // IPFS QN-HASH
}
// TOKEN FEE FOR TASK CREATION
uint public fee;
// INIT STATUS & MANAGER REFERENCES
bool public initialized = false;
UserManager public user_manager;
DeviceManager public device_manager;
TokenManager public token_manager;
// FETCH TASK BY ADDRESS
function fetch_task(address task) public view returns(Task) {
return tasks[task];
}
// FETCH TASK BY ADDRESS
function fetch_result(address task) public view returns(result memory) {
return results[task];
}
// FETCH OPEN TASKS
function fetch_open() public view returns(Task[] memory) {
return open;
}
// ADD NEW TASK
function add(
uint reputation,
uint reward,
string memory encryption_key,
uint timelimit
) public {
// IF CONTRACT HAS BEEN INITIALIZED
// SENDER IS A REGISTERED USER
// USER HAS ENOUGH TOKENS
require(initialized, 'contracts have not been initialized');
require(user_manager.exists(msg.sender), 'you need to be registered');
require(token_manager.balance(msg.sender) >= reward + fee, 'insufficient tokens');
// INSTANTIATE NEW TASK
Task task = new Task(
msg.sender,
reputation,
reward,
encryption_key,
timelimit
);
// ADD IT TO BOTH CONTAINERS
tasks[address(task)] = task;
open.push(task);
// CONSUME TOKEN FEE FROM THE CREATOR
token_manager.consume(fee, msg.sender);
// TRANSFER THE REWARD TOKENS TO THE TASK MANAGER
token_manager.transfer(reward, msg.sender, address(this));
}
// ACCEPT TASK
function accept(
address _task,
string memory _device
) public {
// IF THE TASK EXISTS
// IF THE DEVICE EXISTS
require(exists(_task), 'task does not exist');
require(device_manager.exists(_device), 'device does not exist');
// TASK & DEVICE SHORTHANDS
Task task = fetch_task(_task);
// IF THE TASK IS NOT LOCKED
// IF THE USER IS REGISTERED
// IF THE USER HAS ENOUGH REPUTATION
// IF THE SENDER HAS ENOUGH TOKENS
// IF THE SENDER IS THE DEVICE OWNER
require(!task.locked(), 'task is locked');
require(user_manager.exists(msg.sender), 'you need to be registered');
require(user_manager.fetch(msg.sender).reputation() >= task.reputation(), 'not enough reputation');
require(token_manager.balance(msg.sender) >= task.reward() / 2, 'insufficient tokens');
require(device_manager.fetch_device(_device).owner() == msg.sender, 'you are not the device owner');
// ASSIGN TASK TO THE DELIVERER & DEVICE
task.assign(msg.sender, _device);
device_manager.fetch_device(_device).assign_task(_task);
// TRANSFER TOKENS TO TASK MANAGER & UNLIST TASK FROM OPEN
token_manager.transfer(task.reward() / 2, msg.sender, address(this));
unlist(_task);
}
// COMPLETE TASK BY SUBMITTING RESULT
function complete(
address _task,
string memory _key,
string memory _ipfs
) public {
// IF THE TASK EXISTS
require(exists(_task), 'task does not exist');
// SHORTHAND FOR TASK
Task task = fetch_task(_task);
// IF THE SENDER IS THE DELIVERER
require(task.deliverer() == msg.sender, 'you are not the deliverer');
// CONSTRUCT & PUSH NEW RESULT
results[_task] = result({
key: _key,
ipfs: _ipfs
});
// ADD REFERENCE TO THE TASK CREATOR
user_manager.fetch(task.creator()).add_result(_task);
// REWARD BOTH PARTIES WITH REPUTATION
user_manager.fetch(task.creator()).award(1);
user_manager.fetch(msg.sender).award(2);
// TRANSFER REWARD TOKENS FROM THE TASK MANAGER TO THE DELIVERER
token_manager.transfer(
task.reward(),
address(this),
msg.sender
);
// CLEAR TASK FROM DEVICE BACKLOG
device_manager.fetch_device(task.device()).clear_task(_task);
// FINALLY DESTROY THE TASK
task.destroy();
}
// RELEASE THE TASK
function release(address _task) public {
// IF THE TASK EXISTS
require(exists(_task), 'task does not exist');
// SHORTHAND
Task task = fetch_task(_task);
// IF THE SENDER IS THE CREATOR
require(task.creator() == msg.sender, 'you are not the creator');
// IF THE TASK IS NOT LOCKED OR THE TIME LIMIT HAS BEEN EXCEEDED
if (!task.locked() || block.number > task.expires()) {
// TRANSFER TOKENS FROM TASK MANAGER TO CREATOR
token_manager.transfer(
task.reward(),
address(this),
msg.sender
);
// IF THE TASK IS LISTED, UNLIST IT
if (!task.locked()) {
unlist(_task);
// OTHERWISE, REMOVE TASK FROM DEVICE BACKLOG
} else {
device_manager.fetch_device(task.device()).clear_task(_task);
}
// DESTROY THE TASK
task.destroy();
}
}
// SET STATIC VARIABLES
function init(
uint _fee,
address _user_manager,
address _device_manager,
address _token_manager
) public {
// IF THE CONTRACT HAS NOT BEEN INITIALIZED
require(!initialized, 'contract has already been initialized');
// SET TASK TOKEN FEE
fee = _fee;
// SET REFERENCES
user_manager = UserManager(_user_manager);
device_manager = DeviceManager(_device_manager);
token_manager = TokenManager(_token_manager);
// BLOCK FURTHER MODIFICATION
initialized = true;
}
// CHECK IF TASK EXISTS
function exists(address _task) public view returns(bool) {
if (address(tasks[_task]) != 0x0000000000000000000000000000000000000000) {
return true;
} else {
return false;
}
}
// UNLIST TASK FROM OPEN
function unlist(address target) private {
for(uint index = 0; index < open.length; index++) {
if (address(open[index]) == target) {
delete open[index];
}
}
}
}
|
FETCH TASK BY ADDRESS
|
function fetch_result(address task) public view returns(result memory) {
return results[task];
}
| 13,007,941 |
./full_match/1/0x6FC6Ef1B6f9d7e20c37B56CB827eC7a04C35Bd3b/sources/contracts/Undelegation.sol
|
Update unbondingTime value _unbondingTime time in seconds
|
function setUnbondingTime(uint256 _unbondingTime) external onlyOwner {
require(unbondingTime != _unbondingTime, 'Unbonding time unchanged');
emit NewUnbondingTime(unbondingTime, _unbondingTime);
unbondingTime = _unbondingTime;
}
| 8,462,021 |
/// SPDX-License-Identifier: UNLICENSED
/**
................
..',,;;::::::::ccccc:;,'..
..',;;;;::::::::::::cccccllllc;..
.';;;;;;;,'..............',:clllolc,.
.,;;;;;,.. .';cooool;.
.';;;;;'. ..... .,coodoc.
.,;;;;'. ..',;:::cccc:;,'. .;odddl'
.,;;;;. .,:cccclllllllllool:' ,odddl'
.,:;:;. .;ccccc:;,''''',;cooooo:. ,odddc.
';:::' .,ccclc,.. .':odddc. .cdddo,
.;:::,. ,cccc;. .:oddd:. ,dddd:.
'::::' .ccll:. .ldddo' 'odddc.
,::c:. ,lllc' .';;;::::::::codddd; ,dxxxc.
.,ccc:. .;lllc. ,oooooddddddddddddd; :dxxd:
,cccc. ;llll' .;:ccccccccccccccc;. 'oxxxo'
'cccc, 'loooc. 'lxxxd;
.:lll:. .;ooooc. .;oxxxd:.
,llll;. .;ooddo:'. ..:oxxxxo;.
.:llol,. 'coddddl:;''.........,;codxxxxd:.
.:lool;. .':odddddddddoooodddxxxxxxdl;.
.:ooooc' .';codddddddxxxxxxdol:,.
.;ldddoc'. ...'',,;;;,,''..
.:oddddl:'. .,;:'.
.:odddddoc;,... ..',:ldxxxx;
.,:odddddddoolcc::::::::cllodxxxxxxxd:.
.';clddxxxxxxxxxxxxxxxxxxxxxxoc;'.
..',;:ccllooooooollc:;,'..
......
**/
pragma solidity 0.8.11;
import "../general/RcaGovernable.sol";
import "../library/MerkleProof.sol";
import "../interfaces/IRcaShield.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title RCA Controller
* @notice Controller contract for all RCA vaults.
* This contract creates vaults, emits events when anything happens on a vault,
* keeps track of variables relevant to vault functionality, keeps track of capacities,
* amounts for sale on each vault, prices of tokens, and updates vaults when needed.
* @author Robert M.C. Forster, Romke Jonker, Taek Lee, Chiranjibi Poudyal
*/
contract RcaController is RcaGovernable {
/// @notice Address => whether or not it's a verified shield.
mapping(address => bool) public shieldMapping;
/// @notice Address => whether or not shield is active.
mapping(address => bool) public activeShields;
/// @notice Address => whether or not router is verified.
mapping(address => bool) public isRouterVerified;
/// @notice Fees for users per year for using the system. Ideally just 0 but option is here.
/// In hundredths of %. 1000 == 10%.
uint256 public apr;
/// @notice Amount of time users must wait to withdraw tokens after requesting redemption. In seconds.
uint256 public withdrawalDelay;
/// @notice Discount for purchasing tokens being liquidated from a shield. 1000 == 10%.
uint256 public discount;
/// @notice Address that funds from selling tokens is sent to.
address payable public treasury;
/// @notice Amount of funds for sale on a protocol, sent in by DAO after a hack occurs (in token).
bytes32 public liqForClaimsRoot;
/// @notice The amount of each shield that's currently reserved for hack payouts. 1000 == 10%.
bytes32 public reservedRoot;
/// @notice Root of all underlying token prices--only used if the protocol is doing pricing. Price in Ether.
bytes32 public priceRoot;
/// @notice Nonce to prevent replays of capacity signatures. User => RCA nonce.
mapping(address => uint256) public nonces;
/// @notice Last time each individual shield was checked for update.
mapping(address => uint256) public lastShieldUpdate;
/**
* @dev The update variable flow works in an interesting way to optimize efficiency:
* Each time a user interacts with a specific shield vault, it calls Controller
* for all necessary interactions (events & updates). The general Controller function
* will check when when the last shield update was made vs. all recent other updates.
* If a system update is more recent than the shield update, value is changed.
*/
struct SystemUpdates {
uint32 liqUpdate;
uint32 reservedUpdate;
uint32 withdrawalDelayUpdate;
uint32 discountUpdate;
uint32 aprUpdate;
uint32 treasuryUpdate;
}
SystemUpdates public systemUpdates;
/**
* @dev Events are used to notify the frontend of events on shields. If we have 1,000 shields,
* a centralized event system can tell the frontend which shields to check for a specific user.
*/
event Mint(address indexed rcaShield, address indexed user, uint256 timestamp);
event RedeemRequest(address indexed rcaShield, address indexed user, uint256 timestamp);
event RedeemFinalize(address indexed rcaShield, address indexed user, uint256 timestamp);
event Purchase(address indexed rcaShield, address indexed user, uint256 timestamp);
event ShieldCreated(
address indexed rcaShield,
address indexed underlyingToken,
string name,
string symbol,
uint256 timestamp
);
event ShieldCancelled(address indexed rcaShield);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// modifiers //////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Ensure the sender is a shield.
* @dev We don't want non-shield contracts creating mint, redeem, purchase events.
*/
modifier onlyShield() {
require(shieldMapping[msg.sender], "Caller must be a Shield Vault.");
_;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////// constructor /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Construct with initial privileged addresses for controller.
* @param _governor Complete control of the contracts. Can change all other owners.
* @param _guardian Guardian multisig that can freeze percents after a hack.
* @param _priceOracle Oracle that can submit price root to the ecosystem.
* @param _capOracle Oracle that can submit capacity root to the ecosystem.
* @param _apr Initial fees for the shield (1000 == 10%).
* @param _discount Discount for purchasers of the token (1000 == 10%).
* @param _withdrawalDelay Amount of time (in seconds) users must wait before withdrawing.
* @param _treasury Address of the treasury that Ether funds will be sent to.
*/
constructor(
address _governor,
address _guardian,
address _priceOracle,
address _capOracle,
uint256 _apr,
uint256 _discount,
uint256 _withdrawalDelay,
address payable _treasury
) {
initRcaGovernable(_governor, _guardian, _capOracle, _priceOracle);
apr = _apr;
discount = _discount;
treasury = _treasury;
withdrawalDelay = _withdrawalDelay;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// onlyShield /////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Updates contract, emits event for minting, checks capacity.
* @param _user User that is minting tokens.
* @param _uAmount Underlying token amount being liquidated.
* @param _expiry Time (Unix timestamp) that this request expires.
* @param _v The recovery byte of the signature.
* @param _r Half of the ECDSA signature pair.
* @param _s Half of the ECDSA signature pair.
* @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed.
* @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed.
*/
function mint(
address _user,
uint256 _uAmount,
uint256 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s,
uint256 _newCumLiqForClaims,
bytes32[] calldata _liqForClaimsProof
) external onlyShield {
_update(_newCumLiqForClaims, _liqForClaimsProof, 0, new bytes32[](0), false);
// Confirm the capacity oracle approved this transaction.
verifyCapacitySig(_user, _uAmount, _expiry, _v, _r, _s);
emit Mint(msg.sender, _user, block.timestamp);
}
/**
* @notice Updates contract, emits event for redeem action.
* @param _user User that is redeeming tokens.
* @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed.
* @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed.
* @param _newPercentReserved New percent of the shield that is reserved for hack payouts.
* @param _percentReservedProof Merkle proof to verify the new percent reserved.
*/
function redeemRequest(
address _user,
uint256 _newCumLiqForClaims,
bytes32[] calldata _liqForClaimsProof,
uint256 _newPercentReserved,
bytes32[] calldata _percentReservedProof
) external onlyShield {
_update(_newCumLiqForClaims, _liqForClaimsProof, _newPercentReserved, _percentReservedProof, true);
emit RedeemRequest(msg.sender, _user, block.timestamp);
}
/**
* @notice Updates contract, emits event for redeem action, returns if router is verified.
* @param _user User that is redeeming tokens.
* @param _to Router address which should be used for zapping.
* @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed.
* @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed.
* @param _newPercentReserved New percent of the shield that is reserved for hack payouts.
* @param _percentReservedProof Merkle proof to verify the new percent reserved.
*/
function redeemFinalize(
address _user,
address _to,
uint256 _newCumLiqForClaims,
bytes32[] calldata _liqForClaimsProof,
uint256 _newPercentReserved,
bytes32[] calldata _percentReservedProof
) external onlyShield returns (bool) {
_update(_newCumLiqForClaims, _liqForClaimsProof, _newPercentReserved, _percentReservedProof, true);
emit RedeemFinalize(msg.sender, _user, block.timestamp);
return isRouterVerified[_to];
}
/**
* @notice Updates contract, emits event for purchase action, verifies price.
* @param _user The user that is making the purchase.
* @param _uToken The user that is making the purchase.
* @param _ethPrice The price of one token in Ether.
* @param _priceProof Merkle proof to verify the Ether price of the token.
* @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed.
* @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed.
*/
function purchase(
address _user,
address _uToken,
uint256 _ethPrice,
bytes32[] calldata _priceProof,
uint256 _newCumLiqForClaims,
bytes32[] calldata _liqForClaimsProof
) external onlyShield {
_update(_newCumLiqForClaims, _liqForClaimsProof, 0, new bytes32[](0), false);
verifyPrice(_uToken, _ethPrice, _priceProof);
emit Purchase(msg.sender, _user, block.timestamp);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////// internal //////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice All general updating of shields for a variety of variables that could have changed
* since the last interaction. Amount for sale, whether or not the system is paused, new
* withdrawal delay, new discount for sales, new APR fee for general functionality.
* @param _newCumLiqForClaims New cumulative amount of liquidated tokens if an update is needed.
* @param _liqForClaimsProof Merkle proof to verify the new cumulative liquidated if needed.
* @param _newPercentReserved New percent of tokens of this shield that are reserved.
* @param _percentReservedProof Merkle proof to verify the new percent reserved.
* @param _redeem Whether or not this is a redeem request to know whether to update reserved.
*/
function _update(
uint256 _newCumLiqForClaims,
bytes32[] memory _liqForClaimsProof,
uint256 _newPercentReserved,
bytes32[] memory _percentReservedProof,
bool _redeem
) internal {
IRcaShield shield = IRcaShield(msg.sender);
uint32 lastUpdate = uint32(lastShieldUpdate[msg.sender]);
// Seems kinda messy but not too bad on gas.
SystemUpdates memory updates = systemUpdates;
if (lastUpdate <= updates.treasuryUpdate) shield.setTreasury(treasury);
if (lastUpdate <= updates.discountUpdate) shield.setDiscount(discount);
if (lastUpdate <= updates.withdrawalDelayUpdate) shield.setWithdrawalDelay(withdrawalDelay);
// Update shield here to account for interim period where APR was changed but shield had not updated.
if (lastUpdate <= updates.aprUpdate) {
shield.controllerUpdate(apr, uint256(updates.aprUpdate));
shield.setApr(apr);
}
if (lastUpdate <= updates.liqUpdate) {
// Update potentially needed here as well if amtForSale will grow from APR.
shield.controllerUpdate(apr, uint256(updates.aprUpdate));
verifyLiq(msg.sender, _newCumLiqForClaims, _liqForClaimsProof);
shield.setLiqForClaims(_newCumLiqForClaims);
}
// Only updates if it's a redeem request (which is the only call that's affected by reserved).
if (lastUpdate <= updates.reservedUpdate && _redeem) {
verifyReserved(msg.sender, _newPercentReserved, _percentReservedProof);
shield.setPercentReserved(_newPercentReserved);
}
lastShieldUpdate[msg.sender] = uint32(block.timestamp);
}
/**
* @notice Verify the signature approving the transaction.
* @param _user User that is being minted to.
* @param _amount Amount of underlying tokens being deposited.
* @param _expiry Time (Unix timestamp) that this request expires.
* @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 verifyCapacitySig(
address _user,
uint256 _amount,
uint256 _expiry,
uint8 _v,
bytes32 _r,
bytes32 _s
) internal {
bytes32 digest = keccak256(
abi.encodePacked(
"EASE_RCA_CONTROLLER_1.0",
block.chainid,
address(this),
_user,
msg.sender,
_amount,
nonces[_user]++,
_expiry
)
);
bytes32 message = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", digest));
address signatory = ecrecover(message, _v, _r, _s);
require(signatory == capOracle, "Invalid capacity oracle signature.");
require(block.timestamp <= _expiry, "Capacity permission has expired.");
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////// view ////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Verify the current amount for liquidation.
* @param _shield Address of the shield to verify.
* @param _newCumLiqForClaims New cumulative amount liquidated.
* @param _liqForClaimsProof Proof of the for sale amounts.
*/
function verifyLiq(
address _shield,
uint256 _newCumLiqForClaims,
bytes32[] memory _liqForClaimsProof
) public view {
bytes32 leaf = keccak256(abi.encodePacked(_shield, _newCumLiqForClaims));
require(MerkleProof.verify(_liqForClaimsProof, liqForClaimsRoot, leaf), "Incorrect liq proof.");
}
/**
* @notice Verify price from Ease price oracle.
* @param _shield Address of the shield to find price of.
* @param _value Price of the underlying token (in Ether) for this shield.
* @param _proof Merkle proof.
*/
function verifyPrice(
address _shield,
uint256 _value,
bytes32[] memory _proof
) public view {
bytes32 leaf = keccak256(abi.encodePacked(_shield, _value));
// This doesn't protect against oracle hacks, but does protect against some bugs.
require(_value > 0, "Invalid price submitted.");
require(MerkleProof.verify(_proof, priceRoot, leaf), "Incorrect price proof.");
}
/**
* @notice Verify the percent reserved for a particular shield.
* @param _shield Address of the shield/token to verify reserved.
* @param _percentReserved Percent of shield that's reserved. 10% == 1000.
* @param _proof The Merkle proof verifying the percent reserved.
*/
function verifyReserved(
address _shield,
uint256 _percentReserved,
bytes32[] memory _proof
) public view {
bytes32 leaf = keccak256(abi.encodePacked(_shield, _percentReserved));
require(MerkleProof.verify(_proof, reservedRoot, leaf), "Incorrect capacity proof.");
}
/**
* @notice Makes it easier for frontend to get the balances on many shields.
* @param _user User to find balances of.
* @param _tokens The shields (also tokens) to find the RCA balances for.
*/
function balanceOfs(address _user, address[] calldata _tokens) external view returns (uint256[] memory balances) {
balances = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
uint256 balance = IERC20(_tokens[i]).balanceOf(_user);
balances[i] = balance;
}
}
/**
* @notice Makes it easier for frontend to get the currently withdrawing requests for each shield.
* @param _user User to find requests of.
* @param _shields The shields to find the request data for.
*/
function requestOfs(
address _user,
address[] calldata _shields
) external view returns (IRcaShield.WithdrawRequest[] memory requests) {
requests = new IRcaShield.WithdrawRequest[](_shields.length);
for (uint256 i = 0; i < _shields.length; i++) {
IRcaShield.WithdrawRequest memory request = IRcaShield(_shields[i]).withdrawRequests(_user);
requests[i] = request;
}
}
/**
* @notice Used by frontend to craft signature for a requested transaction.
* @param _user User that is being minted to.
* @param _shield Address of the shield that tokens are being deposited into.
* @param _amount Amount of underlying tokens to deposit.
* @param _nonce User nonce (current nonce +1) that this transaction will be.
* @param _expiry Time (Unix timestamp) that this request will expire.
*/
function getMessageHash(
address _user,
address _shield,
uint256 _amount,
uint256 _nonce,
uint256 _expiry
) external view returns (bytes32) {
return
keccak256(
abi.encodePacked(
"EASE_RCA_CONTROLLER_1.0",
block.chainid,
address(this),
_user,
_shield,
_amount,
_nonce,
_expiry
)
);
}
function getAprUpdate() external view returns (uint32) {
return systemUpdates.aprUpdate;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// onlyGov //////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Initialize a new shield.
* @param _shield Address of the shield to initialize.
*/
function initializeShield(address _shield) external onlyGov {
IRcaShield(_shield).initialize(apr, discount, treasury, withdrawalDelay);
shieldMapping[_shield] = true;
activeShields[_shield] = true;
lastShieldUpdate[_shield] = block.timestamp;
emit ShieldCreated(
_shield,
address(IRcaShield(_shield).uToken()),
IRcaShield(_shield).name(),
IRcaShield(_shield).symbol(),
block.timestamp
);
}
/**
* @notice Governance calls to set the new total amount for sale.
* @param _newLiqRoot Merkle root for new total amounts for sale for each protocol (in token).
* @param _newReservedRoot Reserved root setting all percent reserved back to 0.
*/
function setLiqTotal(bytes32 _newLiqRoot, bytes32 _newReservedRoot) external onlyGov {
liqForClaimsRoot = _newLiqRoot;
systemUpdates.liqUpdate = uint32(block.timestamp);
reservedRoot = _newReservedRoot;
systemUpdates.reservedUpdate = uint32(block.timestamp);
}
/**
* @notice Governance can reset withdrawal delay for amount of time it takes to withdraw from vaults.
* Not a commonly used function, if at all really.
* @param _newWithdrawalDelay New delay (in seconds) for withdrawals.
*/
function setWithdrawalDelay(uint256 _newWithdrawalDelay) external onlyGov {
require(_newWithdrawalDelay <= 86400 * 7, "Withdrawal delay may not be more than 7 days.");
withdrawalDelay = _newWithdrawalDelay;
systemUpdates.withdrawalDelayUpdate = uint32(block.timestamp);
}
/**
* @notice Governance can change the amount of discount for purchasing tokens that are being liquidated.
* @param _newDiscount New discount for purchase in tenths of a percent (1000 == 10%).
*/
function setDiscount(uint256 _newDiscount) external onlyGov {
require(_newDiscount <= 2500, "Discount may not be more than 25%.");
discount = _newDiscount;
systemUpdates.discountUpdate = uint32(block.timestamp);
}
/**
* @notice Governance can set the fees taken per year from a vault. Starts at 0, can update at any time.
* @param _newApr New fees per year for being in the RCA system (1000 == 10%).
*/
function setApr(uint256 _newApr) external onlyGov {
require(_newApr <= 2000, "APR may not be more than 20%.");
apr = _newApr;
systemUpdates.aprUpdate = uint32(block.timestamp);
}
/**
* @notice Governance can set address of the new treasury contract that accepts funds.
* @param _newTreasury New fees per year for being in the RCA system (1000 == 10%).
*/
function setTreasury(address payable _newTreasury) external onlyGov {
treasury = _newTreasury;
systemUpdates.treasuryUpdate = uint32(block.timestamp);
}
/**
* @notice Governance can cancel the shield support.
* @param _shields An array of shield addresses that are being cancelled.
*/
function cancelShield(address[] memory _shields) external onlyGov {
for (uint256 i = 0; i < _shields.length; i++) {
activeShields[_shields[i]] = false;
emit ShieldCancelled(_shields[i]);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////// onlyGuardian ///////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Admin can set the percent paused. This pauses this percent of tokens from each shield
* while the DAO analyzes losses. If a withdrawal occurs while reserved > 0,
* the user will lose this percent of tokens.
* @param _newReservedRoot Percent of shields to temporarily pause for each shield. 1000 == 10%.
*/
function setPercentReserved(bytes32 _newReservedRoot) external onlyGuardian {
reservedRoot = _newReservedRoot;
systemUpdates.reservedUpdate = uint32(block.timestamp);
}
/**
* @notice Admin can set which router is verified and which is not.
* @param _routerAddress Address of a router.
* @param _verified New verified status of the router.
*/
function setRouterVerified(address _routerAddress, bool _verified) external onlyGuardian {
isRouterVerified[_routerAddress] = _verified;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////// onlyPriceOracle //////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @notice Set prices of all tokens with our oracle. This will likely be expanded so that price oracle is a
* smart contract that accepts input from a few sources to increase decentralization.
* @param _newPriceRoot Merkle root for new prices of each underlying token in
* Ether (key is shield address or token for rewards).
*/
function setPrices(bytes32 _newPriceRoot) external onlyPriceOracle {
priceRoot = _newPriceRoot;
}
}
/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.11;
import "../general/Governable.sol";
/**
* @title Governable
* @dev Pretty default ownable but with variable names changed to better convey owner.
*/
contract RcaGovernable is Governable {
address public guardian;
address public priceOracle;
address public capOracle;
event NewGuardian(address indexed oldGuardian, address indexed newGuardian);
event NewPriceOracle(address indexed oldOracle, address indexed newOracle);
event NewCapOracle(address indexed oldOracle, address indexed newOracle);
/**
* @dev The Ownable constructor sets the original s of the contract to the sender
* account.
*/
function initRcaGovernable(
address _governor,
address _guardian,
address _capOracle,
address _priceOracle
) internal {
require(governor() == address(0), "already initialized");
initializeGovernable(_governor);
guardian = _guardian;
capOracle = _capOracle;
priceOracle = _priceOracle;
emit NewGuardian(address(0), _guardian);
emit NewCapOracle(address(0), _capOracle);
emit NewPriceOracle(address(0), _priceOracle);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGuardian() {
require(msg.sender == guardian, "msg.sender is not Guardian.");
_;
}
modifier onlyPriceOracle() {
require(msg.sender == priceOracle, "msg.sender is not price oracle.");
_;
}
modifier onlyCapOracle() {
require(msg.sender == capOracle, "msg.sender is not capacity oracle.");
_;
}
/**
* @notice Allows the current owner to transfer control of the contract to a newOwner.
* @param _newGuardian The address to transfer ownership to.
*/
function setGuardian(address _newGuardian) public onlyGov {
guardian = _newGuardian;
}
function setPriceOracle(address _newPriceOracle) public onlyGov {
priceOracle = _newPriceOracle;
}
function setCapOracle(address _newCapOracle) public onlyGov {
capOracle = _newCapOracle;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
/// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IRcaShield {
function setApr(uint256 apr) external;
function setTreasury(address treasury) external;
function setDiscount(uint256 discount) external;
function setLiqForClaims(uint256 addForSale) external;
function setPercentReserved(uint256 percentPaused) external;
function setWithdrawalDelay(uint256 withdrawalDelay) external;
function initialize(
uint256 apr,
uint256 discount,
address treasury,
uint256 withdrawalDelay
) external;
function name() external returns (string calldata);
function symbol() external returns (string calldata);
function uToken() external returns (IERC20);
function controllerUpdate(uint256 apr, uint256 aprUpdate) external;
struct WithdrawRequest {
uint112 uAmount;
uint112 rcaAmount;
uint32 endTime;
}
function withdrawRequests(address user) external view returns (WithdrawRequest memory);
}
// 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
pragma solidity ^0.8.11;
/**
* @title Governable
* @dev Pretty default ownable but with variable names changed to better convey owner.
*/
contract Governable {
address payable private _governor;
address payable private _pendingGovernor;
event OwnershipTransferred(address indexed previousGovernor, address indexed newGovernor);
event PendingOwnershipTransfer(address indexed from, address indexed to);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function initializeGovernable(address _newGovernor) internal {
require(_governor == address(0), "already initialized");
_governor = payable(_newGovernor);
emit OwnershipTransferred(address(0), _newGovernor);
}
/**
* @return the address of the owner.
*/
function governor() public view returns (address payable) {
return _governor;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGov() {
require(isGov(), "msg.sender is not owner");
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isGov() public view returns (bool) {
return msg.sender == _governor;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newGovernor The address to transfer ownership to.
*/
function transferOwnership(address payable newGovernor) public onlyGov {
_pendingGovernor = newGovernor;
emit PendingOwnershipTransfer(_governor, newGovernor);
}
function receiveOwnership() public {
require(msg.sender == _pendingGovernor, "Only pending governor can call this function");
_transferOwnership(_pendingGovernor);
_pendingGovernor = payable(address(0));
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newGovernor The address to transfer ownership to.
*/
function _transferOwnership(address payable newGovernor) internal {
require(newGovernor != address(0));
emit OwnershipTransferred(_governor, newGovernor);
_governor = newGovernor;
}
uint256[50] private __gap;
}
|
Verify the current amount for liquidation. _shield Address of the shield to verify. _newCumLiqForClaims New cumulative amount liquidated. _liqForClaimsProof Proof of the for sale amounts./
|
function verifyLiq(
address _shield,
uint256 _newCumLiqForClaims,
bytes32[] memory _liqForClaimsProof
) public view {
bytes32 leaf = keccak256(abi.encodePacked(_shield, _newCumLiqForClaims));
require(MerkleProof.verify(_liqForClaimsProof, liqForClaimsRoot, leaf), "Incorrect liq proof.");
}
| 10,309,571 |
// SPDX-License-Identifier: MIT
// Creator: base64.tech
pragma solidity ^0.8.13;
import "./ERC721A.sol";
/**
* @dev Extension of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard,
* that allows for Non Escrow Staking. By calling the stake function on a token, you disable
* the ability to transfer the token. By calling the unstake function on a token you re-enable
* the ability to transfer the token.
*
* This implementation extends ERC721A, but can be modified to extend your own ERC721 implementation
* or the standard Open Zeppelin version.
*/
abstract contract ERC721NES is ERC721A {
// This is an optional reference to an external contract allows
// you to abstract away your staking interface to another contract.
// if this variable is set, stake / unstake can only be called from
// the stakingController if it is not set stake / unstake can be called
// directly on the implementing contract.
address public stakingController;
// Event published when a token is staked.
event Staked(uint256 tokenId);
// Event published when a token is unstaked.
event Unstaked(uint256 tokenId);
// Mapping of tokenId storing its staked status
mapping(uint256 => bool) public tokenToIsStaked;
/**
* @dev sets stakingController, scope of this method is internal, so this defaults
* to requiring setting the staking controller contact upon deployment or requires
* a public OnlyOwner helper method to be exposed in the implementing contract.
*/
function _setStakingController(address _stakingController) internal {
stakingController = _stakingController;
}
/**
* @dev returns whether a token is currently staked
*/
function isStaked(uint256 tokenId) public view returns (bool) {
return tokenToIsStaked[tokenId];
}
/**
* @dev marks a token as staked, calling this function
* you disable the ability to transfer the token.
*/
function _stake(uint256 tokenId) internal {
require(!isStaked(tokenId), "token is already staked");
tokenToIsStaked[tokenId] = true;
emit Staked(tokenId);
}
/**
* @dev marks a token as unstaked. By calling this function
* you re-enable the ability to transfer the token.
*/
function _unstake(uint256 tokenId) internal {
require(isStaked(tokenId), "token isn't staked");
tokenToIsStaked[tokenId] = false;
emit Unstaked(tokenId);
}
/**
* @dev marks a token as staked, can only be performed by delegated
* staking controller contract. By calling this function you
* disable the ability to transfer the token.
*/
function stakeFromController(uint256 tokenId, address originator) public {
require(
msg.sender == stakingController,
"Function can only be called from staking controller contract"
);
require(
ownerOf(tokenId) == originator,
"Originator is not the owner of this token"
);
_stake(tokenId);
}
/**
* @dev marks a token as unstaked, can only be performed delegated
* staking controller contract. By calling this function you
* re-enable the ability to transfer the token.
*/
function unstakeFromController(uint256 tokenId, address originator) public {
require(
msg.sender == stakingController,
"Function can only be called from staking controller contract"
);
require(
ownerOf(tokenId) == originator,
"Originator is not the owner of this token"
);
_unstake(tokenId);
}
/**
* @dev perform safe mint and stake
*/
function _safemintAndStake(address to, uint256 quantity) internal {
uint256 startTokenId = _currentIndex;
for (uint256 i = 0; i < quantity; i++) {
startTokenId++;
tokenToIsStaked[startTokenId] = true;
}
_safeMint(to, quantity, "");
}
/**
* @dev perform mint and stake
*/
function _mintAndStake(address to, uint256 quantity) internal {
uint256 startTokenId = _currentIndex;
for (uint256 i = 0; i < quantity; i++) {
startTokenId++;
tokenToIsStaked[startTokenId] = true;
}
_mint(to, quantity, "", false);
}
/**
* @dev overrides transferFrom to prevent transfer if token is staked
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
require(
isStaked(tokenId) == false,
"You can not transfer a staked token"
);
super.transferFrom(from, to, tokenId);
}
/**
* @dev overrides safeTransferFrom to prevent transfer if token is staked
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
require(
isStaked(tokenId) == false,
"You can not transfer a staked token"
);
super.safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev overrides safeTransferFrom to prevent transfer if token is staked
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
require(
isStaked(tokenId) == false,
"You can not transfer a staked token"
);
super.safeTransferFrom(from, to, tokenId, _data);
}
}
|
perform mint and stake/
|
function _mintAndStake(address to, uint256 quantity) internal {
uint256 startTokenId = _currentIndex;
for (uint256 i = 0; i < quantity; i++) {
startTokenId++;
tokenToIsStaked[startTokenId] = true;
}
_mint(to, quantity, "", false);
}
| 5,415,085 |
./full_match/1/0x500a7eAB8ae0fC36Bf586A8F5149d2885A3b40a3/sources/browser/Pool.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 halvFactor = 2**( ( block.number.sub(startBlock) ).div(halvingPeriod) );
uint256 TigerReward = multiplier.mul(InitTigerPerBlock).mul(pool.allocPoint).div(totalAllocPoint).div(halvFactor);
tiger.mint(address(this), TigerReward);
pool.accTigerPerShare = pool.accTigerPerShare.add(TigerReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 9,613,294 |
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
// Use original Ownable.sol
import "./lib/OwnableOriginal.sol";
// Storage
import "./storage/McModifier.sol"; /// McStorage.sol is inherited
import "./storage/McConstants.sol";
// idle.finance v3
//import "./idle-contracts-v3/contracts/interfaces/IIdleTokenV3.sol";
// AAVE
import "./aave/contracts/interfaces/ILendingPool.sol";
import "./aave/contracts/interfaces/ILendingPoolCore.sol";
import "./aave/contracts/interfaces/ILendingPoolAddressesProvider.sol";
import "./aave/contracts/interfaces/IAToken.sol";
/***
* @notice - This contract is that ...
**/
contract CrowdsourcingPortalForArt is OwnableOriginal(msg.sender), McModifier, McConstants {
using SafeMath for uint;
uint artWorkId;
uint newArtWorkId;
uint totalDepositedDai;
uint artWorkVotingRound;
mapping (uint => uint[]) topProjectArtWorkIds; /// Key is "artWorkVotingRound"
mapping (uint => uint) topProjectVoteCount; /// Key is "companyProfileRound"
//uint topProjectVoteCount;
mapping (uint => uint) topProjectArtWorkIdsCounter; /// Key is "companyProfileRound"
IERC20 public dai;
ILendingPool public lendingPool;
ILendingPoolCore public lendingPoolCore;
ILendingPoolAddressesProvider public lendingPoolAddressesProvider;
IAToken public aDai;
constructor(address daiAddress, address _lendingPool, address _lendingPoolCore, address _lendingPoolAddressesProvider, address _aDai) public {
admin = address(this); /// Temporary
//admin = msg.sender;
dai = IERC20(daiAddress);
lendingPool = ILendingPool(_lendingPool);
lendingPoolCore = ILendingPoolCore(_lendingPoolCore);
lendingPoolAddressesProvider = ILendingPoolAddressesProvider(_lendingPoolAddressesProvider);
aDai = IAToken(_aDai);
/// every 1 weeks, voting deadline is updated
votingInterval = 10; /// For testing (Every 10 second, voting deadline is updated)
//votingInterval = 1 weeks; /// For actual
artWorkDeadline = now.add(votingInterval);
}
/***
* @notice - Join Pool (Deposit DAI into idle-contracts-v3) for getting right of voting
**/
function joinPool(address _reserve, uint256 _amount, uint16 _referralCode) public returns (bool) {
/// Transfer from wallet address
dai.transferFrom(msg.sender, address(this), _amount);
/// Approve LendingPool contract to move your DAI
dai.approve(lendingPoolAddressesProvider.getLendingPoolCore(), _amount);
/// Deposit DAI
lendingPool.deposit(_reserve, _amount, _referralCode);
/// Save deposited amount each user
depositedDai[msg.sender] = _amount;
totalDepositedDai.add(_amount);
emit JoinPool(msg.sender, _reserve, _amount, totalDepositedDai);
}
/***
* @notice - Create artwork and list them.
* @return - New artwork id
**/
function createArtWork(string memory artWorkHash) public returns (uint newArtWorkId) {
// The first artwork will have an ID of 1
//newArtWorkId = artWorkId.add(1);
newArtWorkId = artWorkId++;
artWorkOwner[newArtWorkId] = msg.sender;
artWorkState[newArtWorkId] = ArtWorkState.Active;
artWorkDetails[newArtWorkId] = artWorkHash;
emit CreateArtWork(newArtWorkId,
artWorkOwner[newArtWorkId],
artWorkState[newArtWorkId],
artWorkDetails[newArtWorkId]);
}
/***
* @notice - Vote for selecting the best artwork (voter is only user who deposited before)
**/
function voteForArtWork(uint256 artWorkIdToVoteFor) public {
/// Can only vote if they joined a previous iteration round...
/// Check if the msg.sender has given approval rights to our steward to vote on their behalf
uint currentArtWork = usersNominatedProject[artWorkVotingRound][msg.sender];
if (currentArtWork != 0) {
artWorkVotes[artWorkVotingRound][currentArtWork] = artWorkVotes[artWorkVotingRound][currentArtWork].sub(depositedDai[msg.sender]);
}
/// "artWorkVotingRound" is what number of voting round are.
/// Save what voting round is / who user voted for / how much user deposited
artWorkVotes[artWorkVotingRound][artWorkIdToVoteFor] = artWorkVotes[artWorkVotingRound][artWorkIdToVoteFor].add(depositedDai[msg.sender]);
/// Save who user voted for
usersNominatedProject[artWorkVotingRound][msg.sender] = artWorkIdToVoteFor;
/// Update voting count of voted artworkId
artworkVoteCount[artWorkVotingRound][artWorkIdToVoteFor] = artworkVoteCount[artWorkVotingRound][artWorkIdToVoteFor].add(1);
/// Update current top project (artwork)
uint topProjectVoteCount;
uint[] memory topProjectArtWorkIds;
(topProjectVoteCount, topProjectArtWorkIds) = getTopProject(artWorkVotingRound);
emit VoteForArtWork(artWorkVotingRound,
artWorkVotes[artWorkVotingRound][artWorkIdToVoteFor],
artworkVoteCount[artWorkVotingRound][artWorkIdToVoteFor],
topProjectVoteCount,
topProjectArtWorkIds);
}
function getTopProject(uint artWorkVotingRound) public returns (uint topProjectVoteCount, uint[] memory topProjectArtWorkIds) {
/// Update current top project (artwork)
uint currentArtWorkId = artWorkId;
for (uint i=0; i < currentArtWorkId; i++) {
if (artworkVoteCount[artWorkVotingRound][i] >= topProjectVoteCount) {
topProjectVoteCount = artworkVoteCount[artWorkVotingRound][i];
}
}
uint[] memory _topProjectArtWorkIds;
getTopProjectArtWorkIds(artWorkVotingRound, topProjectVoteCount);
_topProjectArtWorkIds = returnTopProjectArtWorkIds(artWorkVotingRound);
return (topProjectVoteCount, _topProjectArtWorkIds);
}
/// Need to execute for-loop in frontend to get TopProjectArtWorkIds
function getTopProjectArtWorkIds(uint _artWorkVotingRound, uint _topProjectVoteCount) public {
uint currentArtWorkId = artWorkId;
for (uint i=0; i < currentArtWorkId; i++) {
if (artworkVoteCount[_artWorkVotingRound][i] == _topProjectVoteCount) {
topProjectArtWorkIds[_artWorkVotingRound].push(i);
}
}
}
/***
* @notice - Storage can't specify returned value. That's why it create memory instead of storage and utilize as retruned value
**/
function returnTopProjectArtWorkIds(uint _artWorkVotingRound) public view returns(uint[] memory _topProjectArtWorkIdsMemory) {
uint topProjectArtWorkIdsLength = topProjectArtWorkIds[_artWorkVotingRound].length;
uint[] memory topProjectArtWorkIdsMemory = new uint[](topProjectArtWorkIdsLength);
topProjectArtWorkIdsMemory = topProjectArtWorkIds[_artWorkVotingRound];
return topProjectArtWorkIdsMemory;
}
/***
* @notice - Distribute fund into selected ArtWork by voting)
**/
function distributeFunds(uint _artWorkVotingRound, address _reserve, uint16 _referralCode) public onlyAdmin(admin) {
// On a *whatever we decide basis* the funds are distributed to the winning project
// E.g. every 2 weeks, the project with the most votes gets the generated interest.
require(artWorkDeadline < now, "current vote still active");
/// Redeem
address _user = address(this);
uint redeemAmount = aDai.balanceOf(_user);
uint principalBalance = aDai.principalBalanceOf(_user);
aDai.redeem(redeemAmount);
/// Calculate current interest income
uint redeemedAmount = dai.balanceOf(_user);
uint currentInterestIncome = redeemedAmount - principalBalance;
/// Count voting every ArtWork
uint _topProjectVoteCount;
uint[] memory _topProjectArtWorkIds;
(_topProjectVoteCount, _topProjectArtWorkIds) = getTopProject(_artWorkVotingRound);
/// Select winning address
/// Transfer redeemed Interest income into winning address
address[] memory winningAddressList;
for (uint i=0; i < _topProjectArtWorkIds.length; i++) {
winningAddressList = returnWinningAddressList(_artWorkVotingRound, _topProjectArtWorkIds[i]);
}
emit ReturnWinningAddressList(winningAddressList);
//uint numberOfWinningAddress = 1;
uint numberOfWinningAddress = winningAddressList.length;
uint dividedInterestIncome = currentInterestIncome.div(numberOfWinningAddress);
for (uint w=0; w < winningAddressList.length; w++) {
address winningAddress = winningAddressList[w];
dai.approve(winningAddress, dividedInterestIncome);
dai.transfer(winningAddress, dividedInterestIncome);
emit WinningAddressTransferred(winningAddress);
}
/// Re-lending principal balance into AAVE
dai.approve(lendingPoolAddressesProvider.getLendingPoolCore(), principalBalance);
lendingPool.deposit(_reserve, principalBalance, _referralCode);
/// Set next voting deadline
artWorkDeadline = artWorkDeadline.add(votingInterval);
/// Set next voting round
/// Initialize the top project of next voting round
artWorkVotingRound = artWorkVotingRound.add(1); /// "artWorkVotingRound" is number of voting round
topProjectVoteCount[artWorkVotingRound] = 0;
emit DistributeFunds(redeemedAmount, principalBalance, currentInterestIncome);
//emit InitializeAfterDistributeFunds(_topProjectArtWorkIds[artWorkVotingRound], _topProjectVoteCount);
}
function returnWinningAddressList(uint _artWorkVotingRound, uint _votedCompanyProfileId) public view returns(address[] memory _winningAddressListMemory) {
uint winningAddressListLength = votedUserAddress[_artWorkVotingRound][_votedCompanyProfileId].length;
address[] memory winningAddressListMemory = new address[](winningAddressListLength);
winningAddressListMemory = votedUserAddress[_artWorkVotingRound][_votedCompanyProfileId];
return winningAddressListMemory;
}
/***
* @notice - Getter Function
**/
function balanceOfContract() public view returns (uint balanceOfContract_DAI, uint balanceOfContract_ETH) {
return (dai.balanceOf(address(this)), address(this).balance);
}
/***
* @notice - Test Functions
**/
function getAaveRelatedFunction() public view returns (uint redeemAmount, uint principalBalance) {
/// Redeem
address _user = address(this);
uint redeemAmount = aDai.balanceOf(_user);
uint principalBalance = aDai.principalBalanceOf(_user);
return (redeemAmount, principalBalance);
}
}
|
- Test Functions/
|
function getAaveRelatedFunction() public view returns (uint redeemAmount, uint principalBalance) {
address _user = address(this);
uint redeemAmount = aDai.balanceOf(_user);
uint principalBalance = aDai.principalBalanceOf(_user);
return (redeemAmount, principalBalance);
| 5,536,831 |
/**
*Submitted for verification at Etherscan.io on 2021-11-14
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/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 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/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/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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);
}
}
pragma solidity >=0.7.0 <0.9.0;
contract RISEOFCOONS is ERC721Enumerable, Ownable {
using Strings for uint256;
string baseURI;
string public baseExtension = ".json";
uint256 public cost = 0.05 ether;
uint256 public maxSupply = 9000;
uint256 public maxMintAmount = 20;
bool public paused = true;
bool public revealed = false;
string public notRevealedUri;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedUri
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedUri);
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
// public
function mint(uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, supply + i);
}
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner() {
revealed = true;
}
function setCost(uint256 _newCost) public onlyOwner() {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
}
|
Interface of the ERC165 standard, as defined in the Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}./
|
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
pragma solidity ^0.8.0;
}
| 15,116,307 |
./full_match/1/0x8d6467faa693BB1E1ff0CbbCCeE9C79D19740718/sources/src/contracts/FraxEtherRedemptionQueue.sol
|
Recovers ERC20 tokens mistakenly sent to this contract _tokenAddress Address of the token _tokenAmount Amount of the token
|
function recoverErc20(address _tokenAddress, uint256 _tokenAmount) external {
_requireSenderIsTimelock();
}
| 3,063,050 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./interfaces/IMark2Market.sol";
import "./interfaces/IPriceGetter.sol";
import "./registries/Portfolio.sol";
import "./Vault.sol";
contract Mark2Market is IMark2Market, Initializable, AccessControlUpgradeable, UUPSUpgradeable{
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
// --- fields
Vault public vault;
Portfolio public portfolio;
// --- events
event VaultUpdated(address vault);
event PortfolioUpdated(address portfolio);
// --- modifiers
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Restricted to admins");
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function initialize() initializer public {
__AccessControl_init();
__UUPSUpgradeable_init();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(UPGRADER_ROLE, msg.sender);
}
function _authorizeUpgrade(address newImplementation)
internal
onlyRole(UPGRADER_ROLE)
override
{}
// --- setters
function setVault(address _vault) external onlyAdmin {
require(_vault != address(0), "Zero address not allowed");
vault = Vault(_vault);
emit VaultUpdated(_vault);
}
function setPortfolio(address _portfolio) external onlyAdmin {
require(_portfolio != address(0), "Zero address not allowed");
portfolio = Portfolio(_portfolio);
emit PortfolioUpdated(_portfolio);
}
// --- logic
function assetPricesView() public view returns(AssetPrices[] memory){
return assetPrices().assetPrices;
}
function assetPrices() public view override returns (TotalAssetPrices memory) {
Portfolio.AssetInfo[] memory assetInfos = portfolio.getAllAssetInfos();
uint256 totalUsdcPrice = 0;
uint256 count = assetInfos.length;
AssetPrices[] memory assetPrices = new AssetPrices[](count);
for (uint8 i = 0; i < count; i++) {
Portfolio.AssetInfo memory assetInfo = assetInfos[i];
uint256 amountInVault = _currentAmountInVault(assetInfo.asset);
IPriceGetter priceGetter = IPriceGetter(assetInfo.priceGetter);
uint256 usdcPriceDenominator = priceGetter.denominator();
uint256 usdcSellPrice = priceGetter.getUsdcSellPrice();
uint256 usdcBuyPrice = priceGetter.getUsdcBuyPrice();
// in decimals: 18 + 18 - 18 => 18
uint256 usdcPriceInVault = (amountInVault * usdcSellPrice) / usdcPriceDenominator;
totalUsdcPrice += usdcPriceInVault;
assetPrices[i] = AssetPrices(
assetInfo.asset,
amountInVault,
usdcPriceInVault,
usdcPriceDenominator,
usdcSellPrice,
usdcBuyPrice,
IERC20Metadata(assetInfo.asset).decimals(),
IERC20Metadata(assetInfo.asset).name(),
IERC20Metadata(assetInfo.asset).symbol()
);
}
TotalAssetPrices memory totalPrices = TotalAssetPrices(assetPrices, totalUsdcPrice);
return totalPrices;
}
function totalSellAssets() public view override returns(uint256){
return totalAssets(true);
}
function totalBuyAssets() public view override returns(uint256){
return totalAssets(false);
}
function totalAssets(bool sell) internal view returns (uint256)
{
Portfolio.AssetWeight[] memory assetWeights = portfolio.getAllAssetWeights();
uint256 totalUsdcPrice = 0;
uint256 count = assetWeights.length;
for (uint8 i = 0; i < count; i++) {
Portfolio.AssetWeight memory assetWeight = assetWeights[i];
uint256 amountInVault = _currentAmountInVault(assetWeight.asset);
Portfolio.AssetInfo memory assetInfo = portfolio.getAssetInfo(assetWeight.asset);
IPriceGetter priceGetter = IPriceGetter(assetInfo.priceGetter);
uint256 usdcPriceDenominator = priceGetter.denominator();
uint256 usdcPrice;
if(sell)
usdcPrice = priceGetter.getUsdcSellPrice();
else
usdcPrice = priceGetter.getUsdcBuyPrice();
// in decimals: 18 + 18 - 18 => 18
uint256 usdcPriceInVault = (amountInVault * usdcPrice) / usdcPriceDenominator;
totalUsdcPrice += usdcPriceInVault;
}
return totalUsdcPrice;
}
function assetPricesForBalance() external view override returns (BalanceAssetPrices[] memory) {
return assetPricesForBalance(address(0), 0);
}
/**
* @param withdrawToken Token to withdraw
* @param withdrawAmount Not normalized amount to withdraw
*/
function assetPricesForBalance(address withdrawToken, uint256 withdrawAmount)
public
view
override
returns (BalanceAssetPrices[] memory)
{
if (withdrawToken != address(0)) {
// normalize withdrawAmount to 18 decimals
//TODO: denominator usage
uint256 withdrawAmountDenominator = 10**(18 - IERC20Metadata(withdrawToken).decimals());
withdrawAmount = withdrawAmount * withdrawAmountDenominator;
}
uint256 totalUsdcPrice = totalSellAssets();
// 3. validate withdrawAmount
// use `if` instead of `require` because less gas when need to build complex string for revert
if (totalUsdcPrice < withdrawAmount) {
revert(string(
abi.encodePacked(
"Withdraw more than total: ",
Strings.toString(withdrawAmount),
" > ",
Strings.toString(totalUsdcPrice)
)
));
}
// 4. correct total with withdrawAmount
totalUsdcPrice = totalUsdcPrice - withdrawAmount;
// 5. calc diffs to target values
Portfolio.AssetWeight[] memory assetWeights = portfolio.getAllAssetWeights();
uint256 count = assetWeights.length;
BalanceAssetPrices[] memory assetPrices = new BalanceAssetPrices[](count);
for (uint8 i = 0; i < count; i++) {
Portfolio.AssetWeight memory assetWeight = assetWeights[i];
int256 diffToTarget = 0;
bool targetIsZero = false;
(diffToTarget, targetIsZero) = _diffToTarget(totalUsdcPrice, assetWeight);
// update diff for withdrawn token
if (withdrawAmount > 0 && assetWeight.asset == withdrawToken) {
diffToTarget = diffToTarget + int256(withdrawAmount);
}
assetPrices[i] = BalanceAssetPrices(
assetWeight.asset,
diffToTarget,
targetIsZero
);
}
return assetPrices;
}
/**
* @param totalUsdcPrice - Total normilized to 10**18
* @param assetWeight - Token address to calc
* @return normalized to 10**18 signed diff amount and mark that mean that need sell all
*/
function _diffToTarget(uint256 totalUsdcPrice, Portfolio.AssetWeight memory assetWeight)
internal
view
returns (
int256,
bool
)
{
address asset = assetWeight.asset;
uint256 targetUsdcAmount = (totalUsdcPrice * assetWeight.targetWeight) /
portfolio.TOTAL_WEIGHT();
Portfolio.AssetInfo memory assetInfo = portfolio.getAssetInfo(asset);
IPriceGetter priceGetter = IPriceGetter(assetInfo.priceGetter);
uint256 usdcPriceDenominator = priceGetter.denominator();
uint256 usdcBuyPrice = priceGetter.getUsdcBuyPrice();
// in decimals: 18 * 18 / 18 => 18
uint256 targetTokenAmount = (targetUsdcAmount * usdcPriceDenominator) / usdcBuyPrice;
// normalize currentAmount to 18 decimals
uint256 currentAmount = _currentAmountInVault(asset);
bool targetIsZero;
if (targetTokenAmount == 0) {
targetIsZero = true;
} else {
targetIsZero = false;
}
int256 diff = int256(targetTokenAmount) - int256(currentAmount);
return (diff, targetIsZero);
}
function _currentAmountInVault(address asset) internal view returns (uint256){
// normalize currentAmount to 18 decimals
uint256 currentAmount = IERC20(asset).balanceOf(address(vault));
//TODO: denominator usage
uint256 denominator = 10 ** (18 - IERC20Metadata(asset).decimals());
currentAmount = currentAmount * denominator;
return currentAmount;
}
}
|
totalUsdcPrice - Total normilized to 1018 assetWeight - Token address to calc return normalized to 1018 signed diff amount and mark that mean that need sell all/ in decimals: 18 18 / 18 => 18 normalize currentAmount to 18 decimals
|
function _diffToTarget(uint256 totalUsdcPrice, Portfolio.AssetWeight memory assetWeight)
internal
view
returns (
int256,
bool
)
{
address asset = assetWeight.asset;
uint256 targetUsdcAmount = (totalUsdcPrice * assetWeight.targetWeight) /
portfolio.TOTAL_WEIGHT();
Portfolio.AssetInfo memory assetInfo = portfolio.getAssetInfo(asset);
IPriceGetter priceGetter = IPriceGetter(assetInfo.priceGetter);
uint256 usdcPriceDenominator = priceGetter.denominator();
uint256 usdcBuyPrice = priceGetter.getUsdcBuyPrice();
uint256 targetTokenAmount = (targetUsdcAmount * usdcPriceDenominator) / usdcBuyPrice;
uint256 currentAmount = _currentAmountInVault(asset);
bool targetIsZero;
if (targetTokenAmount == 0) {
targetIsZero = true;
targetIsZero = false;
}
int256 diff = int256(targetTokenAmount) - int256(currentAmount);
return (diff, targetIsZero);
}
| 1,051,219 |
./full_match/42220/0xC5317D77a601262c81602900Ebcf299d4b141e01/sources/ABVStrat.sol
|
it calculates how much 'want' the strategy has working in the farm.
|
function balanceOfPool() public view returns (uint256) {
return IAlphaBetaFarm(chef).stakedTokens(poolId, address(this));
}
| 16,325,914 |
/**
* This smart contract code is Copyright 2018 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* This smart contract code is Copyright 2017 TokenMarket Ltd. For more information see https://tokenmarket.net
*
* Licensed under the Apache License, version 2.0: https://github.com/TokenMarketNet/ico/blob/master/LICENSE.txt
*/
/**
* Deserialize bytes payloads.
*
* Values are in big-endian byte order.
*
*/
library BytesDeserializer {
/**
* Extract 256-bit worth of data from the bytes stream.
*/
function slice32(bytes b, uint offset) constant returns (bytes32) {
bytes32 out;
for (uint i = 0; i < 32; i++) {
out |= bytes32(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
/**
* Extract Ethereum address worth of data from the bytes stream.
*/
function sliceAddress(bytes b, uint offset) constant returns (address) {
bytes32 out;
for (uint i = 0; i < 20; i++) {
out |= bytes32(b[offset + i] & 0xFF) >> ((i+12) * 8);
}
return address(uint(out));
}
/**
* Extract 128-bit worth of data from the bytes stream.
*/
function slice16(bytes b, uint offset) constant returns (bytes16) {
bytes16 out;
for (uint i = 0; i < 16; i++) {
out |= bytes16(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
/**
* Extract 32-bit worth of data from the bytes stream.
*/
function slice4(bytes b, uint offset) constant returns (bytes4) {
bytes4 out;
for (uint i = 0; i < 4; i++) {
out |= bytes4(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
/**
* Extract 16-bit worth of data from the bytes stream.
*/
function slice2(bytes b, uint offset) constant returns (bytes2) {
bytes2 out;
for (uint i = 0; i < 2; i++) {
out |= bytes2(b[offset + i] & 0xFF) >> (i * 8);
}
return out;
}
}
/**
* @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 Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
* It's also recommended that you define constants in the contract, like ROLE_ADMIN below,
* to avoid typos.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
/**
* A constant role name for indicating admins.
*/
string public constant ROLE_ADMIN = "admin";
/**
* @dev constructor. Sets msg.sender as admin by default
*/
function RBAC()
public
{
addRole(msg.sender, ROLE_ADMIN);
}
/**
* @dev reverts if addr does not have role
* @param addr address
* @param roleName the name of the role
* // reverts
*/
function checkRole(address addr, string roleName)
view
public
{
roles[roleName].check(addr);
}
/**
* @dev determine if addr has role
* @param addr address
* @param roleName the name of the role
* @return bool
*/
function hasRole(address addr, string roleName)
view
public
returns (bool)
{
return roles[roleName].has(addr);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function adminAddRole(address addr, string roleName)
onlyAdmin
public
{
addRole(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function adminRemoveRole(address addr, string roleName)
onlyAdmin
public
{
removeRole(addr, roleName);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function addRole(address addr, string roleName)
internal
{
roles[roleName].add(addr);
RoleAdded(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function removeRole(address addr, string roleName)
internal
{
roles[roleName].remove(addr);
RoleRemoved(addr, roleName);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param roleName the name of the role
* // reverts
*/
modifier onlyRole(string roleName)
{
checkRole(msg.sender, roleName);
_;
}
/**
* @dev modifier to scope access to admins
* // reverts
*/
modifier onlyAdmin()
{
checkRole(msg.sender, ROLE_ADMIN);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param roleNames the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] roleNames) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < roleNames.length; i++) {
// if (hasRole(msg.sender, roleNames[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface InvestorToken {
function transferInvestorTokens(address, uint256);
}
/// @title TokenMarket Exchange Smart Contract
/// @author TokenMarket Ltd. / Ville Sundell <ville at tokenmarket.net> and Rainer Koirikivi <rainer at tokenmarket.net>
contract Exchange is RBAC {
using SafeMath for uint256;
using BytesDeserializer for bytes;
// Roles for Role Based Access Control, initially the deployer account will
// have all of these roles:
string public constant ROLE_FORCED = "forced";
string public constant ROLE_TRANSFER_TOKENS = "transfer tokens";
string public constant ROLE_TRANSFER_INVESTOR_TOKENS = "transfer investor tokens";
string public constant ROLE_CLAIM = "claim";
string public constant ROLE_WITHDRAW = "withdraw";
string public constant ROLE_TRADE = "trade";
string public constant ROLE_CHANGE_DELAY = "change delay";
string public constant ROLE_SET_FEEACCOUNT = "set feeaccount";
string public constant ROLE_TOKEN_WHITELIST = "token whitelist user";
/// @dev Is the withdrawal transfer (identified by the hash) executed:
mapping(bytes32 => bool) public withdrawn;
/// @dev Is the out-bound transfer (identified by the hash) executed:
mapping(bytes32 => bool) public transferred;
/// @dev Is the token whitelisted for deposit:
mapping(address => bool) public tokenWhitelist;
/// @dev Keeping account of the total supply per token we posses:
mapping(address => uint256) public tokensTotal;
/// @dev Keeping account what tokens the user owns, and how many:
mapping(address => mapping(address => uint256)) public balanceOf;
/// @dev How much of the order (identified by hash) has been filled:
mapping (bytes32 => uint256) public orderFilled;
/// @dev Account where fees should be deposited to:
address public feeAccount;
/// @dev This defines the delay in seconds between user initiang withdrawal
/// by themselves with withdrawRequest(), and finalizing the withdrawal
/// with withdrawUser():
uint256 public delay;
/// @dev This is emitted when token is added or removed from the whitelist:
event TokenWhitelistUpdated(address token, bool status);
/// @dev This is emitted when fee account is changed
event FeeAccountChanged(address newFeeAccocunt);
/// @dev This is emitted when delay between the withdrawRequest() and withdrawUser() is changed:
event DelayChanged(uint256 newDelay);
/// @dev This is emitted when user deposits either ether (token 0x0) or tokens:
event Deposited(address token, address who, uint256 amount, uint256 balance);
/// @dev This is emitted when tokens are forcefully pushed back to user (for example because of contract update):
event Forced(address token, address who, uint256 amount);
/// @dev This is emitted when user is Withdrawing ethers (token 0x0) or tokens with withdrawUser():
event Withdrawn(address token, address who, uint256 amount, uint256 balance);
/// @dev This is emitted when user starts withdrawal process with withdrawRequest():
event Requested(address token, address who, uint256 amount, uint256 index);
/// @dev This is emitted when Investor Interaction Contract tokens are transferred:
event TransferredInvestorTokens(address, address, address, uint256);
/// @dev This is emitted when tokens are transferred inside this Exchange smart contract:
event TransferredTokens(address, address, address, uint256, uint256, uint256);
/// @dev This is emitted when order gets executed, one for each "side" (right and left):
event OrderExecuted(
bytes32 orderHash,
address maker,
address baseToken,
address quoteToken,
address feeToken,
uint256 baseAmountFilled,
uint256 quoteAmountFilled,
uint256 feePaid,
uint256 baseTokenBalance,
uint256 quoteTokenBalance,
uint256 feeTokenBalance
);
/// @dev This struct will have information on withdrawals initiated with withdrawRequest()
struct Withdrawal {
address user;
address token;
uint256 amount;
uint256 createdAt;
bool executed;
}
/// @dev This is a list of withdrawals initiated with withdrawRequest()
/// and which can be finalized by withdrawUser(index).
Withdrawal[] withdrawals;
enum OrderType {Buy, Sell}
/// @dev This struct is containing all the relevant information from the
/// initiating user which can be used as one "side" of each trade
/// trade() needs two of these, once for each "side" (left and right).
struct Order {
OrderType orderType;
address maker;
address baseToken;
address quoteToken;
address feeToken;
uint256 amount;
uint256 priceNumerator;
uint256 priceDenominator;
uint256 feeNumerator;
uint256 feeDenominator;
uint256 expiresAt;
uint256 nonce;
}
/// @dev Upon deployment, user withdrawal delay is set, and the initial roles
/// @param _delay Minimum delay in seconds between withdrawRequest() and withdrawUser()
function Exchange(uint256 _delay) {
delay = _delay;
feeAccount = msg.sender;
addRole(msg.sender, ROLE_FORCED);
addRole(msg.sender, ROLE_TRANSFER_TOKENS);
addRole(msg.sender, ROLE_TRANSFER_INVESTOR_TOKENS);
addRole(msg.sender, ROLE_CLAIM);
addRole(msg.sender, ROLE_WITHDRAW);
addRole(msg.sender, ROLE_TRADE);
addRole(msg.sender, ROLE_CHANGE_DELAY);
addRole(msg.sender, ROLE_SET_FEEACCOUNT);
addRole(msg.sender, ROLE_TOKEN_WHITELIST);
}
/// @dev Update token whitelist: only whitelisted tokens can be deposited
/// @param token The token whose whitelist status will be changed
/// @param status Is the token whitelisted or not
function updateTokenWhitelist(address token, bool status) external onlyRole(ROLE_TOKEN_WHITELIST) {
tokenWhitelist[token] = status;
TokenWhitelistUpdated(token, status);
}
/// @dev Changing the fee account
/// @param _feeAccount Address of the new fee account
function setFeeAccount(address _feeAccount) external onlyRole(ROLE_SET_FEEACCOUNT) {
feeAccount = _feeAccount;
FeeAccountChanged(feeAccount);
}
/// @dev Set user withdrawal delay (must be less than 2 weeks)
/// @param _delay New delay
function setDelay(uint256 _delay) external onlyRole(ROLE_CHANGE_DELAY) {
require(_delay < 2 weeks);
delay = _delay;
DelayChanged(delay);
}
/// @dev This takes in user's tokens
/// User must first call properly approve() on token contract
/// The token must be whitelisted with updateTokenWhitelist() beforehand
/// @param token Token to fetch
/// @param amount Amount of tokens to fetch, in its smallest denominator
/// @return true if transfer is successful
function depositTokens(ERC20 token, uint256 amount) external returns(bool) {
depositInternal(token, amount);
require(token.transferFrom(msg.sender, this, amount));
return true;
}
/// @dev This takes in user's ethers
/// Ether deposit must be allowed with updateTokenWhitelist(address(0), true)
/// @return true if transfer is successful
function depositEthers() external payable returns(bool) {
depositInternal(address(0), msg.value);
return true;
}
/// @dev By default, backend will provide the withdrawal functionality
/// @param token Address of the token
/// @param user Who is the sender (and signer) of this token transfer
/// @param amount Amount of tokens in its smallest denominator
/// @param fee Optional fee in the smallest denominator of the token
/// @param nonce Nonce to make this signed transfer unique
/// @param v V of the user's key which was used to sign this transfer
/// @param r R of the user's key which was used to sign this transfer
/// @param s S of the user's key which was used to sign this transfer
function withdrawAdmin(ERC20 token, address user, uint256 amount, uint256 fee, uint256 nonce, uint8 v, bytes32 r, bytes32 s) external onlyRole(ROLE_WITHDRAW) {
bytes32 hash = keccak256(this, token, user, amount, fee, nonce);
require(withdrawn[hash] == false);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == user);
withdrawn[hash] = true;
withdrawInternal(token, user, amount, fee);
}
/// @dev Backend can force tokens out of the Exchange contract back to user's wallet
/// @param token Token that backend wants to push back to the user
/// @param user User whose funds we want to push back
/// @param amount Amount of tokens in its smallest denominator
function withdrawForced(ERC20 token, address user, uint256 amount) external onlyRole(ROLE_FORCED) {
Forced(token, user, amount);
withdrawInternal(token, user, amount, 0);
}
/// @dev First part of the last-resort user withdrawal
/// @param token Token address that user wants to withdraw
/// @param amount Amount of tokens in its smallest denominator
/// @return ID number of the transfer to be passed to withdrawUser()
function withdrawRequest(ERC20 token, uint256 amount) external returns(uint256) {
uint256 index = withdrawals.length;
withdrawals.push(Withdrawal(msg.sender, address(token), amount, now, false));
Requested(token, msg.sender, amount, index);
return index;
}
/// @dev User can withdraw their tokens here as the last resort. User must call withdrawRequest() first
/// @param index Unique ID of the withdrawal passed by withdrawRequest()
function withdrawUser(uint256 index) external {
require((withdrawals[index].createdAt.add(delay)) < now);
require(withdrawals[index].executed == false);
require(withdrawals[index].user == msg.sender);
withdrawals[index].executed = true;
withdrawInternal(withdrawals[index].token, withdrawals[index].user, withdrawals[index].amount, 0);
}
/// @dev Token transfer inside the Exchange
/// @param token Address of the token
/// @param from Who is the sender (and signer) of this internal token transfer
/// @param to Who is the receiver of this internal token transfer
/// @param amount Amount of tokens in its smallest denominator
/// @param fee Optional fee in the smallest denominator of the token
/// @param nonce Nonce to make this signed transfer unique
/// @param expires Expiration of this transfer
/// @param v V of the user's key which was used to sign this transfer
/// @param r R of the user's key which was used to sign this transfer
/// @param s S of the user's key which was used to sign this transfer
function transferTokens(ERC20 token, address from, address to, uint256 amount, uint256 fee, uint256 nonce, uint256 expires, uint8 v, bytes32 r, bytes32 s) external onlyRole(ROLE_TRANSFER_TOKENS) {
bytes32 hash = keccak256(this, token, from, to, amount, fee, nonce, expires);
require(expires >= now);
require(transferred[hash] == false);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n32", hash), v, r, s) == from);
balanceOf[address(token)][from] = balanceOf[address(token)][from].sub(amount.add(fee));
balanceOf[address(token)][feeAccount] = balanceOf[address(token)][feeAccount].add(fee);
balanceOf[address(token)][to] = balanceOf[address(token)][to].add(amount);
TransferredTokens(token, from, to, amount, fee, nonce);
}
/// @dev This is used to interact with TokenMarket's Security Token Infrastructure
/// @param token Address of the Investor Interaction Contract
/// @param to Destination where those tokens should be transferred to
/// @param amount Amount of tokens in its smallest denominator
function transferInvestorTokens(InvestorToken token, address to, uint256 amount) external onlyRole(ROLE_TRANSFER_INVESTOR_TOKENS) {
token.transferInvestorTokens(to, amount);
TransferredInvestorTokens(msg.sender, token, to, amount);
}
/// @dev This is used to rescue accidentally transfer()'d tokens
/// @param token Address of the EIP-20 compatible token'
function claimExtra(ERC20 token) external onlyRole(ROLE_CLAIM) {
uint256 totalBalance = token.balanceOf(this);
token.transfer(feeAccount, totalBalance.sub(tokensTotal[token]));
}
/// @dev This is the entry point for trading, and will prepare structs for tradeInternal()
/// @param _left The binary blob where Order struct will be extracted from
/// @param leftV V of the user's key which was used to sign _left
/// @param leftR R of the user's key which was used to sign _left
/// @param leftS S of the user's key which was used to sign _left
/// @param _right The binary blob where Order struct will be extracted from
/// @param rightV V of the user's key which was used to sign _right
/// @param leftR R of the user's key which was used to sign _right
/// @param rightS S of the user's key which was used to sign _right
function trade(bytes _left, uint8 leftV, bytes32 leftR, bytes32 leftS, bytes _right, uint8 rightV, bytes32 rightR, bytes32 rightS) external {
checkRole(msg.sender, ROLE_TRADE); //If we use the onlyRole() modifier, we will get "stack too deep" error
Order memory left;
Order memory right;
left.maker = _left.sliceAddress(0);
left.baseToken = _left.sliceAddress(20);
left.quoteToken = _left.sliceAddress(40);
left.feeToken = _left.sliceAddress(60);
left.amount = uint256(_left.slice32(80));
left.priceNumerator = uint256(_left.slice32(112));
left.priceDenominator = uint256(_left.slice32(144));
left.feeNumerator = uint256(_left.slice32(176));
left.feeDenominator = uint256(_left.slice32(208));
left.expiresAt = uint256(_left.slice32(240));
left.nonce = uint256(_left.slice32(272));
if (_left.slice2(304) == 0) {
left.orderType = OrderType.Sell;
} else {
left.orderType = OrderType.Buy;
}
right.maker = _right.sliceAddress(0);
right.baseToken = _right.sliceAddress(20);
right.quoteToken = _right.sliceAddress(40);
right.feeToken = _right.sliceAddress(60);
right.amount = uint256(_right.slice32(80));
right.priceNumerator = uint256(_right.slice32(112));
right.priceDenominator = uint256(_right.slice32(144));
right.feeNumerator = uint256(_right.slice32(176));
right.feeDenominator = uint256(_right.slice32(208));
right.expiresAt = uint256(_right.slice32(240));
right.nonce = uint256(_right.slice32(272));
if (_right.slice2(304) == 0) {
right.orderType = OrderType.Sell;
} else {
right.orderType = OrderType.Buy;
}
bytes32 leftHash = getOrderHash(left);
bytes32 rightHash = getOrderHash(right);
address leftSigner = ecrecover(keccak256("\x19Ethereum Signed Message:\n32", leftHash), leftV, leftR, leftS);
address rightSigner = ecrecover(keccak256("\x19Ethereum Signed Message:\n32", rightHash), rightV, rightR, rightS);
require(leftSigner == left.maker);
require(rightSigner == right.maker);
tradeInternal(left, leftHash, right, rightHash);
}
/// @dev Trading itself happens here
/// @param left Left side of the order pair
/// @param leftHash getOrderHash() of the left
/// @param right Right side of the order pair
/// @param rightHash getOrderHash() of the right
function tradeInternal(Order left, bytes32 leftHash, Order right, bytes32 rightHash) internal {
uint256 priceNumerator;
uint256 priceDenominator;
uint256 leftAmountRemaining;
uint256 rightAmountRemaining;
uint256 amountBaseFilled;
uint256 amountQuoteFilled;
uint256 leftFeePaid;
uint256 rightFeePaid;
require(left.expiresAt > now);
require(right.expiresAt > now);
require(left.baseToken == right.baseToken);
require(left.quoteToken == right.quoteToken);
require(left.baseToken != left.quoteToken);
require((left.orderType == OrderType.Sell && right.orderType == OrderType.Buy) || (left.orderType == OrderType.Buy && right.orderType == OrderType.Sell));
require(left.amount > 0);
require(left.priceNumerator > 0);
require(left.priceDenominator > 0);
require(right.amount > 0);
require(right.priceNumerator > 0);
require(right.priceDenominator > 0);
require(left.feeDenominator > 0);
require(right.feeDenominator > 0);
require(left.amount % left.priceDenominator == 0);
require(left.amount % right.priceDenominator == 0);
require(right.amount % left.priceDenominator == 0);
require(right.amount % right.priceDenominator == 0);
if (left.orderType == OrderType.Buy) {
require((left.priceNumerator.mul(right.priceDenominator)) >= (right.priceNumerator.mul(left.priceDenominator)));
} else {
require((left.priceNumerator.mul(right.priceDenominator)) <= (right.priceNumerator.mul(left.priceDenominator)));
}
priceNumerator = left.priceNumerator;
priceDenominator = left.priceDenominator;
leftAmountRemaining = left.amount.sub(orderFilled[leftHash]);
rightAmountRemaining = right.amount.sub(orderFilled[rightHash]);
require(leftAmountRemaining > 0);
require(rightAmountRemaining > 0);
if (leftAmountRemaining < rightAmountRemaining) {
amountBaseFilled = leftAmountRemaining;
} else {
amountBaseFilled = rightAmountRemaining;
}
amountQuoteFilled = amountBaseFilled.mul(priceNumerator).div(priceDenominator);
leftFeePaid = calculateFee(amountQuoteFilled, left.feeNumerator, left.feeDenominator);
rightFeePaid = calculateFee(amountQuoteFilled, right.feeNumerator, right.feeDenominator);
if (left.orderType == OrderType.Buy) {
checkBalances(left.maker, left.baseToken, left.quoteToken, left.feeToken, amountBaseFilled, amountQuoteFilled, leftFeePaid);
checkBalances(right.maker, right.quoteToken, right.baseToken, right.feeToken, amountQuoteFilled, amountBaseFilled, rightFeePaid);
balanceOf[left.baseToken][left.maker] = balanceOf[left.baseToken][left.maker].add(amountBaseFilled);
balanceOf[left.quoteToken][left.maker] = balanceOf[left.quoteToken][left.maker].sub(amountQuoteFilled);
balanceOf[right.baseToken][right.maker] = balanceOf[right.baseToken][right.maker].sub(amountBaseFilled);
balanceOf[right.quoteToken][right.maker] = balanceOf[right.quoteToken][right.maker].add(amountQuoteFilled);
} else {
checkBalances(left.maker, left.quoteToken, left.baseToken, left.feeToken, amountQuoteFilled, amountBaseFilled, leftFeePaid);
checkBalances(right.maker, right.baseToken, right.quoteToken, right.feeToken, amountBaseFilled, amountQuoteFilled, rightFeePaid);
balanceOf[left.baseToken][left.maker] = balanceOf[left.baseToken][left.maker].sub(amountBaseFilled);
balanceOf[left.quoteToken][left.maker] = balanceOf[left.quoteToken][left.maker].add(amountQuoteFilled);
balanceOf[right.baseToken][right.maker] = balanceOf[right.baseToken][right.maker].add(amountBaseFilled);
balanceOf[right.quoteToken][right.maker] = balanceOf[right.quoteToken][right.maker].sub(amountQuoteFilled);
}
if (leftFeePaid > 0) {
balanceOf[left.feeToken][left.maker] = balanceOf[left.feeToken][left.maker].sub(leftFeePaid);
balanceOf[left.feeToken][feeAccount] = balanceOf[left.feeToken][feeAccount].add(leftFeePaid);
}
if (rightFeePaid > 0) {
balanceOf[right.feeToken][right.maker] = balanceOf[right.feeToken][right.maker].sub(rightFeePaid);
balanceOf[right.feeToken][feeAccount] = balanceOf[right.feeToken][feeAccount].add(rightFeePaid);
}
orderFilled[leftHash] = orderFilled[leftHash].add(amountBaseFilled);
orderFilled[rightHash] = orderFilled[rightHash].add(amountBaseFilled);
emitOrderExecutedEvent(left, leftHash, amountBaseFilled, amountQuoteFilled, leftFeePaid);
emitOrderExecutedEvent(right, rightHash, amountBaseFilled, amountQuoteFilled, rightFeePaid);
}
/// @dev Calculate the fee for an order
/// @param amountFilled How much of the order has been filled
/// @param feeNumerator Will multiply amountFilled with this
/// @param feeDenominator Will divide amountFilled * feeNumerator with this
/// @return Will return the fee
function calculateFee(uint256 amountFilled, uint256 feeNumerator, uint256 feeDenominator) public returns(uint256) {
return (amountFilled.mul(feeNumerator).div(feeDenominator));
}
/// @dev This is the internal method shared by all withdrawal functions
/// @param token Address of the token withdrawn
/// @param user Address of the user making the withdrawal
/// @param amount Amount of token in its smallest denominator
/// @param fee Fee paid in this particular token
function withdrawInternal(address token, address user, uint256 amount, uint256 fee) internal {
require(amount > 0);
require(balanceOf[token][user] >= amount.add(fee));
balanceOf[token][user] = balanceOf[token][user].sub(amount.add(fee));
balanceOf[token][feeAccount] = balanceOf[token][feeAccount].add(fee);
tokensTotal[token] = tokensTotal[token].sub(amount);
if (token == address(0)) {
user.transfer(amount);
} else {
require(ERC20(token).transfer(user, amount));
}
Withdrawn(token, user, amount, balanceOf[token][user]);
}
/// @dev This is the internal method shared by all deposit functions
/// The token must have been whitelisted with updateTokenWhitelist()
/// @param token Address of the token deposited
/// @param amount Amount of token in its smallest denominator
function depositInternal(address token, uint256 amount) internal {
require(tokenWhitelist[address(token)]);
balanceOf[token][msg.sender] = balanceOf[token][msg.sender].add(amount);
tokensTotal[token] = tokensTotal[token].add(amount);
Deposited(token, msg.sender, amount, balanceOf[token][msg.sender]);
}
/// @dev This is for emitting OrderExecuted(), one per order
/// @param order The Order struct which is relevant for this event
/// @param orderHash Hash received from getOrderHash()
/// @param amountBaseFilled Amount of order.baseToken filled
/// @param amountQuoteFilled Amount of order.quoteToken filled
/// @param feePaid Amount in order.feeToken paid
function emitOrderExecutedEvent(
Order order,
bytes32 orderHash,
uint256 amountBaseFilled,
uint256 amountQuoteFilled,
uint256 feePaid
) private {
uint256 baseTokenBalance = balanceOf[order.baseToken][order.maker];
uint256 quoteTokenBalance = balanceOf[order.quoteToken][order.maker];
uint256 feeTokenBalance = balanceOf[order.feeToken][order.maker];
OrderExecuted(
orderHash,
order.maker,
order.baseToken,
order.quoteToken,
order.feeToken,
amountBaseFilled,
amountQuoteFilled,
feePaid,
baseTokenBalance,
quoteTokenBalance,
feeTokenBalance
);
}
/// @dev Order struct will be hashed here with keccak256
/// @param order The Order struct which will be hashed
/// @return The keccak256 hash in bytes32
function getOrderHash(Order order) private returns(bytes32) {
return keccak256(
this,
order.orderType,
order.maker,
order.baseToken,
order.quoteToken,
order.feeToken,
order.amount,
order.priceNumerator,
order.priceDenominator,
order.feeNumerator,
order.feeDenominator,
order.expiresAt,
order.nonce
);
}
/// @dev This is used to check balances for a user upon trade, all in once
/// @param addr Address of the user
/// @param boughtToken The address of the token which is being bought
/// @param soldToken The address of the token which is being sold
/// @param feeToken The token which is used for fees
/// @param boughtAmount Amount in boughtToken
/// @param soldAmount Amount in soldTokens
/// @param feeAmount Amount in feeTokens
function checkBalances(address addr, address boughtToken, address soldToken, address feeToken, uint256 boughtAmount, uint256 soldAmount, uint256 feeAmount) private {
if (feeToken == soldToken) {
require (balanceOf[soldToken][addr] >= (soldAmount.add(feeAmount)));
} else {
if (feeToken == boughtToken) {
require (balanceOf[feeToken][addr].add(boughtAmount) >= feeAmount);
} else {
require (balanceOf[feeToken][addr] >= feeAmount);
}
require (balanceOf[soldToken][addr] >= soldAmount);
}
}
}
|
Order struct will be hashed here with keccak256 order The Order struct which will be hashed return The keccak256 hash in bytes32
|
function getOrderHash(Order order) private returns(bytes32) {
return keccak256(
this,
order.orderType,
order.maker,
order.baseToken,
order.quoteToken,
order.feeToken,
order.amount,
order.priceNumerator,
order.priceDenominator,
order.feeNumerator,
order.feeDenominator,
order.expiresAt,
order.nonce
);
}
| 14,016,131 |
/**
* Copyright BOOSTRY Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
import "./Ownable.sol";
import "../interfaces/IbetStandardTokenInterface.sol";
import "./OTCExchangeStorageModel.sol";
import "./OTCExchangeStorage.sol";
import "./PaymentGateway.sol";
import "./PersonalInfo.sol";
import "../interfaces/RegulatorService.sol";
import "../interfaces/ContractReceiver.sol";
/// @title ibet OTC DEX
contract IbetOTCExchange is Ownable, ContractReceiver, OTCExchangeStorageModel {
using SafeMath for uint256;
// 約定明細の有効期限
// 現在の設定値は14日で設定している(長期の連休を考慮)
uint256 lockingPeriod = 1209600;
// ---------------------------------------------------------------
// Event
// ---------------------------------------------------------------
// Event:注文
event NewOrder(
address indexed tokenAddress,
uint256 orderId,
address indexed ownerAddress,
address indexed counterpartAddress,
uint256 price,
uint256 amount,
address agentAddress
);
// Event: 注文取消
event CancelOrder(
address indexed tokenAddress,
uint256 orderId,
address indexed ownerAddress,
address indexed counterpartAddress,
uint256 price,
uint256 amount,
address agentAddress
);
// Event: 約定
event Agree(
address indexed tokenAddress,
uint256 orderId,
uint256 agreementId,
address indexed buyAddress,
address indexed sellAddress,
uint256 price,
uint256 amount,
address agentAddress
);
// Event: 決済OK
event SettlementOK(
address indexed tokenAddress,
uint256 orderId,
uint256 agreementId,
address indexed buyAddress,
address indexed sellAddress,
uint256 price,
uint256 amount,
address agentAddress
);
// Event: 決済NG
event SettlementNG(
address indexed tokenAddress,
uint256 orderId,
uint256 agreementId,
address indexed buyAddress,
address indexed sellAddress,
uint256 price,
uint256 amount,
address agentAddress
);
// Event: 全引き出し
event Withdrawal(
address indexed tokenAddress,
address indexed accountAddress
);
// ---------------------------------------------------------------
// Constructor
// ---------------------------------------------------------------
address public personalInfoAddress;
address public paymentGatewayAddress;
address public storageAddress;
address public regulatorServiceAddress;
// [CONSTRUCTOR]
/// @param _paymentGatewayAddress PaymentGatewayコントラクトアドレス
/// @param _personalInfoAddress PersonalInfoコントラクトアドレス
/// @param _storageAddress OTCExchangeStorageコントラクトアドレス
/// @param _regulatorServiceAddress RegulatorServiceコントラクトアドレス
constructor(
address _paymentGatewayAddress,
address _personalInfoAddress,
address _storageAddress,
address _regulatorServiceAddress
)
{
paymentGatewayAddress = _paymentGatewayAddress;
personalInfoAddress = _personalInfoAddress;
storageAddress = _storageAddress;
regulatorServiceAddress = _regulatorServiceAddress;
}
// -------------------------------------------------------------------
// Function: getter/setter
// -------------------------------------------------------------------
/// @notice 注文情報取得
/// @param _orderId 注文ID
/// @return _owner 注文実行者(売り手)アドレス
/// @return _counterpart 取引相手(買い手)アドレス
/// @return _token トークンアドレス
/// @return _amount 注文数量
/// @return _price 注文単価
/// @return _agent 決済業者のアドレス
/// @return _canceled キャンセル済み状態
function getOrder(uint256 _orderId)
public
view
returns (
address _owner,
address _counterpart,
address _token,
uint256 _amount,
uint256 _price,
address _agent,
bool _canceled
)
{
OTCExchangeStorageModel.OTCOrder memory _order = OTCExchangeStorage(storageAddress).getOrder(_orderId);
return (
_order.owner,
_order.counterpart,
_order.token,
_order.amount,
_order.price,
_order.agent,
_order.canceled
);
}
/// @notice 注文情報更新
/// @param _orderId 注文ID
/// @param _owner 注文実行者(売り手)アドレス
/// @param _counterpart 取引相手(買い手)アドレス
/// @param _token トークンアドレス
/// @param _amount 注文数量
/// @param _price 注文単価
/// @param _agent 決済業者のアドレス
/// @param _canceled キャンセル済み状態
/// @return 処理結果
function setOrder(
uint256 _orderId,
address _owner,
address _counterpart,
address _token,
uint256 _amount,
uint256 _price,
address _agent,
bool _canceled
)
private
returns (bool)
{
OTCExchangeStorageModel.OTCOrder memory _order = OTCExchangeStorageModel.mappingOTCOrder(
_owner,
_counterpart,
_token,
_amount,
_price,
_agent,
_canceled
);
OTCExchangeStorage(storageAddress).setOrder(
_orderId,
_order
);
return true;
}
/// @notice 約定情報取得
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return _counterpart 約定相手(売り手)アドレス
/// @return _amount 約定数量
/// @return _price 約定単価
/// @return _canceled キャンセル済み状態
/// @return _paid 支払済状態
/// @return _expiry 有効期限
function getAgreement(uint256 _orderId, uint256 _agreementId)
public
view
returns (
address _counterpart,
uint256 _amount,
uint256 _price,
bool _canceled,
bool _paid,
uint256 _expiry
)
{
OTCExchangeStorageModel.OTCAgreement memory _agreement = OTCExchangeStorage(storageAddress).getAgreement(_orderId, _agreementId);
return (
_agreement.counterpart,
_agreement.amount,
_agreement.price,
_agreement.canceled,
_agreement.paid,
_agreement.expiry
);
}
/// @notice 約定情報更新
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @param _counterpart 約定相手(売り手)アドレス
/// @param _amount 約定数量
/// @param _price 約定単価
/// @param _canceled キャンセル済み状態
/// @param _paid 支払済状態
/// @param _expiry 有効期限
/// @return 処理結果
function setAgreement(
uint256 _orderId,
uint256 _agreementId,
address _counterpart,
uint256 _amount,
uint256 _price,
bool _canceled,
bool _paid,
uint256 _expiry
)
private
returns (bool)
{
OTCExchangeStorageModel.OTCAgreement memory _agreement = OTCExchangeStorageModel.mappingOTCAgreement(
_counterpart,
_amount,
_price,
_canceled,
_paid,
_expiry
);
OTCExchangeStorage(storageAddress).setAgreement(
_orderId,
_agreementId,
_agreement
);
return true;
}
/// @notice 直近注文ID取得
/// @return 直近注文ID
function latestOrderId()
public
view
returns (uint256)
{
return OTCExchangeStorage(storageAddress).getLatestOrderId();
}
/// @notice 直近注文ID更新
/// @param _value 更新後の直近注文ID
/// @return 処理結果
function setLatestOrderId(uint256 _value)
private
returns (bool)
{
OTCExchangeStorage(storageAddress).setLatestOrderId(_value);
return true;
}
/// @notice 直近約定ID取得
/// @param _orderId 注文ID
/// @return 直近約定ID
function latestAgreementId(uint256 _orderId)
public
view
returns (uint256)
{
return OTCExchangeStorage(storageAddress).getLatestAgreementId(_orderId);
}
/// @notice 直近約定ID更新
/// @param _orderId 注文ID
/// @param _value 更新後の直近約定ID
/// @return 処理結果
function setLatestAgreementId(uint256 _orderId, uint256 _value)
private
returns (bool)
{
OTCExchangeStorage(storageAddress).setLatestAgreementId(_orderId, _value);
return true;
}
/// @notice 残高参照
/// @param _account アカウントアドレス
/// @param _token トークンアドレス
/// @return 残高数量
function balanceOf(address _account, address _token)
public
view
returns (uint256)
{
return OTCExchangeStorage(storageAddress).getBalance(
_account,
_token
);
}
/// @notice 残高数量更新
/// @param _account アカウントアドレス
/// @param _token トークンアドレス
/// @param _value 更新後の残高数量
/// @return 処理結果
function setBalance(address _account, address _token, uint256 _value)
private
returns (bool)
{
return OTCExchangeStorage(storageAddress).setBalance(
_account,
_token,
_value
);
}
/// @notice 拘束数量参照
/// @param _account アカウントアドレス
/// @param _token トークンアドレス
/// @return 拘束数量
function commitmentOf(address _account, address _token)
public
view
returns (uint256)
{
return OTCExchangeStorage(storageAddress).getCommitment(
_account,
_token
);
}
/// @notice 拘束数量更新
/// @param _account アカウントアドレス
/// @param _token トークンアドレス
/// @param _value 更新後の拘束数量
/// @return 処理結果
function setCommitment(address _account, address _token, uint256 _value)
private
returns (bool)
{
OTCExchangeStorage(storageAddress).setCommitment(
_account,
_token,
_value
);
return true;
}
// ---------------------------------------------------------------
// Function: Logic
// ---------------------------------------------------------------
/// @notice Make注文
/// @param _counterpart 取引相手(買い手)アドレス
/// @param _token トークンアドレス
/// @param _amount 注文数量
/// @param _price 注文単価
/// @param _agent 収納代行業者のアドレス
/// @return 処理結果
function createOrder(
address _counterpart,
address _token,
uint256 _amount,
uint256 _price,
address _agent
)
public
returns (bool)
{
// <CHK>
// 取引参加者チェック
if (regulatorServiceAddress != address(0)) {
require(RegulatorService(regulatorServiceAddress).check(msg.sender) == 0 || RegulatorService(regulatorServiceAddress).check(_counterpart) == 0);
}
// <CHK>
// 1) 注文数量が0の場合
// 2) 残高数量が発注数量に満たない場合
// 3) 名簿用個人情報が登録されていない場合
// 4) 取扱ステータスがFalseの場合
// 5) 有効な収納代行業者(Agent)を指定していない場合
// -> 更新処理: 全ての残高を投資家のアカウントに戻し、falseを返す
if (
_amount == 0 ||
balanceOf(msg.sender, _token) < _amount ||
PersonalInfo(personalInfoAddress).isRegistered(msg.sender, Ownable(_token).owner()) == false ||
IbetStandardTokenInterface(_token).status() == false ||
validateAgent(_agent) == false
) {
IbetStandardTokenInterface(_token).transfer(
msg.sender,
balanceOf(msg.sender, _token)
);
setBalance(msg.sender, _token, 0);
return false;
}
// 更新処理: 注文IDをカウントアップ -> 注文情報を挿入
uint256 orderId = latestOrderId() + 1;
setLatestOrderId(orderId);
setOrder(
orderId,
msg.sender,
_counterpart,
_token,
_amount,
_price,
_agent,
false
);
// 預かりを拘束
setBalance(
msg.sender,
_token,
balanceOf(msg.sender, _token).sub(_amount)
);
setCommitment(
msg.sender,
_token,
commitmentOf(msg.sender, _token).add(_amount)
);
// イベント登録: 新規注文
emit NewOrder(
_token,
orderId,
msg.sender,
_counterpart,
_price,
_amount,
_agent
);
return true;
}
/// @notice 注文キャンセル
/// @param _orderId 注文ID
/// @return 処理結果
function cancelOrder(uint256 _orderId)
public
returns (bool)
{
// <CHK>
// 指定した注文番号が、直近の注文ID以上の場合
// -> REVERT
require(_orderId <= latestOrderId());
OTCExchangeStorageModel.OTCOrder memory order = OTCExchangeStorage(storageAddress).getOrder(_orderId);
// <CHK>
// 1) 元注文の残注文数量が0の場合
// 2) 注文がキャンセル済みの場合
// 3) 元注文の発注者と、注文キャンセルの実施者が異なる場合
// 4) 取扱ステータスがFalseの場合
// -> REVERT
if (
order.amount == 0 ||
order.canceled == true ||
order.owner != msg.sender ||
IbetStandardTokenInterface(order.token).status() == false
) {
revert();
}
// 注文で拘束している預かりを解放 => 残高を投資家のアカウントに戻す
setCommitment(
msg.sender,
order.token,
commitmentOf(msg.sender, order.token).sub(order.amount)
);
IbetStandardTokenInterface(order.token).transfer(
msg.sender,
order.amount
);
// 更新処理: キャンセル済みフラグをキャンセル済み(True)に更新
OTCExchangeStorage(storageAddress).setOrderCanceled(_orderId, true);
// イベント登録: 注文キャンセル
emit CancelOrder(
order.token,
_orderId,
msg.sender,
order.counterpart,
order.price,
order.amount,
order.agent
);
return true;
}
/// @notice Take注文
/// @dev 約定数量 = 注文数量
/// @param _orderId 注文ID
/// @return 処理結果
function executeOrder(uint256 _orderId)
public
returns (bool)
{
// <CHK>
// 指定した注文IDが直近の注文IDを超えている場合
require(_orderId <= latestOrderId());
OTCExchangeStorageModel.OTCOrder memory order = OTCExchangeStorage(storageAddress).getOrder(_orderId);
// <CHK>
// 取引参加者チェック
if (regulatorServiceAddress != address(0)) {
require(
RegulatorService(regulatorServiceAddress).check(msg.sender) == 0 ||
RegulatorService(regulatorServiceAddress).check(order.owner) == 0
);
}
// <CHK>
// 取引関係者限定
require(
order.owner == msg.sender ||
order.counterpart == msg.sender ||
order.agent == msg.sender
);
// <CHK>
// 1) 元注文の発注者と同一のアドレスからの発注の場合
// 2) 元注文がキャンセル済の場合
// 3) 名簿用個人情報が登録されていない場合
// 4) 買注文者がコントラクトアドレスの場合
// 5) 取扱ステータスがFalseの場合
// 6) 元注文の残注文数量が0の場合
// -> REVERT
if (
msg.sender == order.owner ||
order.canceled == true ||
PersonalInfo(personalInfoAddress).isRegistered(msg.sender,Ownable(order.token).owner()) == false ||
isContract(msg.sender) == true ||
IbetStandardTokenInterface(order.token).status() == false ||
order.amount == 0
) {
revert();
}
// 更新処理: 約定IDをカウントアップ => 約定情報を挿入する
uint256 agreementId = latestAgreementId(_orderId) + 1;
setLatestAgreementId(_orderId, agreementId);
uint256 expiry = block.timestamp + lockingPeriod;
setAgreement(
_orderId,
agreementId,
msg.sender,
order.amount,
order.price,
false,
false,
expiry
);
// 更新処理: 元注文の数量を0にする
OTCExchangeStorage(storageAddress).setOrderAmount(_orderId, 0);
// イベント登録: 約定
emit Agree(
order.token,
_orderId,
agreementId,
msg.sender,
order.owner,
order.price,
order.amount,
order.agent
);
return true;
}
/// @notice 決済承認
/// @dev 注文時に指定された決済業者のみ実行が可能
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return 処理結果
function confirmAgreement(uint256 _orderId, uint256 _agreementId)
public
returns (bool)
{
// <CHK>
// 1) 指定した注文番号が、直近の注文ID以上の場合
// 2) 指定した約定IDが、直近の約定ID以上の場合
// -> REVERT
require(_orderId <= latestOrderId());
require(_agreementId <= latestAgreementId(_orderId));
OTCExchangeStorageModel.OTCOrder memory order = OTCExchangeStorage(storageAddress).getOrder(_orderId);
OTCExchangeStorageModel.OTCAgreement memory agreement = OTCExchangeStorage(storageAddress).getAgreement(_orderId, _agreementId);
// <CHK>
// 1) すでに決済承認済み(支払い済み)の場合
// 2) すでに決済非承認済み(キャンセル済み)の場合
// 3) 元注文で指定した決済業者ではない場合
// 4) 取扱ステータスがFalseの場合
// -> REVERT
if (
agreement.paid ||
agreement.canceled ||
msg.sender != order.agent ||
IbetStandardTokenInterface(order.token).status() == false
) {
revert();
}
// 更新処理: 支払い済みフラグを支払い済み(True)に更新する
OTCExchangeStorage(storageAddress).setAgreementPaid(_orderId, _agreementId, true);
// 更新処理: 注文者(売り手)から突合相手(買い手)へと資産移転を行う
setCommitment(
order.owner,
order.token,
commitmentOf(order.owner, order.token).sub(agreement.amount)
);
IbetStandardTokenInterface(order.token).transfer(
agreement.counterpart,
agreement.amount
);
// イベント登録: 決済OK
emit SettlementOK(
order.token,
_orderId,
_agreementId,
agreement.counterpart,
order.owner,
order.price,
agreement.amount,
order.agent
);
return true;
}
/// @notice 決済非承認
/// @dev 注文時に指定された決済業者から実行が可能、有効期限後はMake注文者も実行が可能
/// @param _orderId 注文ID
/// @param _agreementId 約定ID
/// @return 処理結果
function cancelAgreement(uint256 _orderId, uint256 _agreementId)
public
returns (bool)
{
// <CHK>
// 1) 指定した注文番号が、直近の注文ID以上の場合
// 2) 指定した約定IDが、直近の約定ID以上の場合
// -> REVERT
require(_orderId <= latestOrderId());
require(_agreementId <= latestAgreementId(_orderId));
OTCExchangeStorageModel.OTCOrder memory order = OTCExchangeStorage(storageAddress).getOrder(_orderId);
OTCExchangeStorageModel.OTCAgreement memory agreement = OTCExchangeStorage(storageAddress).getAgreement(_orderId, _agreementId);
if (agreement.expiry <= block.timestamp) {
// 約定明細の有効期限を超過している場合
// <CHK>
// 1) すでに決済承認済み(支払い済み)の場合
// 2) すでに決済非承認済み(キャンセル済み)の場合
// 3) msg.senderが、 決済代行(agent)、発注者(owner)、約定相手(counterpart)以外の場合
// 4) 取扱ステータスがFalseの場合
// -> REVERT
if (
agreement.paid ||
agreement.canceled ||
(msg.sender != order.agent &&
msg.sender != order.owner &&
msg.sender != agreement.counterpart) ||
IbetStandardTokenInterface(order.token).status() == false
) {
revert();
}
} else {
// 約定明細の有効期限を超過していない場合
// <CHK>
// 1) すでに支払い済みの場合
// 2) すでに決済非承認済み(キャンセル済み)の場合
// 3) msg.senderが、決済代行(agent)以外の場合
// -> REVERT
if (
agreement.paid ||
agreement.canceled ||
msg.sender != order.agent ||
IbetStandardTokenInterface(order.token).status() == false
) {
revert();
}
}
// 更新処理: キャンセル済みフラグをキャンセル(True)に更新する
OTCExchangeStorage(storageAddress).setAgreementCanceled( _orderId, _agreementId, true);
// 更新処理:元注文の数量を戻す
OTCExchangeStorage(storageAddress).setOrderAmount(_orderId, order.amount.add(agreement.amount));
// イベント登録: 決済NG
emit SettlementNG(
order.token,
_orderId,
_agreementId,
agreement.counterpart,
order.owner,
order.price,
agreement.amount,
order.agent
);
return true;
}
/// @notice 全ての残高を引き出しする
/// @dev 未売却の預かりに対してのみ引き出しをおこなう。約定済、注文中の預かり(commitments)の引き出しはおこなわない。
/// @param _token トークンアドレス
/// @return 処理結果
function withdrawAll(address _token)
public
returns (bool)
{
uint256 balance = balanceOf(msg.sender, _token);
// <CHK>
// 1) 残高がゼロの場合、REVERT
// 2) 取扱ステータスがFalseの場合
if (balance == 0 || IbetStandardTokenInterface(_token).status() == false) {
revert();
}
// 更新処理: トークン引き出し(送信)
IbetStandardTokenInterface(_token).transfer(msg.sender, balance);
setBalance(msg.sender, _token, 0);
// イベント登録
emit Withdrawal(_token, msg.sender);
return true;
}
/// @notice Deposit Handler:デポジット処理
/// @param _from アカウントアドレス:残高を保有するアドレス
/// @param _value デポジット数量
function tokenFallback(address _from, uint256 _value, bytes memory /*_data*/)
public
override
{
setBalance(
_from,
msg.sender,
balanceOf(_from, msg.sender).add(_value)
);
}
/// @notice アドレスがコントラクトアドレスであるかを判定
/// @param _addr アドレス
/// @return is_contract 判定結果
function isContract(address _addr)
private
view
returns (bool is_contract)
{
uint256 length;
assembly {
length := extcodesize(_addr)
}
return (length > 0);
}
/// @notice Agentアドレスが有効なものであることをチェックする
/// @param _addr アドレス
/// @return 有効状態
function validateAgent(address _addr)
private
view
returns (bool)
{
return PaymentGateway(paymentGatewayAddress).getAgent(_addr);
}
}
|
注文情報取得 _orderId 注文ID return _owner 注文実行者(売り手)アドレス return _counterpart 取引相手(買い手)アドレス return _token トークンアドレス return _amount 注文数量 return _price 注文単価 return _agent 決済業者のアドレス return _canceled キャンセル済み状態
|
function getOrder(uint256 _orderId)
public
view
returns (
address _owner,
address _counterpart,
address _token,
uint256 _amount,
uint256 _price,
address _agent,
bool _canceled
)
{
OTCExchangeStorageModel.OTCOrder memory _order = OTCExchangeStorage(storageAddress).getOrder(_orderId);
return (
_order.owner,
_order.counterpart,
_order.token,
_order.amount,
_order.price,
_order.agent,
_order.canceled
);
}
| 12,978,719 |
./full_match/1287/0x8162876a0bD2bE9d48a2023d20d5955d51eC055D/sources/contracts/PartsStore.sol
|
Returns the doodad at the given index id the index of the doodad to retrieve return the doodad at the given index/
|
function getDoodad(uint8 id) external view returns (ImagePart memory) {
return doodads[id];
}
| 7,097,268 |
pragma solidity ^0.4.18;
contract owned {
/* Owner definition. */
address public owner; // Owner address.
function owned() internal {
owner = msg.sender ;
}
modifier onlyOwner {
require(msg.sender == owner); _;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract token {
/* Base token definition. */
string public name; // Name for the token.
string public symbol; // Symbol for the token.
uint8 public decimals; // Number of decimals of the token.
uint256 public totalSupply; // Total of tokens created.
// Array containing the balance foreach address.
mapping (address => uint256) public balanceOf;
// Array containing foreach address, an array containing each approved address and the amount of tokens it can spend.
mapping (address => mapping (address => uint256)) public allowance;
/* This generates a public event on the blockchain that will notify about a transfer done. */
event Transfer(address indexed from, address indexed to, uint256 value);
/* Initializes the contract */
function token(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) internal {
balanceOf[msg.sender] = initialSupply; // Gives the creator all initial tokens.
totalSupply = initialSupply; // Update total supply.
name = tokenName; // Set the name for display purposes.
symbol = tokenSymbol; // Set the symbol for display purposes.
decimals = decimalUnits; // Amount of decimals for display purposes.
}
/* Internal transfer, only can be called by this contract. */
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0); // Prevent transfer to 0x0 address.
require(balanceOf[_from] > _value); // Check if the sender has enough.
require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows.
balanceOf[_from] -= _value; // Subtract from the sender.
balanceOf[_to] += _value; // Add the same to the recipient.
Transfer(_from, _to, _value); // Notifies the blockchain about the transfer.
}
/// @notice Send `_value` tokens to `_to` from your account.
/// @param _to The address of the recipient.
/// @param _value The amount to send.
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/// @notice Send `_value` tokens to `_to` in behalf of `_from`.
/// @param _from The address of the sender.
/// @param _to The address of the recipient.
/// @param _value The amount to send.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance.
allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent.
_transfer(_from, _to, _value); // Makes the transfer.
return true;
}
/// @notice Allows `_spender` to spend a maximum of `_value` tokens in your behalf.
/// @param _spender The address authorized to spend.
/// @param _value The max amount they can spend.
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value; // Adds a new register to allowance, permiting _spender to use _value of your tokens.
return true;
}
}
contract PMHToken is owned, token {
/* Specific token definition for -HormitechToken-. */
uint256 public sellPrice = 5000000000000000; // Price applied if someone wants to sell a token.
uint256 public buyPrice = 10000000000000000; // Price applied if someone wants to buy a token.
bool public closeBuy = false; // If true, nobody will be able to buy.
bool public closeSell = false; // If true, nobody will be able to sell.
uint256 public tokensAvailable = balanceOf[this]; // Number of tokens available for sell.
uint256 public solvency = this.balance; // Amount of Ether available to pay sales.
uint256 public profit = 0; // Shows the actual profit for the company.
address public comisionGetter = 0x70B593f89DaCF6e3BD3e5bD867113FEF0B2ee7aD ; // The address that gets the comisions paid.
// added MAR 2018
mapping (address => string ) public emails ; // Array containing the e-mail addresses of the token holders
mapping (uint => uint) public dividends ; // for each period in the index, how many weis set for dividends distribution
mapping (address => uint[]) public paidDividends ; // for each address, if the period dividend was paid or not and the amount
// added MAR 2018
mapping (address => bool) public frozenAccount; // Array containing foreach address if it's frozen or not.
/* This generates a public event on the blockchain that will notify about an address being freezed. */
event FrozenFunds(address target, bool frozen);
/* This generates a public event on the blockchain that will notify about an addition of Ether to the contract. */
event LogDeposit(address sender, uint amount);
/* This generates a public event on the blockchain that will notify about a Withdrawal of Ether from the contract. */
event LogWithdrawal(address receiver, uint amount);
/* Initializes the contract */
function PMHToken(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) public
token (initialSupply, tokenName, decimalUnits, tokenSymbol) {}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0); // Prevent transfer to 0x0 address.
require(balanceOf[_from] >= _value); // Check if the sender has enough.
require(balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows.
require(!frozenAccount[_from]); // Check if sender is frozen.
require(!frozenAccount[_to]); // Check if recipient is frozen.
balanceOf[_from] -= _value; // Subtracts _value tokens from the sender.
balanceOf[_to] += _value; // Adds the same amount to the recipient.
_updateTokensAvailable(balanceOf[this]); // Update the balance of tokens available if necessary.
Transfer(_from, _to, _value); // Notifies the blockchain about the transfer.
}
function refillTokens(uint256 _value) public onlyOwner{
// Owner sends tokens to the contract.
_transfer(msg.sender, this, _value);
}
/* Overrides basic transfer function due to comision value */
function transfer(address _to, uint256 _value) public {
// This function requires a comision value of 0.4% of the market value.
uint market_value = _value * sellPrice;
uint comision = market_value * 4 / 1000;
// The token smart-contract pays comision, else the transfer is not possible.
require(this.balance >= comision);
comisionGetter.transfer(comision); // Transfers comision to the comisionGetter.
_transfer(msg.sender, _to, _value);
}
/* Overrides basic transferFrom function due to comision value */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance.
// This function requires a comision value of 0.4% of the market value.
uint market_value = _value * sellPrice;
uint comision = market_value * 4 / 1000;
// The token smart-contract pays comision, else the transfer is not possible.
require(this.balance >= comision);
comisionGetter.transfer(comision); // Transfers comision to the comisionGetter.
allowance[_from][msg.sender] -= _value; // Updates the allowance array, substracting the amount sent.
_transfer(_from, _to, _value); // Makes the transfer.
return true;
}
/* Internal, updates the balance of tokens available. */
function _updateTokensAvailable(uint256 _tokensAvailable) internal { tokensAvailable = _tokensAvailable; }
/* Internal, updates the balance of Ether available in order to cover potential sales. */
function _updateSolvency(uint256 _solvency) internal { solvency = _solvency; }
/* Internal, updates the profit value */
function _updateProfit(uint256 _increment, bool add) internal{
if (add){
// Increase the profit value
profit = profit + _increment;
}else{
// Decrease the profit value
if(_increment > profit){ profit = 0; }
else{ profit = profit - _increment; }
}
}
/// @notice Create `mintedAmount` tokens and send it to `target`.
/// @param target Address to receive the tokens.
/// @param mintedAmount The amount of tokens target will receive.
function mintToken(address target, uint256 mintedAmount) onlyOwner public {
balanceOf[target] += mintedAmount; // Updates target's balance.
totalSupply += mintedAmount; // Updates totalSupply.
_updateTokensAvailable(balanceOf[this]); // Update the balance of tokens available if necessary.
Transfer(0, this, mintedAmount); // Notifies the blockchain about the tokens created.
Transfer(this, target, mintedAmount); // Notifies the blockchain about the transfer to target.
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens.
/// @param target Address to be frozen.
/// @param freeze Either to freeze target or not.
function freezeAccount(address target, bool freeze) onlyOwner public {
frozenAccount[target] = freeze; // Sets the target status. True if it's frozen, False if it's not.
FrozenFunds(target, freeze); // Notifies the blockchain about the change of state.
}
/// @notice Allow addresses to pay `newBuyPrice`ETH when buying and receive `newSellPrice`ETH when selling, foreach token bought/sold.
/// @param newSellPrice Price applied when an address sells its tokens, amount in WEI (1ETH = 10¹⁸WEI).
/// @param newBuyPrice Price applied when an address buys tokens, amount in WEI (1ETH = 10¹⁸WEI).
function setPrices(uint256 newSellPrice, uint256 newBuyPrice) onlyOwner public {
sellPrice = newSellPrice; // Updates the buying price.
buyPrice = newBuyPrice; // Updates the selling price.
}
/// @notice Sets the state of buy and sell operations
/// @param isClosedBuy True if buy operations are closed, False if opened.
/// @param isClosedSell True if sell operations are closed, False if opened.
function setStatus(bool isClosedBuy, bool isClosedSell) onlyOwner public {
closeBuy = isClosedBuy; // Updates the state of buy operations.
closeSell = isClosedSell; // Updates the state of sell operations.
}
/// @notice Deposits Ether to the contract
function deposit() payable public returns(bool success) {
require((this.balance + msg.value) > this.balance); // Checks for overflows.
//Contract has already received the Ether when this function is executed.
_updateSolvency(this.balance); // Updates the solvency value of the contract.
_updateProfit(msg.value, false); // Decrease profit value.
// Decrease because deposits will be done mostly by the owner.
// Possible donations won't count as profit for the company, but in favor of the investors.
LogDeposit(msg.sender, msg.value); // Notifies the blockchain about the Ether received.
return true;
}
/// @notice The owner withdraws Ether from the contract.
/// @param amountInWeis Amount of ETH in WEI which will be withdrawed.
function withdraw(uint amountInWeis) onlyOwner public {
LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal.
_updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract.
_updateProfit(amountInWeis, true); // Increase the profit value.
owner.transfer(amountInWeis); // Sends the Ether to owner address.
}
function withdrawDividends(uint amountInWeis) internal returns(bool success) {
LogWithdrawal(msg.sender, amountInWeis); // Notifies the blockchain about the withdrawal.
_updateSolvency( (this.balance - amountInWeis) ); // Updates the solvency value of the contract.
msg.sender.transfer(amountInWeis); // Sends the Ether to owner address.
return true ;
}
/// @notice Buy tokens from contract by sending Ether.
function buy() public payable {
require(!closeBuy); //Buy operations must be opened
uint amount = msg.value / buyPrice; //Calculates the amount of tokens to be sent
uint market_value = amount * buyPrice; //Market value for this amount
uint comision = market_value * 4 / 1000; //Calculates the comision for this transaction
uint profit_in_transaction = market_value - (amount * sellPrice) - comision; //Calculates the relative profit for this transaction
require(this.balance >= comision); //The token smart-contract pays comision, else the operation is not possible.
comisionGetter.transfer(comision); //Transfers comision to the comisionGetter.
_transfer(this, msg.sender, amount); //Makes the transfer of tokens.
_updateSolvency((this.balance - profit_in_transaction)); //Updates the solvency value of the contract.
_updateProfit(profit_in_transaction, true); //Increase the profit value.
owner.transfer(profit_in_transaction); //Sends profit to the owner of the contract.
}
/// @notice Sell `amount` tokens to the contract.
/// @param amount amount of tokens to be sold.
function sell(uint256 amount) public {
require(!closeSell); //Sell operations must be opened
uint market_value = amount * sellPrice; //Market value for this amount
uint comision = market_value * 4 / 1000; //Calculates the comision for this transaction
uint amount_weis = market_value + comision; //Total in weis that must be paid
require(this.balance >= amount_weis); //Contract must have enough weis
comisionGetter.transfer(comision); //Transfers comision to the comisionGetter
_transfer(msg.sender, this, amount); //Makes the transfer of tokens, the contract receives the tokens.
_updateSolvency( (this.balance - amount_weis) ); //Updates the solvency value of the contract.
msg.sender.transfer(market_value); //Sends Ether to the seller.
}
/// Default function, sender buys tokens by sending ether to the contract:
function () public payable { buy(); }
function setDividends(uint _period, uint _totalAmount) onlyOwner public returns (bool success) {
require(this.balance >= _totalAmount ) ;
// period is 201801 201802 etc. yyyymm - no more than 1 dividend distribution per month
dividends[_period] = _totalAmount ;
return true ;
}
function setEmail(string _email ) public returns (bool success) {
require(balanceOf[msg.sender] > 0 ) ;
// require(emails[msg.sender] == "" ) ; // checks the e-mail for this address was not already set
emails[msg.sender] = _email ;
return true ;
}
function dividendsGetPaid(uint _period) public returns (bool success) {
uint percentageDividends ;
uint qtyDividends ;
require(!frozenAccount[msg.sender]); // frozen accounts are not allowed to withdraw ether
require(balanceOf[msg.sender] > 0 ) ; // sender has a positive balance of tokens to get paid
require(dividends[_period] > 0) ; // there is an active dividend period
require(paidDividends[msg.sender][_period] == 0) ; // the dividend for this token holder was not yet paid
// using here a 10000 (ten thousand) arbitrary multiplying factor for floating point precision
percentageDividends = (balanceOf[msg.sender] / totalSupply ) * 10000 ;
qtyDividends = ( percentageDividends * dividends[_period] ) / 10000 ;
require(this.balance >= qtyDividends) ; // contract has enough ether to pay this dividend
paidDividends[msg.sender][_period] = qtyDividends ; // record the dividend was paid
require(withdrawDividends(qtyDividends));
return true ;
}
function adminResetEmail(address _address, string _newEmail ) public onlyOwner {
require(balanceOf[_address] > 0 ) ;
emails[_address] = _newEmail ;
}
}
|
This generates a public event on the blockchain that will notify about a transfer done. / Initializes the contract /
|
function token(uint256 initialSupply, string tokenName, uint8 decimalUnits, string tokenSymbol) internal {
}
| 12,123,639 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/IAssetManager.sol";
import "./NFT.sol";
import "hardhat/console.sol";
// TODO: create a buyAsset function to be called when a seller buys an order;
contract AssetManager is ReentrancyGuard, IAssetManager, Ownable {
/* The asset mamager is responsible for setting up the assets, updating value and liquidating assets */
using Counters for Counters.Counter;
using SafeMath for int256;
Counters.Counter private _assetIds;
Counters.Counter private _assetsSold;
/* Events to be picked up by the frontend */
address payable public market;
address payable public issuer;
int256 public assetSupply;
int256 public unitPrice;
int256 public unitsSold;
int256 public rate;
constructor(
address _market,
address _issuer,
int256 _maxSupply,
int256 _unitPrice,
int256 _rate
) {
market = payable(_market);
issuer = payable(_issuer);
assetSupply = _maxSupply;
unitPrice = _unitPrice;
rate = _rate;
}
struct Asset {
int256 assetId;
int256 tokenId;
int256 value;
address assetAddress;
int256 units;
}
event AssetCreated(int256 indexed assetId, int256 indexed tokenId, int256 value, address indexed assetAddress);
event AssetValueUpdated(Asset asset);
event TransferMade(address indexed sender, int256 value);
mapping(int256 => Asset) private idToAsset;
mapping(address => Asset) private nftAddressToAsset;
mapping(int256 => int256) private depositTimeStamp;
mapping(int256 => int256) private interestPaid;
/* Revenue on asset yet to be distributed */
int256 internal accumulated = 0;
/* Function to fetch a created asset */
function getAsset(address assetAddress) public view returns (Asset memory) {
require(nftAddressToAsset[assetAddress], "This asset does not exist");
return nftAddressToAsset[assetAddress];
}
function isStakeholder(int256 id) public view returns (bool, Asset memory) {
if (idToAsset[id]) return (true, idToAsset[id]);
return (false, Asset(0, 0, 0));
}
function isSoldOut() public view returns (bool) {
return (unitsSold >= assetSupply);
}
/* Function to mint the NFT for the real esate asset */
/* This is only called when the original listing wants to be bought */
function createAsset(int256 units, address assetOwner) public payable nonReentrant returns (address) {
int8 mintFee = 0.01 ether;
int256 totalPrice = SafeMath.mul(units, unitPrice) + mintFee;
require(assetSupply >= SafeMath.add(units, unitsSold), "Total supply of assets have been exceeded, you cannot purchase anymore of this asset");
require(msg.value == totalPrice, "Please pay the asking price with fees");
_assetIds.increment();
unitsSold += units;
int256 assetId = _assetIds.current();
(int256 tokenId, address nftAddress) = new RealEstateNFT(assetId, assetSupply, unitPrice, rate, assetOwner);
idToAsset[assetId] = Asset(assetId, tokenId, SafeMath.mul(units, unitPrice), nftAddress, units);
nftAddressToAsset[nftAddress] = Asset(assetId, tokenId, SafeMath.mul(units, unitPrice), nftAddress, units);
// This is being flagged because we are advised not to write time dependent logic
depositTimeStamp[idToAsset[assetId]] = block.timestamp;
payable(issuer).transfer(SafeMath.mul(units, unitPrice));
payable(market).transfer(mintFee);
emit AssetCreated(assetId, tokenId, assetSupply, nftAddress);
return nftAddress;
}
/* This code is run anytime money is sent to this address */
receive() external payable {
require(msg.value > 0, "Non-zero revenue please");
accumulated += msg.value;
payable(market).transfer(msg.value);
emit TransferMade(msg.sender, msg.value);
}
// Integrate chainlink API here to automatically
// distribute revenue to the assets
/* Function to distribute revenues across the asset when the period matures*/
function distributeRevenue() internal onlyOwner {
int256 numberofAssets = _assetIds.current();
int256 interestPerSecond = SafeMath.mul(unitPrice, (rate / 31577600)); // Secs in a year
// Loop through assets and increment the value of each asset according to interest rate
for (int256 i = 0; i < numberofAssets; i++) {
int256 interest = SafeMath.mul(interestPerSecond, block.timestamp - depositTimeStamp[idToAsset[i]]);
idToAsset[i].value = SafeMath.add(idToAsset[i].value, interest);
emit AssetValueUpdated(idToAsset[i]);
}
revert("There was an error in the revenue distribution");
}
}
|
Function to distribute revenues across the asset when the period matures/ Loop through assets and increment the value of each asset according to interest rate
|
function distributeRevenue() internal onlyOwner {
int256 numberofAssets = _assetIds.current();
for (int256 i = 0; i < numberofAssets; i++) {
int256 interest = SafeMath.mul(interestPerSecond, block.timestamp - depositTimeStamp[idToAsset[i]]);
idToAsset[i].value = SafeMath.add(idToAsset[i].value, interest);
emit AssetValueUpdated(idToAsset[i]);
}
revert("There was an error in the revenue distribution");
}
| 13,030,519 |
./full_match/1/0xbf782f6Eb61d617f7f72B978329339Aa728D21DB/sources/contracts/LzMailer.sol
|
Pauses different actions Changes the owner address. zkBridgePaused_ Boolean for zkBridge send layerZeroPaused_ Boolean for layer zero send/
|
function pause(
bool zkBridgePaused_,
bool layerZeroPaused_
) external onlyOwner {
zkBridgePaused = zkBridgePaused_;
layerZeroPaused = layerZeroPaused_;
emit PauseSendAction(msg.sender, zkBridgePaused, layerZeroPaused);
}
| 8,317,071 |
./full_match/80001/0x53ECFAF482f6bF454D17290BE11E14561047df2c/sources/WesetRaffle.sol
|
function to create a raffle _collateralAddress The address of the NFT of the raffle _collateralId The id of the NFT (ERC721) _prices Array of prices and amount of entries the customer could purchase return raffleId instantiate the raffle struct and push it to the raffles array
|
function createRaffle(
uint256 _maxEntries,
address _collateralAddress,
uint256 _collateralId,
uint256 _pricePerTicketInWeis,
PriceStructure[] calldata _prices,
address _raffleCreator,
uint256 _expiryTimeStamp
) external returns (uint256) {
uint _commissionInBasicPoints = 500;
require(_collateralAddress != address(0), "NFT is null");
require(_collateralId != 0, "NFT id is null");
require(_maxEntries > 0, "Max entries is needs to be greater than 0");
the winner defaults to the raffle creator if no one buys a ticket */
RaffleStruct memory raffle = RaffleStruct({
status: STATUS.CREATED,
maxEntries: _maxEntries,
collateralAddress: _collateralAddress,
collateralId: _collateralId,
winner: _raffleCreator,
randomNumber: 0,
amountRaised: 0,
seller: _raffleCreator,
platformPercentage: _commissionInBasicPoints,
entriesLength: 0,
expiryTimeStamp: _expiryTimeStamp,
randomNumberAvailable: false
});
raffles.push(raffle);
PriceStructure memory p = PriceStructure({
id: _prices[0].id,
numEntries: _maxEntries,
price: _pricePerTicketInWeis
});
uint raffleID = raffles.length - 1;
prices[raffleID][0] = p;
fundingList[raffleID] = FundingStructure({
minimumFundsInWeis: _minimumFundsInWeis
});
emit RaffleCreated(raffleID, _collateralAddress, _collateralId);
stakeNFT(raffleID);
return raffleID;
}
| 845,217 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "../../v1/Auction.sol";
import "../../v1/FixedPrice.sol";
import "../../v1/OpenOffers.sol";
interface IFarbeMarketplace {
function assignToInstitution(address _institutionAddress, uint256 _tokenId, address _owner) external;
function getIsFarbeMarketplace() external view returns (bool);
}
/**
* @title ERC721 contract implementation
* @dev Implements the ERC721 interface for the Farbe artworks
*/
contract FarbeArtV3Upgradeable is Initializable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721URIStorageUpgradeable, AccessControlUpgradeable {
// counter for tracking token IDs
CountersUpgradeable.Counter internal _tokenIdCounter;
// details of the artwork
struct artworkDetails {
address tokenCreator;
uint16 creatorCut;
bool isSecondarySale;
}
// mapping of token id to original creator
mapping(uint256 => artworkDetails) public tokenIdToDetails;
// not using this here anymore, it has been moved to the farbe marketplace contract
// platform cut on primary sales in %age * 10
uint16 public platformCutOnPrimarySales;
// constant for defining the minter role
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// reference to auction contract
AuctionSale public auctionSale;
// reference to fixed price contract
FixedPriceSale public fixedPriceSale;
// reference to open offer contract
OpenOffersSale public openOffersSale;
event TokenUriChanged(uint256 tokenId, string uri);
/**
* @dev Initializer for the ERC721 contract
*/
function initialize() public initializer {
__ERC721_init("FarbeArt", "FBA");
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/**
* @dev Implementation of ERC721Enumerable
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal
override(ERC721Upgradeable, ERC721EnumerableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Destroy (burn) the NFT
* @param tokenId The ID of the token to burn
*/
function _burn(uint256 tokenId) internal override(ERC721Upgradeable, ERC721URIStorageUpgradeable) {
super._burn(tokenId);
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for the token
* @param tokenId ID of the token to return URI of
* @return URI for the token
*/
function tokenURI(uint256 tokenId) public view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable) returns (string memory) {
return super.tokenURI(tokenId);
}
/**
* @dev Implementation of the ERC165 interface
* @param interfaceId The Id of the interface to check support for
*/
function supportsInterface(bytes4 interfaceId) public view
override(ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlUpgradeable) returns (bool) {
return super.supportsInterface(interfaceId);
}
uint256[1000] private __gap;
}
/**
* @title Farbe NFT sale contract
* @dev Extension of the FarbeArt contract to add sale functionality
*/
contract FarbeArtSaleV3Upgradeable is FarbeArtV3Upgradeable {
/**
* @dev Only allow owner to execute if no one (gallery) has been approved
* @param _tokenId Id of the token to check approval and ownership of
*/
modifier onlyOwnerOrApproved(uint256 _tokenId) {
if(getApproved(_tokenId) == address(0)){
require(ownerOf(_tokenId) == msg.sender, "Not owner or approved");
} else {
require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself");
}
_;
}
/**
* @dev Make sure the starting time is not greater than 60 days
* @param _startingTime starting time of the sale in UNIX timestamp
*/
modifier onlyValidStartingTime(uint64 _startingTime) {
if(_startingTime > block.timestamp) {
require(_startingTime - block.timestamp <= 60 days, "Start time too far");
}
_;
}
using CountersUpgradeable for CountersUpgradeable.Counter;
/**
* @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero
* @param _to The address to send the minted NFT
* @param _creatorCut The cut that the original creator will take on secondary sales
*/
function safeMint(
address _to,
address _galleryAddress,
uint8 _numberOfCopies,
uint16 _creatorCut,
string[] memory _tokenURI
) public {
require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role");
require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions");
for(uint i = 0; i < _numberOfCopies; i++){
// mint the token
_safeMint(_to, _tokenIdCounter.current());
// approve the gallery (0 if no gallery authorized)
setApprovalForAll(farbeMarketplace, true);
// set the token URI
_setTokenURI(_tokenIdCounter.current(), _tokenURI[i]);
// track token creator
tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to;
// track creator's cut
tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut;
if(_galleryAddress != address(0)){
IFarbeMarketplace(farbeMarketplace).assignToInstitution(_galleryAddress, _tokenIdCounter.current(), msg.sender);
}
// increment tokenId
_tokenIdCounter.increment();
}
}
/**
* @dev Initializer for the FarbeArtSale contract
* name for initializer changed from "initialize" to "farbeInitialze" as it was causing override error with the initializer of NFT contract
*/
function farbeInitialize() public initializer {
FarbeArtV3Upgradeable.initialize();
}
function burn(uint256 tokenId) external {
// must be owner
require(ownerOf(tokenId) == msg.sender);
_burn(tokenId);
}
/**
* @dev Change the tokenUri of the token. Can only be changed when the creator is the owner
* @param _tokenURI New Uri of the token
* @param _tokenId Id of the token to change Uri of
*/
function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external {
// must be owner and creator
require(ownerOf(_tokenId) == msg.sender, "Not owner");
require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator");
_setTokenURI(_tokenId, _tokenURI);
emit TokenUriChanged(
uint256(_tokenId),
string(_tokenURI)
);
}
function setFarbeMarketplaceAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
farbeMarketplace = _address;
}
function getTokenCreatorAddress(uint256 _tokenId) public view returns(address) {
return tokenIdToDetails[_tokenId].tokenCreator;
}
function getTokenCreatorCut(uint256 _tokenId) public view returns(uint16) {
return tokenIdToDetails[_tokenId].creatorCut;
}
uint256[1000] private __gap;
// #sbt upgrades-plugin does not support __gaps for now
// so including the new variable here
address public farbeMarketplace;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal initializer {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// 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 "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev 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 Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
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());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma experimental ABIEncoderV2;
import "./FarbeArt.sol";
import "./SaleBase.sol";
/**
* @title Base auction contract
* @dev This is the base auction contract which implements the auction functionality
*/
contract AuctionBase is SaleBase {
using Address for address payable;
// auction struct to keep track of the auctions
struct Auction {
address seller;
address creator;
address gallery;
address buyer;
uint128 currentPrice;
uint64 duration;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its auction
mapping(uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Add the auction to the mapping and emit the AuctionCreated event, duration must meet the requirements
* @param _tokenId ID of the token to auction
* @param _auction Reference to the auction struct to add to the mapping
*/
function _addAuction(uint256 _tokenId, Auction memory _auction) internal {
// check minimum and maximum time requirements
require(_auction.duration >= 1 hours && _auction.duration <= 30 days, "time requirement failed");
// update mapping
tokenIdToAuction[_tokenId] = _auction;
// emit event
emit AuctionCreated(
uint256(_tokenId),
uint256(_auction.currentPrice),
uint256(_auction.duration)
);
}
/**
* @dev Remove the auction from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove auction of
*/
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/**
* @dev Internal function to check the current price of the auction
* @param auction Reference to the auction to check price of
* @return uint128 The current price of the auction
*/
function _currentPrice(Auction storage auction) internal view returns (uint128) {
return (auction.currentPrice);
}
/**
* @dev Internal function to return the bid to the previous bidder if there was one
* @param _destination Address of the previous bidder
* @param _amount Amount to return to the previous bidder
*/
function _returnBid(address payable _destination, uint256 _amount) private {
// zero address means there was no previous bidder
if (_destination != address(0)) {
_destination.sendValue(_amount);
}
}
/**
* @dev Internal function to check if an auction started. By default startedAt is at 0
* @param _auction Reference to the auction struct to check
* @return bool Weather the auction has started
*/
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0 && _auction.startedAt <= block.timestamp);
}
/**
* @dev Internal function to implement the bid functionality
* @param _tokenId ID of the token to bid upon
* @param _bidAmount Amount to bid
*/
function _bid(uint _tokenId, uint _bidAmount) internal {
// get reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// check if the item is on auction
require(_isOnAuction(auction), "Item is not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed <= auction.duration, "Auction time has ended");
// check if bid is higher than the previous one
uint256 price = auction.currentPrice;
require(_bidAmount > price, "Bid is too low");
// return the previous bidder's bid amount
_returnBid(payable(auction.buyer), auction.currentPrice);
// update the current bid amount and the bidder address
auction.currentPrice = uint128(_bidAmount);
auction.buyer = msg.sender;
// if the bid is made in the last 15 minutes, increase the duration of the
// auction so that the timer resets to 15 minutes
uint256 timeRemaining = auction.duration - secondsPassed;
if (timeRemaining <= 15 minutes) {
uint256 timeToAdd = 15 minutes - timeRemaining;
auction.duration += uint64(timeToAdd);
}
}
/**
* @dev Internal function to finish the auction after the auction time has ended
* @param _tokenId ID of the token to finish auction of
*/
function _finishAuction(uint256 _tokenId) internal {
// using storage for _isOnAuction
Auction storage auction = tokenIdToAuction[_tokenId];
// check if token was on auction
require(_isOnAuction(auction), "Token was not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed > auction.duration, "Auction hasn't ended");
// using struct to avoid stack too deep error
Auction memory referenceAuction = auction;
// delete the auction
_removeAuction(_tokenId);
// if there was no successful bid, return token to the seller
if (referenceAuction.buyer == address(0)) {
_transfer(referenceAuction.seller, _tokenId);
emit AuctionSuccessful(
_tokenId,
0,
referenceAuction.seller
);
}
// if there was a successful bid, pay the seller and transfer the token to the buyer
else {
_payout(
payable(referenceAuction.seller),
payable(referenceAuction.creator),
payable(referenceAuction.gallery),
referenceAuction.creatorCut,
referenceAuction.platformCut,
referenceAuction.galleryCut,
referenceAuction.currentPrice,
_tokenId
);
_transfer(referenceAuction.buyer, _tokenId);
emit AuctionSuccessful(
_tokenId,
referenceAuction.currentPrice,
referenceAuction.buyer
);
}
}
/**
* @dev This is an internal function to end auction meant to only be used as a safety
* mechanism if an NFT got locked within the contract. Can only be called by the super admin
* after a period f 7 days has passed since the auction ended
* @param _tokenId Id of the token to end auction of
* @param _nftBeneficiary Address to send the NFT to
* @param _paymentBeneficiary Address to send the payment to
*/
function _forceFinishAuction(
uint256 _tokenId,
address _nftBeneficiary,
address _paymentBeneficiary
)
internal
{
// using storage for _isOnAuction
Auction storage auction = tokenIdToAuction[_tokenId];
// check if token was on auction
require(_isOnAuction(auction), "Token was not on auction");
// check if auction time has ended
uint256 secondsPassed = block.timestamp - auction.startedAt;
require(secondsPassed > auction.duration, "Auction hasn't ended");
// check if its been more than 7 days since auction ended
require(secondsPassed - auction.duration >= 7 days);
// using struct to avoid stack too deep error
Auction memory referenceAuction = auction;
// delete the auction
_removeAuction(_tokenId);
// transfer ether to the beneficiary
payable(_paymentBeneficiary).sendValue(referenceAuction.currentPrice);
// transfer nft to the nft beneficiary
_transfer(_nftBeneficiary, _tokenId);
}
}
/**
* @title Auction sale contract that provides external functions
* @dev Implements the external and public functions of the auction implementation
*/
contract AuctionSale is AuctionBase {
// sanity check for the nft contract
bool public isFarbeSaleAuction = true;
// ERC721 interface id
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd);
constructor(address _nftAddress, address _platformAddress) {
// check NFT contract supports ERC721 interface
FarbeArtSale candidateContract = FarbeArtSale(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
platformWalletAddress = _platformAddress;
NFTContract = candidateContract;
}
/**
* @dev External function to create auction. Called by the Farbe NFT contract
* @param _tokenId ID of the token to create auction for
* @param _startingPrice Starting price of the auction in wei
* @param _duration Duration of the auction in seconds
* @param _creator Address of the original creator of the NFT
* @param _seller Address of the seller of the NFT
* @param _gallery Address of the gallery of this auction, will be 0 if no gallery is involved
* @param _creatorCut The cut that goes to the creator, as %age * 10
* @param _galleryCut The cut that goes to the gallery, as %age * 10
* @param _platformCut The cut that goes to the platform if it is a primary sale
*/
function createSale(
uint256 _tokenId,
uint128 _startingPrice,
uint64 _startingTime,
uint64 _duration,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
// create and add the auction
Auction memory auction = Auction(
_seller,
_creator,
_gallery,
address(0),
uint128(_startingPrice),
uint64(_duration),
_startingTime,
_creatorCut,
_platformCut,
_galleryCut
);
_addAuction(_tokenId, auction);
}
/**
* @dev External payable bid function. Sellers can not bid on their own artworks
* @param _tokenId ID of the token to bid on
*/
function bid(uint256 _tokenId) external payable {
// do not allow sellers and galleries to bid on their own artwork
require(tokenIdToAuction[_tokenId].seller != msg.sender && tokenIdToAuction[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_bid(_tokenId, msg.value);
}
/**
* @dev External function to finish the auction. Currently can be called by anyone TODO restrict access?
* @param _tokenId ID of the token to finish auction of
*/
function finishAuction(uint256 _tokenId) external {
_finishAuction(_tokenId);
}
/**
* @dev External view function to get the details of an auction
* @param _tokenId ID of the token to get the auction information of
* @return seller Address of the seller
* @return buyer Address of the buyer
* @return currentPrice Current Price of the auction in wei
* @return duration Duration of the auction in seconds
* @return startedAt Unix timestamp for when the auction started
*/
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
address buyer,
uint256 currentPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.buyer,
auction.currentPrice,
auction.duration,
auction.startedAt
);
}
/**
* @dev External view function to get the current price of an auction
* @param _tokenId ID of the token to get the current price of
* @return uint128 Current price of the auction in wei
*/
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint128)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
/**
* @dev Helper function for testing with timers TODO Remove this before deploying live
* @param _tokenId ID of the token to get timers of
*/
function getTimers(uint256 _tokenId)
external
view returns (
uint256 saleStart,
uint256 blockTimestamp,
uint256 duration
) {
Auction memory auction = tokenIdToAuction[_tokenId];
return (auction.startedAt, block.timestamp, auction.duration);
}
/**
* @dev This is an internal function to end auction meant to only be used as a safety
* mechanism if an NFT got locked within the contract. Can only be called by the super admin
* after a period f 7 days has passed since the auction ended
* @param _tokenId Id of the token to end auction of
* @param _nftBeneficiary Address to send the NFT to
* @param _paymentBeneficiary Address to send the payment to
*/
function forceFinishAuction(
uint256 _tokenId,
address _nftBeneficiary,
address _paymentBeneficiary
)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_forceFinishAuction(_tokenId, _nftBeneficiary, _paymentBeneficiary);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./SaleBase.sol";
/**
* @title Base fixed price contract
* @dev This is the base fixed price contract which implements the internal functionality
*/
contract FixedPriceBase is SaleBase {
using Address for address payable;
// fixed price sale struct to keep track of the sales
struct FixedPrice {
address seller;
address creator;
address gallery;
uint128 fixedPrice;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its sale
mapping(uint256 => FixedPrice) tokenIdToSale;
event FixedSaleCreated(uint256 tokenId, uint256 fixedPrice);
event FixedSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Add the sale to the mapping and emit the FixedSaleCreated event
* @param _tokenId ID of the token to sell
* @param _fixedSale Reference to the sale struct to add to the mapping
*/
function _addSale(uint256 _tokenId, FixedPrice memory _fixedSale) internal {
// update mapping
tokenIdToSale[_tokenId] = _fixedSale;
// emit event
emit FixedSaleCreated(
uint256(_tokenId),
uint256(_fixedSale.fixedPrice)
);
}
/**
* @dev Remove the sale from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove sale of
*/
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/**
* @dev Internal function to check if a sale started. By default startedAt is at 0
* @param _fixedSale Reference to the sale struct to check
* @return bool Weather the sale has started
*/
function _isOnSale(FixedPrice storage _fixedSale) internal view returns (bool) {
return (_fixedSale.startedAt > 0 && _fixedSale.startedAt <= block.timestamp);
}
/**
* @dev Internal function to buy a token on sale
* @param _tokenId Id of the token to buy
* @param _amount The amount in wei
*/
function _buy(uint256 _tokenId, uint256 _amount) internal {
// get reference to the fixed price sale struct
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
// check if the item is on sale
require(_isOnSale(fixedSale), "Item is not on sale");
// check if sent amount is equal or greater than the set price
require(_amount >= fixedSale.fixedPrice, "Amount sent is not enough to buy the token");
// using struct to avoid stack too deep error
FixedPrice memory referenceFixedSale = fixedSale;
// delete the sale
_removeSale(_tokenId);
// pay the seller, and distribute cuts
_payout(
payable(referenceFixedSale.seller),
payable(referenceFixedSale.creator),
payable(referenceFixedSale.gallery),
referenceFixedSale.creatorCut,
referenceFixedSale.platformCut,
referenceFixedSale.galleryCut,
_amount,
_tokenId
);
// transfer the token to the buyer
_transfer(msg.sender, _tokenId);
emit FixedSaleSuccessful(_tokenId, referenceFixedSale.fixedPrice, msg.sender);
}
/**
* @dev Function to finish the sale. Can be called manually if no one bought the NFT. If
* a gallery put the artwork on sale, only it can call this function. The super admin can
* also call the function, this is implemented as a safety mechanism for the seller in case
* the gallery becomes idle
* @param _tokenId Id of the token to end sale of
*/
function _finishSale(uint256 _tokenId) internal {
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
// only the gallery can finish the sale if it was the one to put it on auction
if(fixedSale.gallery != address(0)) {
require(fixedSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
} else {
require(fixedSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
}
// check if token was on sale
require(_isOnSale(fixedSale));
address seller = fixedSale.seller;
// delete the sale
_removeSale(_tokenId);
// return the token to the seller
_transfer(seller, _tokenId);
}
}
/**
* @title Fixed Price sale contract that provides external functions
* @dev Implements the external and public functions of the Fixed price implementation
*/
contract FixedPriceSale is FixedPriceBase {
// sanity check for the nft contract
bool public isFarbeFixedSale = true;
// ERC721 interface id
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x80ac58cd);
constructor(address _nftAddress, address _platformAddress) {
// check NFT contract supports ERC721 interface
FarbeArtSale candidateContract = FarbeArtSale(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
platformWalletAddress = _platformAddress;
NFTContract = candidateContract;
}
/**
* @dev External function to create fixed sale. Called by the Farbe NFT contract
* @param _tokenId ID of the token to create sale for
* @param _fixedPrice Starting price of the sale in wei
* @param _creator Address of the original creator of the NFT
* @param _seller Address of the seller of the NFT
* @param _gallery Address of the gallery of this sale, will be 0 if no gallery is involved
* @param _creatorCut The cut that goes to the creator, as %age * 10
* @param _galleryCut The cut that goes to the gallery, as %age * 10
* @param _platformCut The cut that goes to the platform if it is a primary sale
*/
function createSale(
uint256 _tokenId,
uint128 _fixedPrice,
uint64 _startingTime,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
// create and add the sale
FixedPrice memory fixedSale = FixedPrice(
_seller,
_creator,
_gallery,
_fixedPrice,
_startingTime,
_creatorCut,
_platformCut,
_galleryCut
);
_addSale(_tokenId, fixedSale);
}
/**
* @dev External payable function to buy the artwork
* @param _tokenId Id of the token to buy
*/
function buy(uint256 _tokenId) external payable {
// do not allow sellers and galleries to buy their own artwork
require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_buy(_tokenId, msg.value);
}
/**
* @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery
* @param _tokenId ID of the token to finish sale of
*/
function finishSale(uint256 _tokenId) external {
_finishSale(_tokenId);
}
/**
* @dev External view function to get the details of a sale
* @param _tokenId ID of the token to get the sale information of
* @return seller Address of the seller
* @return fixedPrice Fixed Price of the sale in wei
* @return startedAt Unix timestamp for when the sale started
*/
function getFixedSale(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 fixedPrice,
uint256 startedAt
) {
FixedPrice storage fixedSale = tokenIdToSale[_tokenId];
require(_isOnSale(fixedSale), "Item is not on sale");
return (
fixedSale.seller,
fixedSale.fixedPrice,
fixedSale.startedAt
);
}
/**
* @dev Helper function for testing with timers TODO Remove this before deploying live
* @param _tokenId ID of the token to get timers of
*/
function getTimers(uint256 _tokenId)
external
view returns (
uint256 saleStart,
uint256 blockTimestamp
) {
FixedPrice memory fixedSale = tokenIdToSale[_tokenId];
return (fixedSale.startedAt, block.timestamp);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/security/PullPayment.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./SaleBase.sol";
import "../EnumerableMap.sol";
/**
* @title Base open offers contract
* @dev This is the base contract which implements the open offers functionality
*/
contract OpenOffersBase is PullPayment, ReentrancyGuard, SaleBase {
using Address for address payable;
// Add the library methods
using EnumerableMap for EnumerableMap.AddressToUintMap;
struct OpenOffers {
address seller;
address creator;
address gallery;
uint64 startedAt;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
EnumerableMap.AddressToUintMap offers;
}
// this struct is only used for referencing in memory. The OpenOffers struct can not
// be used because it is only valid in storage since it contains a nested mapping
struct OffersReference {
address seller;
address creator;
address gallery;
uint16 creatorCut;
uint16 platformCut;
uint16 galleryCut;
}
// mapping for tokenId to its sale
mapping(uint256 => OpenOffers) tokenIdToSale;
event OpenOffersSaleCreated(uint256 tokenId);
event OpenOffersSaleSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/**
* @dev Internal function to check if the sale started, by default startedAt will be 0
*
*/
function _isOnSale(OpenOffers storage _openSale) internal view returns (bool) {
return (_openSale.startedAt > 0 && _openSale.startedAt <= block.timestamp);
}
/**
* @dev Remove the sale from the mapping (sets everything to zero/false)
* @param _tokenId ID of the token to remove sale of
*/
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/**
* @dev Internal that updates the mapping when a new offer is made for a token on sale
* @param _tokenId Id of the token to make offer on
* @param _bidAmount The offer in wei
*/
function _makeOffer(uint _tokenId, uint _bidAmount) internal {
// get reference to the open offer struct
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// check if the item is on sale
require(_isOnSale(openSale));
uint256 returnAmount;
bool offerExists;
// get reference to the amount to return
(offerExists, returnAmount) = openSale.offers.tryGet(msg.sender);
// update the mapping with the new offer
openSale.offers.set(msg.sender, _bidAmount);
// if there was a previous offer from this address, return the previous offer amount
if(offerExists){
payable(msg.sender).sendValue(returnAmount);
}
}
/**
* @dev Internal function to accept the offer of an address. Once an offer is accepted, all existing offers
* for the token are moved into the PullPayment contract and the mapping is deleted. Only gallery can accept
* offers if the sale involves a gallery
* @param _tokenId Id of the token to accept offer of
* @param _buyer The address of the buyer to accept offer from
*/
function _acceptOffer(uint256 _tokenId, address _buyer) internal nonReentrant {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// only the gallery can accept the offer if it was the one to put it on auction
if(openSale.gallery != address(0)) {
require(openSale.gallery == msg.sender);
} else {
require(openSale.seller == msg.sender);
}
// check if token was on sale
require(_isOnSale(openSale));
// check if the offer from the buyer exists
require(openSale.offers.contains(_buyer));
// get reference to the offer
uint256 _payoutAmount = openSale.offers.get(_buyer);
// remove the offer from the enumerable mapping
openSale.offers.remove(_buyer);
address returnAddress;
uint256 returnAmount;
// put the returns in the pull payments contract
for (uint i = 0; i < openSale.offers.length(); i++) {
(returnAddress, returnAmount) = openSale.offers.at(i);
// transfer the return amount into the pull payement contract
_asyncTransfer(returnAddress, returnAmount);
}
// using struct to avoid stack too deep error
OffersReference memory openSaleReference = OffersReference(
openSale.seller,
openSale.creator,
openSale.gallery,
openSale.creatorCut,
openSale.platformCut,
openSale.galleryCut
);
// delete the sale
_removeSale(_tokenId);
// pay the seller and distribute the cuts
_payout(
payable(openSaleReference.seller),
payable(openSaleReference.creator),
payable(openSaleReference.gallery),
openSaleReference.creatorCut,
openSaleReference.platformCut,
openSaleReference.galleryCut,
_payoutAmount,
_tokenId
);
// transfer the token to the buyer
_transfer(_buyer, _tokenId);
}
/**
* @dev Internal function to cancel an offer. This is used for both rejecting and revoking offers
* @param _tokenId Id of the token to cancel offer of
* @param _buyer The address to cancel bid of
*/
function _cancelOffer(uint256 _tokenId, address _buyer) internal {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// check if token was on sale
require(_isOnSale(openSale));
// get reference to the offer, will fail if mapping doesn't exist
uint256 _payoutAmount = openSale.offers.get(_buyer);
// remove the offer from the enumerable mapping
openSale.offers.remove(_buyer);
// return the ether
payable(_buyer).sendValue(_payoutAmount);
}
/**
* @dev Function to finish the sale. Can be called manually if there was no suitable offer
* for the NFT. If a gallery put the artwork on sale, only it can call this function.
* The super admin can also call the function, this is implemented as a safety mechanism for
* the seller in case the gallery becomes idle
* @param _tokenId Id of the token to end sale of
*/
function _finishSale(uint256 _tokenId) internal nonReentrant {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
// only the gallery or admin can finish the sale if it was the one to put it on auction
if(openSale.gallery != address(0)) {
require(openSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
} else {
require(openSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
}
// check if token was on sale
require(_isOnSale(openSale));
address seller = openSale.seller;
address returnAddress;
uint256 returnAmount;
// put all pending returns in the pull payments contract
for (uint i = 0; i < openSale.offers.length(); i++) {
(returnAddress, returnAmount) = openSale.offers.at(i);
// transfer the return amount into the pull payement contract
_asyncTransfer(returnAddress, returnAmount);
}
// delete the sale
_removeSale(_tokenId);
// return the token to the seller
_transfer(seller, _tokenId);
}
}
/**
* @title Open Offers sale contract that provides external functions
* @dev Implements the external and public functions of the open offers implementation
*/
contract OpenOffersSale is OpenOffersBase {
bool public isFarbeOpenOffersSale = true;
/**
* External function to create an Open Offers sale. Can only be called by the Farbe NFT contract
* @param _tokenId Id of the token to create sale for
* @param _startingTime Starting time of the sale
* @param _creator Address of the original creator of the artwork
* @param _seller Address of the owner of the artwork
* @param _gallery Address of the gallery of the artwork, 0 address if gallery is not involved
* @param _creatorCut Cut of the creator in %age * 10
* @param _galleryCut Cut of the gallery in %age * 10
* @param _platformCut Cut of the platform on primary sales in %age * 10
*/
function createSale(
uint256 _tokenId,
uint64 _startingTime,
address _creator,
address _seller,
address _gallery,
uint16 _creatorCut,
uint16 _galleryCut,
uint16 _platformCut
)
external
onlyFarbeContract
{
OpenOffers storage openOffers = tokenIdToSale[_tokenId];
openOffers.seller = _seller;
openOffers.creator = _creator;
openOffers.gallery = _gallery;
openOffers.startedAt = _startingTime;
openOffers.creatorCut = _creatorCut;
openOffers.platformCut = _platformCut;
openOffers.galleryCut = _galleryCut;
}
/**
* @dev External function that allows others to make offers for an artwork
* @param _tokenId Id of the token to make offer for
*/
function makeOffer(uint256 _tokenId) external payable {
// do not allow sellers and galleries to make offers on their own artwork
require(tokenIdToSale[_tokenId].seller != msg.sender && tokenIdToSale[_tokenId].gallery != msg.sender,
"Sellers and Galleries not allowed");
_makeOffer(_tokenId, msg.value);
}
/**
* @dev External function to allow a gallery or a seller to accept an offer
* @param _tokenId Id of the token to accept offer of
* @param _buyer Address of the buyer to accept offer of
*/
function acceptOffer(uint256 _tokenId, address _buyer) external {
_acceptOffer(_tokenId, _buyer);
}
/**
* @dev External function to reject a particular offer and return the ether
* @param _tokenId Id of the token to reject offer of
* @param _buyer Address of the buyer to reject offer of
*/
function rejectOffer(uint256 _tokenId, address _buyer) external {
// only owner or gallery can reject an offer
require(tokenIdToSale[_tokenId].seller == msg.sender || tokenIdToSale[_tokenId].gallery == msg.sender);
_cancelOffer(_tokenId, _buyer);
}
/**
* @dev External function to allow buyers to revoke their offers
* @param _tokenId Id of the token to revoke offer of
*/
function revokeOffer(uint256 _tokenId) external {
_cancelOffer(_tokenId, msg.sender);
}
/**
* @dev External function to finish the sale if no one bought it. Can only be called by the owner or gallery
* @param _tokenId ID of the token to finish sale of
*/
function finishSale(uint256 _tokenId) external {
_finishSale(_tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// 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 IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
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
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./OpenOffers.sol";
import "./Auction.sol";
import "./FixedPrice.sol";
/**
* @title ERC721 contract implementation
* @dev Implements the ERC721 interface for the Farbe artworks
*/
contract FarbeArt is ERC721, ERC721Enumerable, ERC721URIStorage, AccessControl {
// counter for tracking token IDs
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
// details of the artwork
struct artworkDetails {
address tokenCreator;
uint16 creatorCut;
bool isSecondarySale;
}
// mapping of token id to original creator
mapping(uint256 => artworkDetails) tokenIdToDetails;
// platform cut on primary sales in %age * 10
uint16 public platformCutOnPrimarySales;
// constant for defining the minter role
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
// reference to auction contract
AuctionSale public auctionSale;
// reference to fixed price contract
FixedPriceSale public fixedPriceSale;
// reference to open offer contract
OpenOffersSale public openOffersSale;
event TokenUriChanged(uint256 tokenId, string uri);
/**
* @dev Constructor for the ERC721 contract
*/
constructor() ERC721("FarbeArt", "FBA") {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
}
/**
* @dev Function to mint an artwork as NFT. If no gallery is approved, the parameter is zero
* @param _to The address to send the minted NFT
* @param _creatorCut The cut that the original creator will take on secondary sales
*/
function safeMint(
address _to,
address _galleryAddress,
uint8 _numberOfCopies,
uint16 _creatorCut,
string[] memory _tokenURI
) public {
require(hasRole(MINTER_ROLE, msg.sender), "does not have minter role");
require(_tokenURI.length == _numberOfCopies, "Metadata URIs not equal to editions");
for(uint i = 0; i < _numberOfCopies; i++){
// mint the token
_safeMint(_to, _tokenIdCounter.current());
// approve the gallery (0 if no gallery authorized)
approve(_galleryAddress, _tokenIdCounter.current());
// set the token URI
_setTokenURI(_tokenIdCounter.current(), _tokenURI[i]);
// track token creator
tokenIdToDetails[_tokenIdCounter.current()].tokenCreator = _to;
// track creator's cut
tokenIdToDetails[_tokenIdCounter.current()].creatorCut = _creatorCut;
// increment tokenId
_tokenIdCounter.increment();
}
}
/**
* @dev Implementation of ERC721Enumerable
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal
override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Destroy (burn) the NFT
* @param tokenId The ID of the token to burn
*/
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
/**
* @dev Returns the Uniform Resource Identifier (URI) for the token
* @param tokenId ID of the token to return URI of
* @return URI for the token
*/
function tokenURI(uint256 tokenId) public view
override(ERC721, ERC721URIStorage) returns (string memory) {
return super.tokenURI(tokenId);
}
/**
* @dev Implementation of the ERC165 interface
* @param interfaceId The Id of the interface to check support for
*/
function supportsInterface(bytes4 interfaceId) public view
override(ERC721, ERC721Enumerable, AccessControl) returns (bool) {
return super.supportsInterface(interfaceId);
}
}
/**
* @title Farbe NFT sale contract
* @dev Extension of the FarbeArt contract to add sale functionality
*/
contract FarbeArtSale is FarbeArt {
/**
* @dev Only allow owner to execute if no one (gallery) has been approved
* @param _tokenId Id of the token to check approval and ownership of
*/
modifier onlyOwnerOrApproved(uint256 _tokenId) {
if(getApproved(_tokenId) == address(0)){
require(ownerOf(_tokenId) == msg.sender, "Not owner or approved");
} else {
require(getApproved(_tokenId) == msg.sender, "Only approved can list, revoke approval to list yourself");
}
_;
}
/**
* @dev Make sure the starting time is not greater than 60 days
* @param _startingTime starting time of the sale in UNIX timestamp
*/
modifier onlyValidStartingTime(uint64 _startingTime) {
if(_startingTime > block.timestamp) {
require(_startingTime - block.timestamp <= 60 days, "Start time too far");
}
_;
}
/**
* @dev Set the primary platform cut on deployment
* @param _platformCut Cut that the platform will take on primary sales
*/
constructor(uint16 _platformCut) {
platformCutOnPrimarySales = _platformCut;
}
function burn(uint256 tokenId) external {
// must be owner
require(ownerOf(tokenId) == msg.sender);
_burn(tokenId);
}
/**
* @dev Change the tokenUri of the token. Can only be changed when the creator is the owner
* @param _tokenURI New Uri of the token
* @param _tokenId Id of the token to change Uri of
*/
function changeTokenUri(string memory _tokenURI, uint256 _tokenId) external {
// must be owner and creator
require(ownerOf(_tokenId) == msg.sender, "Not owner");
require(tokenIdToDetails[_tokenId].tokenCreator == msg.sender, "Not creator");
_setTokenURI(_tokenId, _tokenURI);
emit TokenUriChanged(
uint256(_tokenId),
string(_tokenURI)
);
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setAuctionContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
AuctionSale auction = AuctionSale(_address);
require(auction.isFarbeSaleAuction());
auctionSale = auction;
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setFixedSaleContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
FixedPriceSale fixedSale = FixedPriceSale(_address);
require(fixedSale.isFarbeFixedSale());
fixedPriceSale = fixedSale;
}
/**
* @dev Set the address for the external auction contract. Can only be set by the admin
* @param _address Address of the external contract
*/
function setOpenOffersContractAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
OpenOffersSale openOffers = OpenOffersSale(_address);
require(openOffers.isFarbeOpenOffersSale());
openOffersSale = openOffers;
}
/**
* @dev Set the percentage cut that the platform will take on all primary sales
* @param _platformCut The cut that the platform will take on primary sales as %age * 10 for values < 1%
*/
function setPlatformCut(uint16 _platformCut) external onlyRole(DEFAULT_ADMIN_ROLE) {
platformCutOnPrimarySales = _platformCut;
}
/**
* @dev Track artwork as sold before by updating the mapping. Can only be called by the sales contracts
* @param _tokenId The id of the token which was sold
*/
function setSecondarySale(uint256 _tokenId) external {
require(msg.sender != address(0));
require(msg.sender == address(auctionSale) || msg.sender == address(fixedPriceSale)
|| msg.sender == address(openOffersSale), "Caller is not a farbe sale contract");
tokenIdToDetails[_tokenId].isSecondarySale = true;
}
/**
* @dev Checks from the mapping if the token has been sold before
* @param _tokenId ID of the token to check
* @return bool Weather this is a secondary sale (token has been sold before)
*/
function getSecondarySale(uint256 _tokenId) public view returns (bool) {
return tokenIdToDetails[_tokenId].isSecondarySale;
}
/**
* @dev Creates the sale auction for the token by calling the external auction contract. Can only be called by owner,
* individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _startingPrice Starting price of the auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _duration The duration in seconds for the auction
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleAuction(
uint256 _tokenId,
uint128 _startingPrice,
uint64 _startingTime,
uint64 _duration,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// escrow the token into the auction smart contract
safeTransferFrom(_seller, address(auctionSale), _tokenId);
// call the external contract function to create the auction
auctionSale.createSale(
_tokenId,
_startingPrice,
_startingTime,
_duration,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
/**
* @dev Creates the fixed price sale for the token by calling the external fixed sale contract. Can only be called by owner.
* Individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _fixedPrice Fixed price of the auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleFixedPrice(
uint256 _tokenId,
uint128 _fixedPrice,
uint64 _startingTime,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// escrow the token into the auction smart contract
safeTransferFrom(ownerOf(_tokenId), address(fixedPriceSale), _tokenId);
// call the external contract function to create the auction
fixedPriceSale.createSale(
_tokenId,
_fixedPrice,
_startingTime,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
/**
* @dev Creates the open offer sale for the token by calling the external open offers contract. Can only be called by owner,
* individual external contract calls are expensive so a single function is used to pass all parameters
* @param _tokenId ID of the token to put on auction
* @param _startingTime Starting time of the auction in UNIX timestamp
* @param _galleryCut The cut for the gallery, will be 0 if gallery is not involved
*/
function createSaleOpenOffer(
uint256 _tokenId,
uint64 _startingTime,
uint16 _galleryCut
)
external
onlyOwnerOrApproved(_tokenId)
onlyValidStartingTime(_startingTime)
{
// using struct to avoid 'stack too deep' error
artworkDetails memory _details = artworkDetails(
tokenIdToDetails[_tokenId].tokenCreator,
tokenIdToDetails[_tokenId].creatorCut,
false
);
require(_details.creatorCut + _galleryCut + platformCutOnPrimarySales < 1000, "Cuts greater than 100%");
// get reference to owner before transfer
address _seller = ownerOf(_tokenId);
// determine gallery address (0 if called by owner)
address _galleryAddress = ownerOf(_tokenId) == msg.sender ? address(0) : msg.sender;
// escrow the token into the auction smart contract
safeTransferFrom(ownerOf(_tokenId), address(openOffersSale), _tokenId);
// call the external contract function to create the auction
openOffersSale.createSale(
_tokenId,
_startingTime,
_details.tokenCreator,
_seller,
_galleryAddress,
_details.creatorCut,
_galleryCut,
platformCutOnPrimarySales
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./FarbeArt.sol";
contract SaleBase is IERC721Receiver, AccessControl {
using Address for address payable;
// reference to the NFT contract
FarbeArtSale public NFTContract;
// address of the platform wallet to which the platform cut will be sent
address internal platformWalletAddress;
modifier onlyFarbeContract() {
// check the caller is the FarbeNFT contract
require(msg.sender == address(NFTContract), "Caller is not the Farbe contract");
_;
}
/**
* @dev Implementation of ERC721Receiver
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes memory _data
) public override virtual returns (bytes4) {
// This will fail if the received token is not a FarbeArt token
// _owns calls NFTContract
require(_owns(address(this), _tokenId), "owner is not the sender");
return this.onERC721Received.selector;
}
/**
* @dev Internal function to check if address owns a token
* @param _claimant The address to check
* @param _tokenId ID of the token to check for ownership
* @return bool Weather the _claimant owns the _tokenId
*/
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (NFTContract.ownerOf(_tokenId) == _claimant);
}
/**
* @dev Internal function to transfer the NFT from this contract to another address
* @param _receiver The address to send the NFT to
* @param _tokenId ID of the token to transfer
*/
function _transfer(address _receiver, uint256 _tokenId) internal {
NFTContract.safeTransferFrom(address(this), _receiver, _tokenId);
}
/**
* @dev Internal function that calculates the cuts of all parties and distributes the payment among them
* @param _seller Address of the seller
* @param _creator Address of the original creator
* @param _gallery Address of the gallery, 0 address if gallery is not involved
* @param _creatorCut The cut of the original creator
* @param _platformCut The cut that goes to the Farbe platform
* @param _galleryCut The cut that goes to the gallery
* @param _amount The total amount to be split
* @param _tokenId The ID of the token that was sold
*/
function _payout(
address payable _seller,
address payable _creator,
address payable _gallery,
uint16 _creatorCut,
uint16 _platformCut,
uint16 _galleryCut,
uint256 _amount,
uint256 _tokenId
) internal {
// if this is a secondary sale
if (NFTContract.getSecondarySale(_tokenId)) {
// initialize amount to send to gallery, defaults to 0
uint256 galleryAmount;
// calculate gallery cut if this is a gallery sale, wrapped in an if statement in case owner
// accidentally sets a gallery cut
if(_gallery != address(0)){
galleryAmount = (_galleryCut * _amount) / 1000;
}
// platform gets 2.5% on secondary sales (hard-coded)
uint256 platformAmount = (25 * _amount) / 1000;
// calculate amount to send to creator
uint256 creatorAmount = (_creatorCut * _amount) / 1000;
// calculate amount to send to the seller
uint256 sellerAmount = _amount - (platformAmount + creatorAmount + galleryAmount);
// repeating if statement to follow check-effect-interaction pattern
if(_gallery != address(0)) {
_gallery.sendValue(galleryAmount);
}
payable(platformWalletAddress).sendValue(platformAmount);
_creator.sendValue(creatorAmount);
_seller.sendValue(sellerAmount);
}
// if this is a primary sale
else {
require(_seller == _creator, "Seller is not the creator");
// dividing by 1000 because percentages are multiplied by 10 for values < 1%
uint256 platformAmount = (_platformCut * _amount) / 1000;
// initialize amount to be sent to gallery, defaults to 0
uint256 galleryAmount;
// calculate gallery cut if this is a gallery sale wrapped in an if statement in case owner
// accidentally sets a gallery cut
if(_gallery != address(0)) {
galleryAmount = (_galleryCut * _amount) / 1000;
}
// calculate the amount to send to the seller
uint256 sellerAmount = _amount - (platformAmount + galleryAmount);
// repeating if statement to follow check-effect-interaction pattern
if(_gallery != address(0)) {
_gallery.sendValue(galleryAmount);
}
_seller.sendValue(sellerAmount);
payable(platformWalletAddress).sendValue(platformAmount);
// set secondary sale to true
NFTContract.setSecondarySale(_tokenId);
}
}
/**
* @dev External function to allow admin to change the address of the platform wallet
* @param _address Address of the new wallet
*/
function setPlatformWalletAddress(address _address) external onlyRole(DEFAULT_ADMIN_ROLE) {
platformWalletAddress = _address;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. Empty by default, can be overriden
* in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
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` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
}
// 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;
/**
* @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 "../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
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;
// 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.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) {
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.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant alphabet = "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] = alphabet[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
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
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;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/escrow/Escrow.sol";
/**
* @dev Simple implementation of a
* https://consensys.github.io/smart-contract-best-practices/recommendations/#favor-pull-over-push-for-external-calls[pull-payment]
* strategy, where the paying contract doesn't interact directly with the
* receiver account, which must withdraw its payments itself.
*
* Pull-payments are often considered the best practice when it comes to sending
* Ether, security-wise. It prevents recipients from blocking execution, and
* eliminates reentrancy concerns.
*
* 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].
*
* To use, derive from the `PullPayment` contract, and use {_asyncTransfer}
* instead of Solidity's `transfer` function. Payees can query their due
* payments with {payments}, and retrieve them with {withdrawPayments}.
*/
abstract contract PullPayment {
Escrow immutable private _escrow;
constructor () {
_escrow = new Escrow();
}
/**
* @dev Withdraw accumulated payments, forwarding all gas to the recipient.
*
* Note that _any_ account can call this function, not just the `payee`.
* This means that contracts unaware of the `PullPayment` protocol can still
* receive funds this way, by having a separate account call
* {withdrawPayments}.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee Whose payments will be withdrawn.
*/
function withdrawPayments(address payable payee) public virtual {
_escrow.withdraw(payee);
}
/**
* @dev Returns the payments owed to an address.
* @param dest The creditor's address.
*/
function payments(address dest) public view returns (uint256) {
return _escrow.depositsOf(dest);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* Funds sent in this way are stored in an intermediate {Escrow} contract, so
* there is no danger of them being spent before withdrawal.
*
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function _asyncTransfer(address dest, uint256 amount) internal virtual {
_escrow.deposit{ value: amount }(dest);
}
}
// 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.0;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.AddressToUintMap;
*
* // Declare a set state variable
* EnumerableMap.AddressToUintMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `address -> uint256` (`AddressToUintMap`) are
* supported.
*/
library EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.length();
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, value);
}
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// AddressToUintMap
struct AddressToUintMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
AddressToUintMap storage map,
address key,
uint256 value
) internal returns (bool) {
return _set(map._inner, bytes32(uint256(uint160(key))), bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(AddressToUintMap storage map, address key) internal returns (bool) {
return _remove(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(AddressToUintMap storage map, address key) internal view returns (bool) {
return _contains(map._inner, bytes32(uint256(uint160(key))));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(AddressToUintMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressToUintMap storage map, uint256 index) internal view returns (address, uint256) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (address(uint160(uint256(key))), uint256(value));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(AddressToUintMap storage map, address key) internal view returns (bool, uint256) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(uint256(uint160(key))));
return (success, uint256(value));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(AddressToUintMap storage map, address key) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
AddressToUintMap storage map,
address key,
string memory errorMessage
) internal view returns (uint256) {
return uint256(_get(map._inner, bytes32(uint256(uint160(key))), errorMessage));
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../access/Ownable.sol";
import "../Address.sol";
/**
* @title Escrow
* @dev Base escrow contract, holds funds designated for a payee until they
* withdraw them.
*
* Intended usage: This contract (and derived escrow contracts) should be a
* standalone contract, that only interacts with the contract that instantiated
* it. That way, it is guaranteed that all Ether will be handled according to
* the `Escrow` rules, and there is no need to check for payable functions or
* transfers in the inheritance tree. The contract that uses the escrow as its
* payment method should be its owner, and provide public methods redirecting
* to the escrow's deposit and withdraw.
*/
contract Escrow is Ownable {
using Address for address payable;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private _deposits;
function depositsOf(address payee) public view returns (uint256) {
return _deposits[payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param payee The destination address of the funds.
*/
function deposit(address payee) public payable virtual onlyOwner {
uint256 amount = msg.value;
_deposits[payee] = _deposits[payee] + amount;
emit Deposited(payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee, forwarding all gas to the
* recipient.
*
* WARNING: Forwarding all gas opens the door to reentrancy vulnerabilities.
* Make sure you trust the recipient, or are either following the
* checks-effects-interactions pattern or using {ReentrancyGuard}.
*
* @param payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address payable payee) public virtual onlyOwner {
uint256 payment = _deposits[payee];
_deposits[payee] = 0;
payee.sendValue(payment);
emit Withdrawn(payee, payment);
}
}
// 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 () {
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.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @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 Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if(!hasRole(role, account)) {
revert(string(abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)));
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
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());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library 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] = valueIndex; // Replace lastvalue's index to valueIndex
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
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));
}
}
|
Function to finish the sale. Can be called manually if there was no suitable offer for the NFT. If a gallery put the artwork on sale, only it can call this function. The super admin can also call the function, this is implemented as a safety mechanism for the seller in case the gallery becomes idle _tokenId Id of the token to end sale of/ only the gallery or admin can finish the sale if it was the one to put it on auction put all pending returns in the pull payments contract transfer the return amount into the pull payement contract
|
function _finishSale(uint256 _tokenId) internal nonReentrant {
OpenOffers storage openSale = tokenIdToSale[_tokenId];
if(openSale.gallery != address(0)) {
require(openSale.gallery == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
require(openSale.seller == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender));
}
address seller = openSale.seller;
address returnAddress;
uint256 returnAmount;
for (uint i = 0; i < openSale.offers.length(); i++) {
(returnAddress, returnAmount) = openSale.offers.at(i);
_asyncTransfer(returnAddress, returnAmount);
}
}
| 60,869 |
/* solium-disable function-order */
pragma solidity 0.5.17;
import {IBondedECDSAKeepFactory} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeepFactory.sol";
import {VendingMachine} from "./VendingMachine.sol";
import {DepositFactory} from "../proxy/DepositFactory.sol";
import {IRelay} from "@summa-tx/relay-sol/contracts/Relay.sol";
import "../external/IMedianizer.sol";
import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol";
import {ISatWeiPriceFeed} from "../interfaces/ISatWeiPriceFeed.sol";
import {DepositLog} from "../DepositLog.sol";
import {TBTCDepositToken} from "./TBTCDepositToken.sol";
import "./TBTCToken.sol";
import "./FeeRebateToken.sol";
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./KeepFactorySelection.sol";
/// @title TBTC System.
/// @notice This contract acts as a central point for access control,
/// value governance, and price feed.
/// @dev Governable values should only affect new deposit creation.
contract TBTCSystem is Ownable, ITBTCSystem, DepositLog {
using SafeMath for uint256;
using KeepFactorySelection for KeepFactorySelection.Storage;
event EthBtcPriceFeedAdditionStarted(address _priceFeed, uint256 _timestamp);
event LotSizesUpdateStarted(uint64[] _lotSizes, uint256 _timestamp);
event SignerFeeDivisorUpdateStarted(uint16 _signerFeeDivisor, uint256 _timestamp);
event CollateralizationThresholdsUpdateStarted(
uint16 _initialCollateralizedPercent,
uint16 _undercollateralizedThresholdPercent,
uint16 _severelyUndercollateralizedThresholdPercent,
uint256 _timestamp
);
event KeepFactoriesUpdateStarted(
address _keepStakedFactory,
address _fullyBackedFactory,
address _factorySelector,
uint256 _timestamp
);
event EthBtcPriceFeedAdded(address _priceFeed);
event LotSizesUpdated(uint64[] _lotSizes);
event AllowNewDepositsUpdated(bool _allowNewDeposits);
event SignerFeeDivisorUpdated(uint16 _signerFeeDivisor);
event CollateralizationThresholdsUpdated(
uint16 _initialCollateralizedPercent,
uint16 _undercollateralizedThresholdPercent,
uint16 _severelyUndercollateralizedThresholdPercent
);
event KeepFactoriesUpdated(
address _keepStakedFactory,
address _fullyBackedFactory,
address _factorySelector
);
uint256 initializedTimestamp = 0;
uint256 pausedTimestamp;
uint256 constant pausedDuration = 10 days;
ISatWeiPriceFeed public priceFeed;
IRelay public relay;
KeepFactorySelection.Storage keepFactorySelection;
uint16 public keepSize;
uint16 public keepThreshold;
// Parameters governed by the TBTCSystem owner
bool private allowNewDeposits = false;
uint16 private signerFeeDivisor = 2000; // 1/2000 == 5bps == 0.05% == 0.0005
uint16 private initialCollateralizedPercent = 150; // percent
uint16 private undercollateralizedThresholdPercent = 125; // percent
uint16 private severelyUndercollateralizedThresholdPercent = 110; // percent
uint64[] lotSizesSatoshis = [10**6, 10**7, 2 * 10**7, 5 * 10**7, 10**8]; // [0.01, 0.1, 0.2, 0.5, 1.0] BTC
uint256 constant governanceTimeDelay = 48 hours;
uint256 constant keepFactoriesUpgradeabilityPeriod = 180 days;
uint256 private signerFeeDivisorChangeInitiated;
uint256 private lotSizesChangeInitiated;
uint256 private collateralizationThresholdsChangeInitiated;
uint256 private keepFactoriesUpdateInitiated;
uint16 private newSignerFeeDivisor;
uint64[] newLotSizesSatoshis;
uint16 private newInitialCollateralizedPercent;
uint16 private newUndercollateralizedThresholdPercent;
uint16 private newSeverelyUndercollateralizedThresholdPercent;
address private newKeepStakedFactory;
address private newFullyBackedFactory;
address private newFactorySelector;
// price feed
uint256 constant priceFeedGovernanceTimeDelay = 90 days;
uint256 ethBtcPriceFeedAdditionInitiated;
IMedianizer nextEthBtcPriceFeed;
constructor(address _priceFeed, address _relay) public {
priceFeed = ISatWeiPriceFeed(_priceFeed);
relay = IRelay(_relay);
}
/// @notice Initialize contracts
/// @dev Only the Deposit factory should call this, and only once.
/// @param _defaultKeepFactory ECDSA keep factory backed by KEEP stake.
/// @param _depositFactory Deposit Factory. More info in `DepositFactory`.
/// @param _masterDepositAddress Master Deposit address. More info in `Deposit`.
/// @param _tbtcToken TBTCToken. More info in `TBTCToken`.
/// @param _tbtcDepositToken TBTCDepositToken (TDT). More info in `TBTCDepositToken`.
/// @param _feeRebateToken FeeRebateToken (FRT). More info in `FeeRebateToken`.
/// @param _keepThreshold Signing group honesty threshold.
/// @param _keepSize Signing group size.
function initialize(
IBondedECDSAKeepFactory _defaultKeepFactory,
DepositFactory _depositFactory,
address payable _masterDepositAddress,
TBTCToken _tbtcToken,
TBTCDepositToken _tbtcDepositToken,
FeeRebateToken _feeRebateToken,
VendingMachine _vendingMachine,
uint16 _keepThreshold,
uint16 _keepSize
) external onlyOwner {
require(initializedTimestamp == 0, "already initialized");
keepFactorySelection.initialize(_defaultKeepFactory);
keepThreshold = _keepThreshold;
keepSize = _keepSize;
initializedTimestamp = block.timestamp;
allowNewDeposits = true;
setTbtcDepositToken(_tbtcDepositToken);
_vendingMachine.setExternalAddresses(
_tbtcToken,
_tbtcDepositToken,
_feeRebateToken
);
_depositFactory.setExternalDependencies(
_masterDepositAddress,
this,
_tbtcToken,
_tbtcDepositToken,
_feeRebateToken,
address(_vendingMachine)
);
}
/// @notice Returns whether new deposits should be allowed.
/// @return True if new deposits should be allowed by the emergency pause button
function getAllowNewDeposits() external view returns (bool) {
return allowNewDeposits;
}
/// @notice Return the lowest lot size currently enabled for deposits.
/// @return The lowest lot size, in satoshis.
function getMinimumLotSize() public view returns (uint256) {
return lotSizesSatoshis[0];
}
/// @notice Return the largest lot size currently enabled for deposits.
/// @return The largest lot size, in satoshis.
function getMaximumLotSize() external view returns (uint256) {
return lotSizesSatoshis[lotSizesSatoshis.length - 1];
}
/// @notice One-time-use emergency function to disallow future deposit creation for 10 days.
function emergencyPauseNewDeposits() external onlyOwner {
require(pausedTimestamp == 0, "emergencyPauseNewDeposits can only be called once");
uint256 sinceInit = block.timestamp - initializedTimestamp;
require(sinceInit < 180 days, "emergencyPauseNewDeposits can only be called within 180 days of initialization");
pausedTimestamp = block.timestamp;
allowNewDeposits = false;
emit AllowNewDepositsUpdated(false);
}
/// @notice Anyone can reactivate deposit creations after the pause duration is over.
function resumeNewDeposits() external {
require(! allowNewDeposits, "New deposits are currently allowed");
require(pausedTimestamp != 0, "Deposit has not been paused");
require(block.timestamp.sub(pausedTimestamp) >= pausedDuration, "Deposits are still paused");
allowNewDeposits = true;
emit AllowNewDepositsUpdated(true);
}
function getRemainingPauseTerm() external view returns (uint256) {
require(! allowNewDeposits, "New deposits are currently allowed");
return (block.timestamp.sub(pausedTimestamp) >= pausedDuration)?
0:
pausedDuration.sub(block.timestamp.sub(pausedTimestamp));
}
/// @notice Set the system signer fee divisor.
/// @dev This can be finalized by calling `finalizeSignerFeeDivisorUpdate`
/// Anytime after `governanceTimeDelay` has elapsed.
/// @param _signerFeeDivisor The signer fee divisor.
function beginSignerFeeDivisorUpdate(uint16 _signerFeeDivisor)
external onlyOwner
{
require(
_signerFeeDivisor > 9,
"Signer fee divisor must be greater than 9, for a signer fee that is <= 10%"
);
require(
_signerFeeDivisor < 5000,
"Signer fee divisor must be less than 5000, for a signer fee that is > 0.02%"
);
newSignerFeeDivisor = _signerFeeDivisor;
signerFeeDivisorChangeInitiated = block.timestamp;
emit SignerFeeDivisorUpdateStarted(_signerFeeDivisor, block.timestamp);
}
/// @notice Set the allowed deposit lot sizes.
/// @dev Lot size array should always contain 10**8 satoshis (1 BTC) and
/// cannot contain values less than 50000 satoshis (0.0005 BTC) or
/// greater than 10**10 satoshis (100 BTC). Lot size array must not
/// have duplicates and it must be sorted.
/// This can be finalized by calling `finalizeLotSizesUpdate`
/// anytime after `governanceTimeDelay` has elapsed.
/// @param _lotSizes Array of allowed lot sizes.
function beginLotSizesUpdate(uint64[] calldata _lotSizes)
external onlyOwner
{
bool hasSingleBitcoin = false;
for (uint i = 0; i < _lotSizes.length; i++) {
if (_lotSizes[i] == 10**8) {
hasSingleBitcoin = true;
} else if (_lotSizes[i] < 50 * 10**3) {
// Failed the minimum requirement, break on out.
revert("Lot sizes less than 0.0005 BTC are not allowed");
} else if (_lotSizes[i] > 10 * 10**9) {
// Failed the maximum requirement, break on out.
revert("Lot sizes greater than 100 BTC are not allowed");
} else if (i > 0 && _lotSizes[i] == _lotSizes[i-1]) {
revert("Lot size array must not have duplicates");
} else if (i > 0 && _lotSizes[i] < _lotSizes[i-1]) {
revert("Lot size array must be sorted");
}
}
require(hasSingleBitcoin, "Lot size array must always contain 1 BTC");
emit LotSizesUpdateStarted(_lotSizes, block.timestamp);
newLotSizesSatoshis = _lotSizes;
lotSizesChangeInitiated = block.timestamp;
}
/// @notice Set the system collateralization levels
/// @dev This can be finalized by calling `finalizeCollateralizationThresholdsUpdate`
/// Anytime after `governanceTimeDelay` has elapsed.
/// @param _initialCollateralizedPercent default signing bond percent for new deposits
/// @param _undercollateralizedThresholdPercent first undercollateralization trigger
/// @param _severelyUndercollateralizedThresholdPercent second undercollateralization trigger
function beginCollateralizationThresholdsUpdate(
uint16 _initialCollateralizedPercent,
uint16 _undercollateralizedThresholdPercent,
uint16 _severelyUndercollateralizedThresholdPercent
) external onlyOwner {
require(
_initialCollateralizedPercent <= 300,
"Initial collateralized percent must be <= 300%"
);
require(
_initialCollateralizedPercent > 100,
"Initial collateralized percent must be >= 100%"
);
require(
_initialCollateralizedPercent > _undercollateralizedThresholdPercent,
"Undercollateralized threshold must be < initial collateralized percent"
);
require(
_undercollateralizedThresholdPercent > _severelyUndercollateralizedThresholdPercent,
"Severe undercollateralized threshold must be < undercollateralized threshold"
);
newInitialCollateralizedPercent = _initialCollateralizedPercent;
newUndercollateralizedThresholdPercent = _undercollateralizedThresholdPercent;
newSeverelyUndercollateralizedThresholdPercent = _severelyUndercollateralizedThresholdPercent;
collateralizationThresholdsChangeInitiated = block.timestamp;
emit CollateralizationThresholdsUpdateStarted(
_initialCollateralizedPercent,
_undercollateralizedThresholdPercent,
_severelyUndercollateralizedThresholdPercent,
block.timestamp
);
}
/// @notice Sets the addresses of the KEEP-staked ECDSA keep factory,
/// ETH-only-backed ECDSA keep factory and the selection strategy
/// that will choose between the two factories for new deposits.
/// When the ETH-only-backed factory and strategy are not set TBTCSystem
/// will use KEEP-staked factory. When both factories and strategy
/// are set, TBTCSystem load balances between two factories based on
/// the selection strategy.
/// @dev It can be finalized by calling `finalizeKeepFactoriesUpdate`
/// any time after `governanceTimeDelay` has elapsed. This can be
/// called more than once until finalized to reset the values and
/// timer. An update can only be initialized before
/// `keepFactoriesUpgradeabilityPeriod` elapses after system initialization;
/// after that, no further updates can be initialized, though any pending
/// update can be finalized. All calls must set all three properties to
/// their desired value; leaving a value as 0, even if it was previously
/// set, will update that value to be 0. ETH-bond-only factory or the
/// strategy are allowed to be set as zero addresses.
/// @param _keepStakedFactory Address of the KEEP staked based factory.
/// @param _fullyBackedFactory Address of the ETH-bond-only-based factory.
/// @param _factorySelector Address of the keep factory selection strategy.
function beginKeepFactoriesUpdate(
address _keepStakedFactory,
address _fullyBackedFactory,
address _factorySelector
)
external onlyOwner
{
uint256 sinceInit = block.timestamp - initializedTimestamp;
require(
sinceInit < keepFactoriesUpgradeabilityPeriod,
"beginKeepFactoriesUpdate can only be called within 180 days of initialization"
);
// It is required that KEEP staked factory address is configured as this is
// a default choice factory. Fully backed factory and factory selector
// are optional for the system to work, hence they don't have to be provided.
require(
_keepStakedFactory != address(0),
"KEEP staked factory must be a nonzero address"
);
newKeepStakedFactory = _keepStakedFactory;
newFullyBackedFactory = _fullyBackedFactory;
newFactorySelector = _factorySelector;
keepFactoriesUpdateInitiated = block.timestamp;
emit KeepFactoriesUpdateStarted(
_keepStakedFactory,
_fullyBackedFactory,
_factorySelector,
block.timestamp
);
}
/// @notice Add a new ETH/BTC price feed contract to the priecFeed.
/// @dev This can be finalized by calling `finalizeEthBtcPriceFeedAddition`
/// anytime after `priceFeedGovernanceTimeDelay` has elapsed.
function beginEthBtcPriceFeedAddition(IMedianizer _ethBtcPriceFeed) external onlyOwner {
bool ethBtcActive;
(, ethBtcActive) = _ethBtcPriceFeed.peek();
require(ethBtcActive, "Cannot add inactive feed");
nextEthBtcPriceFeed = _ethBtcPriceFeed;
ethBtcPriceFeedAdditionInitiated = block.timestamp;
emit EthBtcPriceFeedAdditionStarted(address(_ethBtcPriceFeed), block.timestamp);
}
modifier onlyAfterGovernanceDelay(
uint256 _changeInitializedTimestamp,
uint256 _delay
) {
require(_changeInitializedTimestamp > 0, "Change not initiated");
require(
block.timestamp.sub(_changeInitializedTimestamp) >= _delay,
"Governance delay has not elapsed"
);
_;
}
/// @notice Finish setting the system signer fee divisor.
/// @dev `beginSignerFeeDivisorUpdate` must be called first, once `governanceTimeDelay`
/// has passed, this function can be called to set the signer fee divisor to the
/// value set in `beginSignerFeeDivisorUpdate`
function finalizeSignerFeeDivisorUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(signerFeeDivisorChangeInitiated, governanceTimeDelay)
{
signerFeeDivisor = newSignerFeeDivisor;
emit SignerFeeDivisorUpdated(newSignerFeeDivisor);
newSignerFeeDivisor = 0;
signerFeeDivisorChangeInitiated = 0;
}
/// @notice Finish setting the accepted system lot sizes.
/// @dev `beginLotSizesUpdate` must be called first, once `governanceTimeDelay`
/// has passed, this function can be called to set the lot sizes to the
/// value set in `beginLotSizesUpdate`
function finalizeLotSizesUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(lotSizesChangeInitiated, governanceTimeDelay) {
lotSizesSatoshis = newLotSizesSatoshis;
emit LotSizesUpdated(newLotSizesSatoshis);
lotSizesChangeInitiated = 0;
newLotSizesSatoshis.length = 0;
refreshMinimumBondableValue();
}
/// @notice Finish setting the system collateralization levels
/// @dev `beginCollateralizationThresholdsUpdate` must be called first, once `governanceTimeDelay`
/// has passed, this function can be called to set the collateralization thresholds to the
/// value set in `beginCollateralizationThresholdsUpdate`
function finalizeCollateralizationThresholdsUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
collateralizationThresholdsChangeInitiated,
governanceTimeDelay
) {
initialCollateralizedPercent = newInitialCollateralizedPercent;
undercollateralizedThresholdPercent = newUndercollateralizedThresholdPercent;
severelyUndercollateralizedThresholdPercent = newSeverelyUndercollateralizedThresholdPercent;
emit CollateralizationThresholdsUpdated(
newInitialCollateralizedPercent,
newUndercollateralizedThresholdPercent,
newSeverelyUndercollateralizedThresholdPercent
);
newInitialCollateralizedPercent = 0;
newUndercollateralizedThresholdPercent = 0;
newSeverelyUndercollateralizedThresholdPercent = 0;
collateralizationThresholdsChangeInitiated = 0;
}
/// @notice Finish setting addresses of the KEEP-staked ECDSA keep factory,
/// ETH-only-backed ECDSA keep factory, and the selection strategy
/// that will choose between the two factories for new deposits.
/// @dev `beginKeepFactoriesUpdate` must be called first; once
/// `governanceTimeDelay` has passed, this function can be called to
/// set factories addresses to the values set in `beginKeepFactoriesUpdate`.
function finalizeKeepFactoriesUpdate()
external
onlyOwner
onlyAfterGovernanceDelay(
keepFactoriesUpdateInitiated,
governanceTimeDelay
) {
keepFactorySelection.setFactories(
newKeepStakedFactory,
newFullyBackedFactory,
newFactorySelector
);
emit KeepFactoriesUpdated(
newKeepStakedFactory,
newFullyBackedFactory,
newFactorySelector
);
keepFactoriesUpdateInitiated = 0;
newKeepStakedFactory = address(0);
newFullyBackedFactory = address(0);
newFactorySelector = address(0);
}
/// @notice Finish adding a new price feed contract to the priceFeed.
/// @dev `beginEthBtcPriceFeedAddition` must be called first; once
/// `ethBtcPriceFeedAdditionInitiated` has passed, this function can be
/// called to append a new price feed.
function finalizeEthBtcPriceFeedAddition()
external
onlyOwner
onlyAfterGovernanceDelay(
ethBtcPriceFeedAdditionInitiated,
priceFeedGovernanceTimeDelay
) {
// This process interacts with external contracts, so
// Checks-Effects-Interactions it.
IMedianizer _nextEthBtcPriceFeed = nextEthBtcPriceFeed;
nextEthBtcPriceFeed = IMedianizer(0);
ethBtcPriceFeedAdditionInitiated = 0;
emit EthBtcPriceFeedAdded(address(_nextEthBtcPriceFeed));
priceFeed.addEthBtcFeed(_nextEthBtcPriceFeed);
}
/// @notice Gets the system signer fee divisor.
/// @return The signer fee divisor.
function getSignerFeeDivisor() external view returns (uint16) { return signerFeeDivisor; }
/// @notice Gets the allowed lot sizes
/// @return Uint64 array of allowed lot sizes
function getAllowedLotSizes() external view returns (uint64[] memory){
return lotSizesSatoshis;
}
/// @notice Get the system undercollateralization level for new deposits
function getUndercollateralizedThresholdPercent() external view returns (uint16) {
return undercollateralizedThresholdPercent;
}
/// @notice Get the system severe undercollateralization level for new deposits
function getSeverelyUndercollateralizedThresholdPercent() external view returns (uint16) {
return severelyUndercollateralizedThresholdPercent;
}
/// @notice Get the system initial collateralized level for new deposits.
function getInitialCollateralizedPercent() external view returns (uint16) {
return initialCollateralizedPercent;
}
/// @notice Get the price of one satoshi in wei.
/// @dev Reverts if the price of one satoshi is 0 wei, or if the price of
/// one satoshi is 1 ether. Can only be called by a deposit with minted
/// TDT.
/// @return The price of one satoshi in wei.
function fetchBitcoinPrice() external view returns (uint256) {
require(
tbtcDepositToken.exists(uint256(msg.sender)),
"Caller must be a Deposit contract"
);
return _fetchBitcoinPrice();
}
// Difficulty Oracle
function fetchRelayCurrentDifficulty() external view returns (uint256) {
return relay.getCurrentEpochDifficulty();
}
function fetchRelayPreviousDifficulty() external view returns (uint256) {
return relay.getPrevEpochDifficulty();
}
/// @notice Get the time remaining until the signer fee divisor can be updated.
function getRemainingSignerFeeDivisorUpdateTime() external view returns (uint256) {
return getRemainingChangeTime(
signerFeeDivisorChangeInitiated,
governanceTimeDelay
);
}
/// @notice Get the time remaining until the lot sizes can be updated.
function getRemainingLotSizesUpdateTime() external view returns (uint256) {
return getRemainingChangeTime(
lotSizesChangeInitiated,
governanceTimeDelay
);
}
/// @notice Get the time remaining until the collateralization thresholds can be updated.
function getRemainingCollateralizationThresholdsUpdateTime() external view returns (uint256) {
return getRemainingChangeTime(
collateralizationThresholdsChangeInitiated,
governanceTimeDelay
);
}
/// @notice Get the time remaining until the Keep ETH-only-backed ECDSA keep
/// factory and the selection strategy that will choose between it
/// and the KEEP-backed factory can be updated.
function getRemainingKeepFactoriesUpdateTime() external view returns (uint256) {
return getRemainingChangeTime(
keepFactoriesUpdateInitiated,
governanceTimeDelay
);
}
/// @notice Get the time remaining until the signer fee divisor can be updated.
function getRemainingEthBtcPriceFeedAdditionTime() external view returns (uint256) {
return getRemainingChangeTime(
ethBtcPriceFeedAdditionInitiated,
priceFeedGovernanceTimeDelay
);
}
/// @notice Get the time remaining until Keep factories can no longer be updated.
function getRemainingKeepFactoriesUpgradeabilityTime() external view returns (uint256) {
return getRemainingChangeTime(
initializedTimestamp,
keepFactoriesUpgradeabilityPeriod
);
}
/// @notice Refreshes the minimum bondable value required from the operator
/// to join the sortition pool for tBTC. The minimum bondable value is
/// equal to the current minimum lot size collateralized 150% multiplied by
/// the current BTC price.
/// @dev It is recommended to call this function on tBTC initialization and
/// after minimum lot size update.
function refreshMinimumBondableValue() public {
keepFactorySelection.setMinimumBondableValue(
calculateBondRequirementWei(getMinimumLotSize()),
keepSize,
keepThreshold
);
}
/// @notice Returns the time delay used for governance actions except for
/// price feed additions.
function getGovernanceTimeDelay() external pure returns (uint256) {
return governanceTimeDelay;
}
/// @notice Returns the time period when keep factories upgrades are allowed.
function getKeepFactoriesUpgradeabilityPeriod() public pure returns (uint256) {
return keepFactoriesUpgradeabilityPeriod;
}
/// @notice Returns the time delay used for price feed addition governance
/// actions.
function getPriceFeedGovernanceTimeDelay() external pure returns (uint256) {
return priceFeedGovernanceTimeDelay;
}
/// @notice Gets a fee estimate for creating a new Deposit.
/// @return Uint256 estimate.
function getNewDepositFeeEstimate()
external
view
returns (uint256)
{
IBondedECDSAKeepFactory _keepFactory = keepFactorySelection.selectFactory();
return _keepFactory.openKeepFeeEstimate();
}
/// @notice Request a new keep opening.
/// @param _requestedLotSizeSatoshis Lot size in satoshis.
/// @param _maxSecuredLifetime Duration of stake lock in seconds.
/// @return Address of a new keep.
function requestNewKeep(
uint64 _requestedLotSizeSatoshis,
uint256 _maxSecuredLifetime
)
external
payable
returns (address)
{
require(tbtcDepositToken.exists(uint256(msg.sender)), "Caller must be a Deposit contract");
require(isAllowedLotSize(_requestedLotSizeSatoshis), "provided lot size not supported");
IBondedECDSAKeepFactory _keepFactory = keepFactorySelection.selectFactoryAndRefresh();
uint256 bond = calculateBondRequirementWei(_requestedLotSizeSatoshis);
return _keepFactory.openKeep.value(msg.value)(keepSize, keepThreshold, msg.sender, bond, _maxSecuredLifetime);
}
/// @notice Check if a lot size is allowed.
/// @param _requestedLotSizeSatoshis Lot size to check.
/// @return True if lot size is allowed, false otherwise.
function isAllowedLotSize(uint64 _requestedLotSizeSatoshis) public view returns (bool){
for( uint i = 0; i < lotSizesSatoshis.length; i++){
if (lotSizesSatoshis[i] == _requestedLotSizeSatoshis){
return true;
}
}
return false;
}
/// @notice Calculates bond requirement in wei for the given lot size in
/// satoshis based on the current ETHBTC price.
/// @param _requestedLotSizeSatoshis Lot size in satoshis.
/// @return Bond requirement in wei.
function calculateBondRequirementWei(
uint256 _requestedLotSizeSatoshis
) internal view returns (uint256) {
uint256 lotSizeInWei = _fetchBitcoinPrice().mul(_requestedLotSizeSatoshis);
return lotSizeInWei.mul(initialCollateralizedPercent).div(100);
}
function _fetchBitcoinPrice() internal view returns (uint256) {
uint256 price = priceFeed.getPrice();
if (price == 0 || price > 10 ** 18) {
// This is if a sat is worth 0 wei, or is worth >1 ether. Revert at
// once.
revert("System returned a bad price");
}
return price;
}
/// @notice Get the time remaining until the function parameter timer value can be updated.
function getRemainingChangeTime(
uint256 _changeTimestamp,
uint256 _delayAmount
) internal view returns (uint256){
require(_changeTimestamp > 0, "Update not initiated");
uint256 elapsed = block.timestamp.sub(_changeTimestamp);
if (elapsed >= _delayAmount) {
return 0;
} else {
return _delayAmount.sub(elapsed);
}
}
}
|
Gets a fee estimate for creating a new Deposit. return Uint256 estimate.
|
function getNewDepositFeeEstimate()
external
view
returns (uint256)
{
IBondedECDSAKeepFactory _keepFactory = keepFactorySelection.selectFactory();
return _keepFactory.openKeepFeeEstimate();
}
| 1,057,859 |
./full_match/1/0x85d08e7Ec2FFf95A1c6C2EC8d5435cA048120930/sources/contracts/OTCExchangeNew.sol
|
Withdraws excess allowed tokens from the contract
|
function withdrawAllowedToken() external onlyOwner {
uint256 actualBalance = allowedToken.balanceOf(address(this));
uint256 excess = actualBalance - tokenBalance;
require(excess > 0, "No excess tokens to withdraw");
allowedToken.safeTransfer(msg.sender, excess);
}
| 3,130,429 |
pragma solidity ^0.5.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 "./uniswap/UniswapV2Factory.sol";
import "./PairTokenManager.sol";
/// @title zkSync main contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32 public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
//create pair
function createPair(address _tokenA, address _tokenB) external {
requireActive();
governance.requireTokenLister(msg.sender);
//check _tokenA is registered or not
uint16 tokenAID = governance.validateTokenAddress(_tokenA);
//check _tokenB is registered or not
uint16 tokenBID = governance.validateTokenAddress(_tokenB);
//make sure _tokenA is fee token
require(tokenAID <= MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "tokenA should be fee token");
//create pair
address pair = pairmanager.createPair(_tokenA, _tokenB);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
tokenAID,
_tokenA,
tokenBID,
_tokenB,
validatePairTokenAddress(pair),
pair
);
}
//create pair including ETH
function createETHPair(address _tokenERC20) external {
requireActive();
governance.requireTokenLister(msg.sender);
//check _tokenERC20 is registered or not
uint16 erc20ID = governance.validateTokenAddress(_tokenERC20);
//create pair
address pair = pairmanager.createPair(address(0), _tokenERC20);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
0,
address(0),
erc20ID,
_tokenERC20,
validatePairTokenAddress(pair),
pair
);
}
function registerCreatePair(uint16 _tokenAID, address _tokenA, uint16 _tokenBID, address _tokenB, uint16 _tokenPair, address _pair) internal {
// Priority Queue request
Operations.CreatePair memory op = Operations.CreatePair({
accountId : 0, //unknown at this point
tokenA : _tokenAID,
tokenB : _tokenBID,
tokenPair : _tokenPair,
pair : _pair
});
bytes memory pubData = Operations.writeCreatePairPubdata(op);
bytes memory userData = abi.encodePacked(
_tokenA, // tokenA address
_tokenB // tokenB address
);
addPriorityRequest(Operations.OpType.CreatePair, pubData, userData);
emit OnchainCreatePair(_tokenAID, _tokenBID, _tokenPair, _pair);
}
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
function upgradeNoticePeriodStarted() external {
}
/// @notice Notification that upgrade preparation status is activated
function upgradePreparationStarted() external {
upgradePreparationActive = true;
upgradePreparationActivationTime = now;
}
/// @notice Notification that upgrade canceled
function upgradeCanceled() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
function upgradeFinishes() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool) {
return !exodusMode;
}
constructor() public {
governance = Governance(msg.sender);
zkSyncCommitBlockAddress = address(this);
zkSyncExitAddress = address(this);
}
/// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _governanceAddress The address of Governance contract
/// _verifierAddress The address of Verifier contract
/// _ // FIXME: remove _genesisAccAddress
/// _genesisRoot Genesis blocks (first block) root
function initialize(bytes calldata initializationParameters) external {
require(address(governance) == address(0), "init0");
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
address _verifierExitAddress,
address _pairManagerAddress
) = abi.decode(initializationParameters, (address, address, address, address));
verifier = Verifier(_verifierAddress);
verifierExit = VerifierExit(_verifierExitAddress);
governance = Governance(_governanceAddress);
pairmanager = UniswapV2Factory(_pairManagerAddress);
maxDepositAmount = DEFAULT_MAX_DEPOSIT_AMOUNT;
withdrawGasLimit = ERC20_WITHDRAWAL_GAS_LIMIT;
}
function setGenesisRootAndAddresses(bytes32 _genesisRoot, address _zkSyncCommitBlockAddress, address _zkSyncExitAddress) external {
// This function cannot be called twice as long as
// _zkSyncCommitBlockAddress and _zkSyncExitAddress have been set to
// non-zero.
require(zkSyncCommitBlockAddress == address(0), "sraa1");
require(zkSyncExitAddress == address(0), "sraa2");
blocks[0].stateRoot = _genesisRoot;
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
zkSyncExitAddress = _zkSyncExitAddress;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Sends tokens
/// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount
/// @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 withdrawERC20Guarded(IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount) external returns (uint128 withdrawnAmount) {
require(msg.sender == address(this), "wtg10");
// wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed)
uint16 lpTokenId = tokenIds[address(_token)];
uint256 balance_before = _token.balanceOf(address(this));
if (lpTokenId > 0) {
validatePairTokenAddress(address(_token));
pairmanager.mint(address(_token), _to, _amount);
} else {
require(Utils.sendERC20(_token, _to, _amount), "wtg11");
// wtg11 - ERC20 transfer fails
}
uint256 balance_after = _token.balanceOf(address(this));
uint256 balance_diff = balance_before.sub(balance_after);
require(balance_diff <= _maxAmount, "wtg12");
// wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount
return SafeCast.toUint128(balance_diff);
}
/// @notice executes pending withdrawals
/// @param _n The number of withdrawals to complete starting from oldest
function completeWithdrawals(uint32 _n) external nonReentrant {
// TODO: when switched to multi validators model we need to add incentive mechanism to call complete.
uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals);
uint32 startIndex = firstPendingWithdrawalIndex;
numberOfPendingWithdrawals -= toProcess;
firstPendingWithdrawalIndex += toProcess;
for (uint32 i = startIndex; i < startIndex + toProcess; ++i) {
uint16 tokenId = pendingWithdrawals[i].tokenId;
address to = pendingWithdrawals[i].to;
// send fails are ignored hence there is always a direct way to withdraw.
delete pendingWithdrawals[i];
bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId);
uint128 amount = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
// amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20
if (amount != 0) {
balancesToWithdraw[packedBalanceKey].balanceToWithdraw -= amount;
bool sent = false;
if (tokenId == 0) {
address payable toPayable = address(uint160(to));
sent = Utils.sendETHNoRevert(toPayable, amount);
} else {
address tokenAddr = address(0);
if (tokenId < PAIR_TOKEN_START_ID) {
// It is normal ERC20
tokenAddr = governance.tokenAddresses(tokenId);
} else {
// It is pair token
tokenAddr = tokenAddresses[tokenId];
}
// tokenAddr cannot be 0
require(tokenAddr != address(0), "cwt0");
// we can just check that call not reverts because it wants to withdraw all amount
(sent,) = address(this).call.gas(withdrawGasLimit)(
abi.encodeWithSignature("withdrawERC20Guarded(address,address,uint128,uint128)", tokenAddr, to, amount, amount)
);
}
if (!sent) {
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += amount;
}
}
}
if (toProcess > 0) {
emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess);
}
}
/// @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) external nonReentrant {
require(exodusMode, "coe01");
// exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "coe02");
// no deposits to process
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
Operations.Deposit memory op = Operations.readDepositPubdata(priorityRequests[id].pubData);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId);
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
/// @param _franklinAddr The receiver Layer 2 address
function depositETH(address _franklinAddr) external payable nonReentrant {
requireActive();
registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr);
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender
/// @param _amount Ether amount to withdraw
function withdrawETH(uint128 _amount) external nonReentrant {
registerWithdrawal(0, _amount, msg.sender);
(bool success,) = msg.sender.call.value(_amount)("");
require(success, "fwe11");
// ETH withdraw failed
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to _to address
/// @param _amount Ether amount to withdraw
function withdrawETHWithAddress(uint128 _amount, address payable _to) external nonReentrant {
require(_to != address(0), "ipa11");
registerWithdrawal(0, _amount, _to);
(bool success,) = _to.call.value(_amount)("");
require(success, "fwe12");
// ETH withdraw failed
}
/// @notice Config amount limit for each ERC20 deposit
/// @param _amount Max deposit amount
function setMaxDepositAmount(uint128 _amount) external {
governance.requireGovernor(msg.sender);
maxDepositAmount = _amount;
}
/// @notice Config gas limit for withdraw erc20 token
/// @param _gasLimit withdraw erc20 gas limit
function setWithDrawGasLimit(uint256 _gasLimit) external {
governance.requireGovernor(msg.sender);
withdrawGasLimit = _gasLimit;
}
/// @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 _franklinAddr Receiver Layer 2 address
function depositERC20(IERC20 _token, uint104 _amount, address _franklinAddr) external nonReentrant {
requireActive();
// Get token id by its address
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
lpTokenId = validatePairTokenAddress(address(_token));
}
uint256 balance_before = 0;
uint256 balance_after = 0;
uint128 deposit_amount = 0;
if (lpTokenId > 0) {
// Note: For lp token, main contract always has no money
balance_before = _token.balanceOf(msg.sender);
pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount));
balance_after = _token.balanceOf(msg.sender);
deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after));
require(deposit_amount <= maxDepositAmount, "fd011");
registerDeposit(lpTokenId, deposit_amount, _franklinAddr);
} else {
balance_before = _token.balanceOf(address(this));
require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012");
// token transfer failed deposit
balance_after = _token.balanceOf(address(this));
deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before));
require(deposit_amount <= maxDepositAmount, "fd013");
registerDeposit(tokenId, deposit_amount, _franklinAddr);
}
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender
/// @param _token Token address
/// @param _amount amount to withdraw
function withdrawERC20(IERC20 _token, uint128 _amount) external nonReentrant {
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
tokenId = validatePairTokenAddress(address(_token));
}
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, msg.sender, _amount, balance);
registerWithdrawal(tokenId, withdrawnAmount, msg.sender);
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to _to address
/// @param _token Token address
/// @param _amount amount to withdraw
/// @param _to address to withdraw
function withdrawERC20WithAddress(IERC20 _token, uint128 _amount, address payable _to) external nonReentrant {
require(_to != address(0), "ipa12");
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
tokenId = validatePairTokenAddress(address(_token));
}
bytes22 packedBalanceKey = packAddressAndTokenId(_to, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, _to, _amount, balance);
registerWithdrawal(tokenId, withdrawnAmount, _to);
}
/// @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 fullExit(uint32 _accountId, address _token) external nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "fee11");
uint16 tokenId;
if (_token == address(0)) {
tokenId = 0;
} else {
tokenId = governance.validateTokenAddress(_token);
require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "fee12");
}
// Priority Queue request
Operations.FullExit memory op = Operations.FullExit({
accountId : _accountId,
owner : msg.sender,
tokenId : tokenId,
amount : 0 // unknown at this point
});
bytes memory pubData = Operations.writeFullExitPubdata(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);
balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff;
}
/// @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.writeDepositPubdata(op);
addPriorityRequest(Operations.OpType.Deposit, pubData, "");
emit OnchainDeposit(
msg.sender,
_tokenId,
_amount,
_owner
);
}
/// @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 = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(_amount);
emit OnchainWithdrawal(
_to,
_token,
_amount
);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "fre11");
// exodus mode activated
}
// 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,
bytes memory _userData
) internal {
// Expiration block is: current block number + priority expiration delta
uint256 expirationBlock = block.number + PRIORITY_EXPIRATION;
uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests;
priorityRequests[nextPriorityRequestId] = PriorityOperation({
opType : _opType,
pubData : _pubData,
expirationBlock : expirationBlock
});
emit NewPriorityRequest(
msg.sender,
nextPriorityRequestId,
_opType,
_pubData,
_userData,
expirationBlock
);
totalOpenPriorityRequests++;
}
// The contract is too large. Break some functions to zkSyncCommitBlockAddress
function() external payable {
address nextAddress = zkSyncCommitBlockAddress;
require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set");
// Execute external function from facet using delegatecall and return any value.
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
/// Address of lock flag variable.
/// Flag is placed at random memory location to not interfere with Storage contract.
uint constant private LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
function initializeReentrancyGuard () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
assembly { sstore(LOCK_FLAG_ADDRESS, 1) }
}
/**
* @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() {
bool notEntered;
assembly { notEntered := sload(LOCK_FLAG_ADDRESS) }
// On the first call to nonReentrant, _notEntered will be true
require(notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
assembly { sstore(LOCK_FLAG_ADDRESS, 0) }
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly { sstore(LOCK_FLAG_ADDRESS, 1) }
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library 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, "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(uint128 a, uint128 b) internal pure returns (uint128) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(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, "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(uint128 a, uint128 b) internal pure returns (uint128) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(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, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.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, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
}
pragma solidity ^0.5.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 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) {
// TODO: Use constant from Config
uint256 ETH_WITHDRAWAL_GAS_LIMIT = 10000;
(bool callSuccess, ) = _to.call.gas(ETH_WITHDRAWAL_GAS_LIMIT).value(_amount)("");
return callSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _message signed message.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes memory _message) internal pure returns (address) {
require(_signature.length == 65, "ves10"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint offset = 0;
(offset, signR) = Bytes.readBytes32(_signature, offset);
(offset, signS) = Bytes.readBytes32(_signature, offset);
uint8 signV = uint8(_signature[offset]);
return ecrecover(keccak256(_message), signV, signR, signS);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Governance.sol";
import "./Verifier.sol";
import "./VerifierExit.sol";
import "./Operations.sol";
import "./uniswap/UniswapV2Factory.sol";
/// @title ZKSwap storage contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Storage {
/// @notice Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool public upgradePreparationActive;
/// @notice Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint public upgradePreparationActivationTime;
/// @notice Verifier contract. Used to verify block proof and exit proof
Verifier internal verifier;
VerifierExit internal verifierExit;
/// @notice Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance internal governance;
UniswapV2Factory internal pairmanager;
struct BalanceToWithdraw {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @notice Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => BalanceToWithdraw) public balancesToWithdraw;
/// @notice verified withdrawal pending to be executed.
struct PendingWithdrawal {
address to;
uint16 tokenId;
}
/// @notice Verified but not executed withdrawals for addresses stored in here (key is pendingWithdrawal's index in pending withdrawals queue)
mapping(uint32 => PendingWithdrawal) public pendingWithdrawals;
uint32 public firstPendingWithdrawalIndex;
uint32 public numberOfPendingWithdrawals;
/// @notice Total number of verified blocks i.e. blocks[totalBlocksVerified] points at the latest verified block (block 0 is genesis)
uint32 public totalBlocksVerified;
/// @notice Total number of checked blocks
uint32 public totalBlocksChecked;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Rollup block data (once per block)
/// @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 Block {
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;
}
/// @notice Blocks by Franklin block id
mapping(uint32 => Block) public blocks;
/// @notice Onchain operations - operations processed inside rollup blocks
/// @member opType Onchain operation type
/// @member amount Amount used in the operation
/// @member pubData Operation pubdata
struct OnchainOperation {
Operations.OpType opType;
bytes pubData;
}
/// @notice Flag indicates that a user has exited certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public exited;
mapping(uint32 => mapping(uint32 => bool)) public swap_exited;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice User authenticated fact hashes for some nonce.
mapping(address => mapping(uint32 => bytes32)) public authFacts;
/// @notice 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 PriorityOperation {
Operations.OpType opType;
bytes pubData;
uint256 expirationBlock;
}
/// @notice 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) public priorityRequests;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice 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 public 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)));
}
/// @notice Gets value from balancesToWithdraw
function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) {
return balancesToWithdraw[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
address public zkSyncCommitBlockAddress;
address public zkSyncExitAddress;
/// @notice Limit the max amount for each ERC20 deposit
uint128 public maxDepositAmount;
/// @notice withdraw erc20 token gas limit
uint256 public withdrawGasLimit;
}
pragma solidity ^0.5.0;
/// @title ZKSwap configuration constants
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Config {
/// @notice ERC20 token withdrawal gas limit, used only for complete withdrawals
uint256 constant ERC20_WITHDRAWAL_GAS_LIMIT = 350000;
/// @notice ETH token withdrawal gas limit, used only for complete withdrawals
uint256 constant ETH_WITHDRAWAL_GAS_LIMIT = 10000;
/// @notice Bytes in one chunk
uint8 constant CHUNK_BYTES = 11;
/// @notice ZKSwap address length
uint8 constant ADDRESS_BYTES = 20;
uint8 constant PUBKEY_HASH_BYTES = 20;
/// @notice Public key bytes length
uint8 constant PUBKEY_BYTES = 32;
/// @notice Ethereum signature r/s bytes length
uint8 constant ETH_SIGN_RS_BYTES = 32;
/// @notice Success flag bytes length
uint8 constant SUCCESS_FLAG_BYTES = 1;
/// @notice Max amount of fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 constant MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS = 32 - 1;
/// @notice start ID for user tokens
uint16 constant USER_TOKENS_START_ID = 32;
/// @notice Max amount of user tokens registered in the network
uint16 constant MAX_AMOUNT_OF_REGISTERED_USER_TOKENS = 16352;
/// @notice Max amount of tokens registered in the network
uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 16384 - 1;
/// @notice Max account id that could be registered in the network
uint32 constant MAX_ACCOUNT_ID = (2 ** 28) - 1;
/// @notice Expected average period of block creation
uint256 constant BLOCK_PERIOD = 15 seconds;
/// @notice ETH blocks verification expectation
/// Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// If set to 0 validator can revert blocks at any time.
uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 constant CREATE_PAIR_BYTES = 3 * CHUNK_BYTES;
uint256 constant DEPOSIT_BYTES = 4 * CHUNK_BYTES;
uint256 constant TRANSFER_TO_NEW_BYTES = 4 * CHUNK_BYTES;
uint256 constant PARTIAL_EXIT_BYTES = 5 * CHUNK_BYTES;
uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 constant UNISWAP_ADD_LIQ_BYTES = 3 * CHUNK_BYTES;
uint256 constant UNISWAP_RM_LIQ_BYTES = 3 * CHUNK_BYTES;
uint256 constant UNISWAP_SWAP_BYTES = 2 * CHUNK_BYTES;
/// @notice Full exit operation length
uint256 constant FULL_EXIT_BYTES = 4 * CHUNK_BYTES;
/// @notice OnchainWithdrawal data length
uint256 constant ONCHAIN_WITHDRAWAL_BYTES = 1 + 20 + 2 + 16; // (uint8 addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount)
/// @notice ChangePubKey operation length
uint256 constant CHANGE_PUBKEY_BYTES = 5 * CHUNK_BYTES;
/// @notice Expiration delta for priority request to be satisfied (in seconds)
/// NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD), otherwise incorrect block with priority op could not be reverted.
uint256 constant PRIORITY_EXPIRATION_PERIOD = 3 days;
/// @notice Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD;
/// @notice 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 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @notice Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint constant MASS_FULL_EXIT_PERIOD = 3 days;
/// @notice Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @notice Notice period before activation preparation status of upgrade mode (in seconds)
// 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.
uint constant UPGRADE_NOTICE_PERIOD = MASS_FULL_EXIT_PERIOD + PRIORITY_EXPIRATION_PERIOD + TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT;
// @notice Default amount limit for each ERC20 deposit
uint128 constant DEFAULT_MAX_DEPOSIT_AMOUNT = 2 ** 85;
}
pragma solidity ^0.5.0;
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title ZKSwap events
/// @author Matter Labs
/// @author ZKSwap L2 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 a sequence of blocks is verified
event MultiblockVerification(uint32 indexed blockNumberFrom, uint32 indexed blockNumberTo);
/// @notice Event emitted when user send a transaction to withdraw her funds from onchain balance
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @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 indexed totalBlocksVerified,
uint32 indexed 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,
bytes userData,
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 Pending withdrawals index range that were added in the verifyBlock operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsAdd(
uint32 queueStartIndex,
uint32 queueEndIndex
);
/// @notice Pending withdrawals index range that were executed in the completeWithdrawals operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsComplete(
uint32 queueStartIndex,
uint32 queueEndIndex
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
}
/// @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(
uint indexed versionId,
address indexed upgradeable
);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint indexed versionId,
address[] newTargets,
uint noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(
uint indexed versionId
);
/// @notice Upgrade mode preparation status event
event PreparationStart(
uint indexed versionId
);
/// @notice Upgrade mode complete event
event UpgradeComplete(
uint indexed versionId,
address[] newTargets
);
}
pragma solidity ^0.5.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(uint(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(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(uint self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "bt211");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint data = self << ((32 - byteLength) * 8);
assembly {
mstore(add(bts, /*BYTES_HEADER_SIZE*/32), 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(uint(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, "bta11");
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), "btb20");
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, "btu02");
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, "btu03");
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, "btu04");
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, "btu16");
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, "btu20");
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, "btb32");
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,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length), "bse11"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
// TODO: Review this thoroughly.
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 new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(bytes memory _data, uint _offset, uint _length) internal pure returns (uint new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint _offset) internal pure returns (uint new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
// Helper function for hex conversion.
function halfByteToHex(byte _byte) internal pure returns (byte _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return byte (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;
}
/// Trim bytes into single word
function trim(bytes memory _data, uint _new_length) internal pure returns (uint r) {
require(_new_length <= 0x20, "trm10"); // new_length is longer than word
require(_data.length >= _new_length, "trm11"); // data is to short
uint a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
}
pragma solidity ^0.5.0;
import "./Bytes.sol";
/// @title ZKSwap operations tools
library Operations {
// Circuit ops and their pubdata (chunks * bytes)
/// @notice ZKSwap circuit operation type
enum OpType {
Noop,
Deposit,
TransferToNew,
PartialExit,
_CloseAccount, // used for correct op id offset
Transfer,
FullExit,
ChangePubKey,
CreatePair,
AddLiquidity,
RemoveLiquidity,
Swap
}
// Byte lengths
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @notice Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @notice ZKSwap account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @notice Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
}
uint public constant PACKED_DEPOSIT_PUBDATA_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.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_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, "rdp10"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
function writeDepositPubdata(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner // owner
);
}
/// @notice Check that deposit pubdata from request and block matches
function depositPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
// FullExit pubdata
struct FullExit {
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
}
uint public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_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.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "rfp10"); // reading invalid full exit pubdata size
}
function writeFullExitPubdata(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
/// @notice Check that full exit pubdata from request and block matches
function fullExitPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// `amount` is ignored because it is present in block pubdata but not in priority queue
uint lhs = Bytes.trim(_lhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
uint rhs = Bytes.trim(_rhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
return lhs == rhs;
}
// PartialExit pubdata
struct PartialExit {
//uint32 accountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
}
function readPartialExitPubdata(bytes memory _data, uint _offset) 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.
uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
}
function writePartialExitPubdata(PartialExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
// ChangePubKey
struct ChangePubKey {
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
}
function readChangePubKeyPubdata(bytes memory _data, uint _offset) internal pure
returns (ChangePubKey memory parsed)
{
uint offset = _offset;
(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
}
// Withdrawal data process
function readWithdrawalData(bytes memory _data, uint _offset) internal pure
returns (bool _addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount)
{
uint offset = _offset;
(offset, _addToPendingWithdrawalsQueue) = Bytes.readBool(_data, offset);
(offset, _to) = Bytes.readAddress(_data, offset);
(offset, _tokenId) = Bytes.readUInt16(_data, offset);
(offset, _amount) = Bytes.readUInt128(_data, offset);
}
// CreatePair pubdata
struct CreatePair {
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
uint public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
function readCreatePairPubdata(bytes memory _data) internal pure
returns (CreatePair memory parsed)
{
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
/// @notice Check that create pair pubdata from request and block matches
function createPairPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint);
/// @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.5.16;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract UniswapV2Factory is IUniswapV2Factory {
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
address public zkSyncAddress;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor() public {
}
function initialize(bytes calldata data) external {
}
function setZkSyncAddress(address _zksyncAddress) external {
require(zkSyncAddress == address(0), "szsa1");
zkSyncAddress = _zksyncAddress;
}
/// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp1');
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
//require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(zkSyncAddress != address(0), 'wzk');
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function mint(address pair, address to, uint amount) external {
require(msg.sender == zkSyncAddress, 'fmt1');
IUniswapV2Pair(pair).mint(to, amount);
}
function burn(address pair, address to, uint amount) external {
require(msg.sender == zkSyncAddress, 'fbr1');
IUniswapV2Pair(pair).burn(to, amount);
}
}
pragma solidity ^0.5.0;
contract PairTokenManager {
/// @notice Max amount of pair tokens registered in the network.
uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 49152;
uint16 constant PAIR_TOKEN_START_ID = 16384;
/// @notice Total number of pair tokens registered in the network
uint16 public totalPairTokens;
/// @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 Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
function addPairToken(address _token) internal {
require(tokenIds[_token] == 0, "pan1"); // token exists
require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens
uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens;
totalPairTokens++;
tokenAddresses[newPairTokenId] = _token;
tokenIds[_token] = newPairTokenId;
emit NewToken(_token, newPairTokenId);
}
/// @notice Validate pair token address
/// @param _tokenAddr Token address
/// @return tokens id
function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "pms3");
require(tokenId <= (PAIR_TOKEN_START_ID -1 + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4");
return tokenId;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./Config.sol";
/// @title Governance Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
/// @notice Governor changed
event NewGovernor(
address newGovernor
);
/// @notice tokenLister changed
event NewTokenLister(
address newTokenLister
);
/// @notice Validator's status changed
event ValidatorStatusUpdate(
address indexed validatorAddress,
bool isActive
);
/// @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 fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalFeeTokens;
/// @notice Total number of ERC20 user tokens registered in the network
uint16 public totalUserTokens;
/// @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;
address public tokenLister;
constructor() public {
networkGovernor = msg.sender;
}
/// @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 {
require(networkGovernor == address(0), "init0");
(address _networkGovernor, address _tokenLister) = abi.decode(initializationParameters, (address, address));
networkGovernor = _networkGovernor;
tokenLister = _tokenLister;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
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);
require(_newGovernor != address(0), "zero address is passed as _newGovernor");
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Change current governor
/// @param _newTokenLister Address of the new governor
function changeTokenLister(address _newTokenLister) external {
requireGovernor(msg.sender);
require(_newTokenLister != address(0), "zero address is passed as _newTokenLister");
if (tokenLister != _newTokenLister) {
tokenLister = _newTokenLister;
emit NewTokenLister(_newTokenLister);
}
}
/// @notice Add fee token to the list of networks tokens
/// @param _token Token address
function addFeeToken(address _token) external {
requireGovernor(msg.sender);
require(tokenIds[_token] == 0, "gan11"); // token exists
require(totalFeeTokens < MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "fee12"); // no free identifiers for tokens
require(
_token != address(0), "address cannot be zero"
);
totalFeeTokens++;
uint16 newTokenId = totalFeeTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
requireTokenLister(msg.sender);
require(tokenIds[_token] == 0, "gan11"); // token exists
require(totalUserTokens < MAX_AMOUNT_OF_REGISTERED_USER_TOKENS, "gan12"); // no free identifiers for tokens
require(
_token != address(0), "address cannot be zero"
);
uint16 newTokenId = USER_TOKENS_START_ID + totalUserTokens;
totalUserTokens++;
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @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, "grr11"); // only by governor
}
/// @notice Check if specified address can list token
/// @param _address Address to check
function requireTokenLister(address _address) public view {
require(_address == networkGovernor || _address == tokenLister, "grr11"); // token lister or governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "grr21"); // 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 <= totalFeeTokens) || (_tokenId >= USER_TOKENS_START_ID && _tokenId < (USER_TOKENS_START_ID + totalUserTokens ));
}
/// @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, "gvs11"); // 0 is not a valid token
require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "gvs12");
return tokenId;
}
function getTokenAddress(uint16 _tokenId) external view returns (address) {
address tokenAddr = tokenAddresses[_tokenId];
return tokenAddr;
}
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./KeysWithPlonkAggVerifier.sol";
// Hardcoded constants to avoid accessing store
contract Verifier is KeysWithPlonkAggVerifier {
bool constant DUMMY_VERIFIER = false;
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
function upgrade(bytes calldata upgradeParameters) external {}
function isBlockSizeSupported(uint32 _size) public pure returns (bool) {
if (DUMMY_VERIFIER) {
return true;
} else {
return isBlockSizeSupportedInternal(_size);
}
}
function verifyMultiblockProof(
uint256[] calldata _recursiveInput,
uint256[] calldata _proof,
uint32[] calldata _block_sizes,
uint256[] calldata _individual_vks_inputs,
uint256[] calldata _subproofs_limbs
) external view returns (bool) {
if (DUMMY_VERIFIER) {
uint oldGasValue = gasleft();
uint tmp;
while (gasleft() + 500000 > oldGasValue) {
tmp += 1;
}
return true;
}
uint8[] memory vkIndexes = new uint8[](_block_sizes.length);
for (uint32 i = 0; i < _block_sizes.length; i++) {
vkIndexes[i] = blockSizeToVkIndex(_block_sizes[i]);
}
VerificationKey memory vk = getVkAggregated(uint32(_block_sizes.length));
return verify_serialized_proof_with_recursion(_recursiveInput, _proof, VK_TREE_ROOT, VK_MAX_INDEX, vkIndexes, _individual_vks_inputs, _subproofs_limbs, vk);
}
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./KeysWithPlonkSingleVerifier.sol";
// Hardcoded constants to avoid accessing store
contract VerifierExit is KeysWithPlonkSingleVerifier {
function initialize(bytes calldata) external {
}
/// @notice VerifierExit contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyExitProof(
bytes32 _rootHash,
uint32 _accountId,
address _owner,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external view returns (bool) {
bytes32 commitment = sha256(abi.encodePacked(_rootHash, _accountId, _owner, _tokenId, _amount));
uint256[] memory inputs = new uint256[](1);
uint256 mask = (~uint256(0)) >> 3;
inputs[0] = uint256(commitment) & mask;
Proof memory proof = deserialize_proof(inputs, _proof);
VerificationKey memory vk = getVkExit();
require(vk.num_inputs == inputs.length);
return verify(proof, vk);
}
function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
for (uint i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (uint i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
function verifyLpExitProof(
bytes calldata _account_data,
bytes calldata _pair_data0,
bytes calldata _pair_data1,
uint256[] calldata _proof
) external view returns (bool) {
bytes memory _data1 = concatBytes(_account_data, _pair_data0);
bytes memory _data2 = concatBytes(_data1, _pair_data1);
bytes32 commitment = sha256(_data2);
uint256[] memory inputs = new uint256[](1);
uint256 mask = (~uint256(0)) >> 3;
inputs[0] = uint256(commitment) & mask;
Proof memory proof = deserialize_proof(inputs, _proof);
VerificationKey memory vk = getVkLpExit();
require(vk.num_inputs == inputs.length);
return verify(proof, vk);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable contract
/// @author Matter Labs
/// @author ZKSwap L2 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.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
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);
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IUNISWAPERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using UniswapSafeMath for uint;
using UQ112x112 for uint224;
address public factory;
address public token0;
address public token1;
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
function mint(address to, uint amount) external lock {
require(msg.sender == factory, 'mt1');
_mint(to, amount);
}
function burn(address to, uint amount) external lock {
require(msg.sender == factory, 'br1');
_burn(to, amount);
}
}
pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PlonkAggCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkAggVerifier is AggVerifierWithDeserialize {
uint256 constant VK_TREE_ROOT = 0x0a3cdc9655e61bf64758c1e8df745723e9b83addd4f0d0f2dd65dc762dc1e9e7;
uint8 constant VK_MAX_INDEX = 5;
function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) {
if (_size == uint32(6)) { return true; }
else if (_size == uint32(12)) { return true; }
else if (_size == uint32(48)) { return true; }
else if (_size == uint32(96)) { return true; }
else if (_size == uint32(204)) { return true; }
else if (_size == uint32(420)) { return true; }
else { return false; }
}
function blockSizeToVkIndex(uint32 _chunks) internal pure returns (uint8) {
if (_chunks == uint32(6)) { return 0; }
else if (_chunks == uint32(12)) { return 1; }
else if (_chunks == uint32(48)) { return 2; }
else if (_chunks == uint32(96)) { return 3; }
else if (_chunks == uint32(204)) { return 4; }
else if (_chunks == uint32(420)) { return 5; }
}
function getVkAggregated(uint32 _blocks) internal pure returns (VerificationKey memory vk) {
if (_blocks == uint32(1)) { return getVkAggregated1(); }
else if (_blocks == uint32(5)) { return getVkAggregated5(); }
}
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 getVkAggregated5() 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(
0x023cfc69ef1b002da66120fce352ede75893edd8cd8196403a54e1eceb82cd43,
0x2baf3bd673e46be9df0d43ca30f834671543c22db422f450b2efd8c931e9b34e
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x23783fe0e5c3f83c02c864e25fe766afb727134c9a77ae6b9694efb7b46f31ab,
0x1903d01005e447d061c16323a1d604d8fbd4b5cc9b64945a71f1234d280c4d3a
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x2897df6c6fa993661b2b0b0cf52460278e33533de71b3c0f7ed7c1f20af238c6,
0x042344afee0aed5505e59bce4ebbe942a91268a8af6b77ea95f603b5b726e8cb
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x0fceed33e78426afc38d8a68c0d93413d2bbaa492b087125271d33d52bdb07b8,
0x0057e4f63be36edb56e91da931f3d0ba72d1862d4b7751c59b92b6ae9f1fcc11
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x14230a35f172cd77a2147cecc20b2a13148363cbab78709489a29d08001e26fb,
0x04f1040477d77896475080b5abb8091cda2cce4917ee0ba5dd62d0ab1be379b4
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x20d1a079ad80a8abb7fd8ba669dddbbe23231360a5f0ba679b6536b6bf980649,
0x120c5a845903bd6de4105eb8cef90e6dff2c3888ada16c90e1efb393778d6a4d
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x1af6b9e362e458a96b8bbbf8f8ce2bdbd650fb68478360c408a2acf1633c1ce1,
0x27033728b767b44c659e7896a6fcc956af97566a5a1135f87a2e510976a62d41
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x0dbfb3c5f5131eb6f01e12b1a6333b0ad22cc8292b666e46e9bd4d80802cccdf,
0x2d058711c42fd2fd2eef33fb327d111a27fe2063b46e1bb54b32d02e9676e546
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x0c8c7352a84dd3f32412b1a96acd94548a292411fd7479d8609ca9bd872f1e36,
0x0874203fd8012d6976698cc2df47bca14bc04879368ade6412a2109c1e71e5e8
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1b17bb7c319b1cf15461f4f0b69d98e15222320cb2d22f4e3a5f5e0e9e51f4bd,
0x0cf5bc338235ded905926006027aa2aab277bc32a098cd5b5353f5545cbd2825
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x0794d3cfbc2fdd756b162571a40e40b8f31e705c77063f30a4e9155dbc00e0ef,
0x1f821232ab8826ea5bf53fe9866c74e88a218c8d163afcaa395eda4db57b7a23
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x224d93783aa6856621a9bbec495f4830c94994e266b240db9d652dbb394a283b,
0x161bcec99f3bc449d655c0ca59874dafe1194138eec91af34392b09a83338ca1
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x1fa27e2916b2c11d39c74c0e61063190da31c102d2b7da5c0a61ec8c5e82f132,
0x0a815ee76cd8aa600e6f66463b25a0ee57814bfdf06c65a91ddc70cede41caae
);
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]
);
}
}
pragma solidity >=0.5.0 <0.7.0;
import "./PlonkSingleCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkSingleVerifier is SingleVerifierWithDeserialize {
function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) {
if (_size == uint32(6)) { return true; }
else if (_size == uint32(12)) { return true; }
else if (_size == uint32(48)) { return true; }
else if (_size == uint32(96)) { return true; }
else if (_size == uint32(204)) { return true; }
else if (_size == uint32(420)) { return true; }
else { return false; }
}
function getVkExit() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x1abc710835cdc78389d61b670b0e8d26416a63c9bd3d6ed435103ebbb8a8665e,
0x138c6678230ed19f90b947d0a9027bd9fc458bbd1d2b8371fa72e28470a97b9c
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x28d81ac76e1ddf630b4bf8e4a789cf9c4470c5e5cc010a24849b20ab595b8b22,
0x251ca3cf0829b261d3be8d6cbd25aa97d9af716819c29f6319d806f075e79655
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x1504c8c227833a1152f3312d258412c334ac7ae213e21427ff63028729bc28fa,
0x0f0942f3fede795cbe624fb9ddf9be90ba546609383f2246c3c9b92af7aab5fd
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x1f14a5bb19ea2897ac6b9fbdbd2b4e371be09f8e90a47ae26602d399c9bcd311,
0x029c6ea094247da75d9a66cea627c3c77d48b898003125d4f8e785435dc2cf23
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x102cdd83e2d70638a70d700622b662607f8a2d92f5c36053a4ddb4b600d75bcf,
0x09ef3679579d761507ef69eaf49c978b271f0e4500468da1ebd7197f3ff5d6ac
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x2c2bd1d2fa3d4b3915d0fe465469e11ee563e79751da71c6082fcd0ca4e41cd5,
0x0304f16147a8af177dcc703370931d5161bda9dcf3e091787b9a54377ab54c32
);
// 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(
0x14420680f992f4bc8d8012e2d8b14a774cf9114adf1e41b3c02c20cc1648398e,
0x237d3d5cdee5e3d7d58f4eb336ecd7aa5ec88d89205861b410420f6b9f6b26a1
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x221045ae5578ccb35e0a198d83c0fb191da8cdc98423fc46e580f1762682c73e,
0x15b7f3d74fcd258fdd2ae6001693a7c615e654d613a506d213aaf0ad314e338d
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x03e47981b459b3be258a6353593898babec571ccf3e0362d53a67f078f04830a,
0x0809556ab6eb28403bb5a749fcdbd8656940add7685ff5473dc3a9ad940034df
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x2c02322c53d7e6a6474b15c7db738419e3f4d1263e9f98ebb56c24906f555ef9,
0x2322c69f51366551665b584d797e0fdadb16fe31b1e7ae2f532847a75b3aeaab
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x2147e39b49c2bef4168884c0ac9e38bb4dc65b41ba21953f7ded2daab7fe1534,
0x071f3548c9ca2c6a8d10b11d553263ebe0afaf1f663b927ef970bd6c3974cb68
);
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]
);
}
function getVkLpExit() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 524288;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0cf1526aaafac6bacbb67d11a4077806b123f767e4b0883d14cc0193568fc082);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x067d967299b3d380f2e461409fbacb82d9af8c85b62de082a423f344fb0b9d38,
0x2440bd569ac24e9525b29e433334ee98d72cb8eb19af65250ee0099fb470d873
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x086a9ed0f6175964593e516a8c1fc8bbd0a9c8afb724ebbce08a7772bd7b8837,
0x0aca3794dc6a2f0cab69dfed529d31deb7a5e9e6c339e3c07d8d88df0f7abd6b
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x00b6bfec3aceb55618e6caf637c978c3fe2344568c64515022fcfa00e490eb97,
0x0f890fe6b9cb943fb4887df1529cdae99e2494eabf675f89905215eb51c29c6e
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x0968470be841bcbfbcccc10dd0d8b63a871cdb3289c214fc59f38c88ab15146a,
0x1a9b4d034050fa0b119bb64ba0e967fd09f224c6fd9cd8b54cd6f081085dfb98
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x080dbe10de0cacf12db303a86049c7a4d42f068a9def099e0cb874008f210b1b,
0x02f17638d3410ab573e33a4e6c6cf0c918bea2aa4f1025ca5ee13d7a950c4058
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x267043dbe00520bd8bbf55a96b51fde6b3b64219eca9e2fd8309693db0cf0392,
0x08dbbfa17faad841228af22a03fab7ec20f765036a2acae62f543f61e55b6e8c
);
// 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(
0x215141775449677e3dbe25ff6c5e5d99336a29d952a61d5ec87618346e78df30,
0x29502caeb6afaf2acd13766d52fac2907efb7d11c66cd8beb93c8321d380b215
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x150790105b9f5455ae6f91daa6b03c5793fb7bcfcd9d5d37d3b643b77535b10a,
0x2b644a9736282f80fae8d35f00cbddf2bba3560c54f3d036ec1c8014c147a506
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x1b898666ded092a449935de7d707ad8d65809c2baccdd7dd7cfdaf2fb27e1262,
0x2a24c241dcad93b7bdf1cce2427c9c54f731a7d50c27a825e2af3dabb66dc81f
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x049892634dbbfa0c364523827cd7e604b70a7e24a4cb111cb8fccb7c05b04d7f,
0x1e5d8d7c0bf92d822dcf339a52c326a35cadf010b888b8f26e155a68c7e23dc9
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x04f90846cb1598aa05164a78d171ea918154414652d07d3f5cab84a26e6aa158,
0x0975ba8858f136bb8b1b043daf8dfed33709f72ba37e01e5de62c81f3928a13c
);
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;
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 factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function initialize(address, address) external;
function mint(address to, uint amount) external;
function burn(address to, uint amount) external;
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/UniswapSafeMath.sol';
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using UniswapSafeMath for uint;
string public constant name = 'ZKSWAP V2';
string public constant symbol = 'ZKS-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint 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;
}
}
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
pragma solidity =0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
pragma solidity >=0.5.0;
interface IUNISWAPERC20 {
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);
}
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PlonkCoreLib.sol";
contract Plonk4AggVerifierWithAccessToDNext {
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 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 (uint 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 (uint 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 (uint i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.gate_selector_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint 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 (uint 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 (uint 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 (uint 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();
state.cached_lagrange_evals = new PairingsBn254.Fr[](1);
state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain(
0,
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[] 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[] 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 AggVerifierWithDeserialize is Plonk4AggVerifierWithAccessToDNext {
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[] 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;
}
}
pragma solidity >=0.5.0 <0.7.0;
import "./PlonkCoreLib.sol";
contract Plonk4SingleVerifierWithAccessToDNext {
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant STATE_WIDTH = 4;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[STATE_WIDTH+2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant
PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] next_step_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point 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 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 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);
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 - 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(
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..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 + STATE_WIDTH - 1;
res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH + 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; 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].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 - 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(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey 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 (uint 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 (uint 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 (uint 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 - 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 (uint 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 (uint 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(
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.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();
state.cached_lagrange_evals = new PairingsBn254.Fr[](1);
state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain(
0,
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(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
PartialVerifierState memory state;
bool valid = verify_initial(state, proof, vk);
if (valid == false) {
return false;
}
valid = verify_commitments(state, proof, vk);
return valid;
}
}
contract SingleVerifierWithDeserialize is Plonk4SingleVerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 33;
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.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;
}
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.5.0;
interface IUniswapV2ERC20 {
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);
}
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library UniswapSafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity >=0.5.0 <0.7.0;
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 {
uint[2] X;
uint[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
{
uint[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);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint 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];
}
uint[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});
}
}
|
require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
|
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp1');
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(zkSyncAddress != address(0), 'wzk');
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
| 1,250,512 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.