file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
./partial_match/1/0xd3B5AD4979788Cf23cBE0704C2Cd2F0629e521b6/sources/LiquidityMining.sol
|
* @dev this function allows any user to rebalance the pinned setup. */ if (!_hasPinned || !_setups[_pinnedSetupIndex].free) return; this is a locked setup that it's currently active or it's a new one the amount to add to the pinned is given by the difference between the reward per block and currently locked one in the case of a new setup, the currentRewardPerBlock is 0 so the difference is the whole rewardPerBlock this is a locked setup that has expired check if the setup is renewable if it is, we renew it and add the reward per block
|
function rebalancePinnedSetup() public {
uint256 amount;
for (uint256 i = 0; i < _setups.length; i++) {
if (_setups[i].free) continue;
if (block.number >= _setups[i].startBlock && block.number < _setups[i].endBlock) {
amount += _setups[i].rewardPerBlock - ((_setups[i].rewardPerBlock * (_setups[i].currentStakedLiquidity * 1e18 / _setups[i].maximumLiquidity)) / 1e18);
_finishedLockedSetups[_setups[i].objectId] = true;
if (_setups[i].renewTimes > 0) {
_setups[i].renewTimes -= 1;
_renewSetup(i);
amount += _setups[i].rewardPerBlock;
}
}
}
if (_hasPinned && _setups[_pinnedSetupIndex].free) {
_setups[_pinnedSetupIndex].rewardPerBlock = _setups[_pinnedSetupIndex].currentRewardPerBlock;
_rebalanceRewardPerBlock(_pinnedSetupIndex, amount, true);
}
}
| 4,218,363 |
[
1,
2211,
445,
5360,
1281,
729,
358,
283,
12296,
326,
26193,
3875,
18,
342,
309,
16051,
67,
5332,
12178,
11748,
747,
401,
67,
8401,
87,
63,
67,
13097,
11748,
7365,
1016,
8009,
9156,
13,
327,
31,
333,
353,
279,
8586,
3875,
716,
518,
1807,
4551,
2695,
578,
518,
1807,
279,
394,
1245,
326,
3844,
358,
527,
358,
326,
26193,
353,
864,
635,
326,
7114,
3086,
326,
19890,
1534,
1203,
471,
4551,
8586,
1245,
316,
326,
648,
434,
279,
394,
3875,
16,
326,
783,
17631,
1060,
2173,
1768,
353,
374,
1427,
326,
7114,
353,
326,
7339,
19890,
2173,
1768,
333,
353,
279,
8586,
3875,
716,
711,
7708,
866,
309,
326,
3875,
353,
15723,
429,
309,
518,
353,
16,
732,
15723,
518,
471,
527,
326,
19890,
1534,
1203,
2,
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,
1,
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,
12296,
12178,
11748,
7365,
1435,
1071,
288,
203,
3639,
2254,
5034,
3844,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
8401,
87,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
67,
8401,
87,
63,
77,
8009,
9156,
13,
1324,
31,
203,
5411,
309,
261,
2629,
18,
2696,
1545,
389,
8401,
87,
63,
77,
8009,
1937,
1768,
597,
1203,
18,
2696,
411,
389,
8401,
87,
63,
77,
8009,
409,
1768,
13,
288,
203,
7734,
3844,
1011,
389,
8401,
87,
63,
77,
8009,
266,
2913,
2173,
1768,
300,
14015,
67,
8401,
87,
63,
77,
8009,
266,
2913,
2173,
1768,
380,
261,
67,
8401,
87,
63,
77,
8009,
2972,
510,
9477,
48,
18988,
24237,
380,
404,
73,
2643,
342,
389,
8401,
87,
63,
77,
8009,
15724,
48,
18988,
24237,
3719,
342,
404,
73,
2643,
1769,
203,
7734,
389,
13527,
8966,
7365,
87,
63,
67,
8401,
87,
63,
77,
8009,
1612,
548,
65,
273,
638,
31,
203,
7734,
309,
261,
67,
8401,
87,
63,
77,
8009,
1187,
359,
10694,
405,
374,
13,
288,
203,
10792,
389,
8401,
87,
63,
77,
8009,
1187,
359,
10694,
3947,
404,
31,
203,
10792,
389,
1187,
359,
7365,
12,
77,
1769,
203,
10792,
3844,
1011,
389,
8401,
87,
63,
77,
8009,
266,
2913,
2173,
1768,
31,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
3639,
309,
261,
67,
5332,
12178,
11748,
597,
389,
8401,
87,
63,
67,
13097,
11748,
7365,
1016,
8009,
9156,
13,
288,
203,
5411,
389,
8401,
87,
2
] |
pragma solidity ^0.4.24;
/**
* @title Kings Of London DApp
* @author Frederico Lacs
* @version 0.1.0
**/
import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol";
import "../node_modules/openzeppelin-solidity/contracts/payment/PullPayment.sol";
contract KOLogic is Ownable, PullPayment {
constructor (uint256 _blockCreationPrice, address _storageAddress) public {
blockCreationPrice = _blockCreationPrice;
emit UpdatedBlockCreationValue(_blockCreationPrice);
s = StorageInterface(_storageAddress);
emit UpdatedStorageAddress(_storageAddress);
}
StorageInterface internal s;
uint256 internal blockCreationPrice;
mapping(string => bool) internal isValidUniversity;
struct Block{
string imageURL;
string description;
address blockOwner;
bool forSale;
uint256 price;
// hash of information of block without blockOwner, for fast comparisons
bytes32 infoHash;
bool isEntity;
}
event NewValidUniversity (string _name);
event UpdatedBlockCreationValue (uint256 value);
event UpdatedStorageAddress (address newStorageAddress);
event BlockBought (
uint8 x,
uint8 y,
string indexed universityName,
address indexed oldOwner,
address indexed newOwner,
uint256 price
);
event BlockInformationUpdated (
uint8 x,
uint8 y,
string indexed universityName,
string _imageURL,
string _description,
address indexed _blockOwner,
bool indexed _forSale,
uint256 _price
);
function setBlockCreationPrice(uint256 _blockCreationPrice) public onlyOwner {
blockCreationPrice = _blockCreationPrice;
emit UpdatedBlockCreationValue(_blockCreationPrice);
}
function setStorageAddress(address _storageAddress) public onlyOwner {
s.transferOwnership(msg.sender);
s = StorageInterface(_storageAddress);
emit UpdatedStorageAddress(_storageAddress);
}
function addValidUniversity(string _name) public onlyOwner {
isValidUniversity[_name] = true;
emit NewValidUniversity(_name);
}
/*
* Could have made this a pure function and added the uni verification somewhere else.
* Maybe verify for valid universities in the frontend input?
*/
function getBlockID(uint8 _x, uint8 _y, string _uniName) internal view returns (bytes32 id) {
require(isValidUniversity[_uniName], "Invalid University");
id = keccak256(abi.encodePacked(_x, ":", _y, "@", _uniName));
}
function getInfoHash(string imageURL, string description, bool forSale, uint price) internal pure returns ( bytes32 infoHash) {
infoHash = keccak256(abi.encodePacked(imageURL, description, forSale, price));
}
function getBlock(bytes32 _id) internal view returns (Block b) {
string memory imageURL;
string memory description;
address blockOwner;
bool forSale;
uint256 price;
bool isEntity;
(imageURL, description, blockOwner, forSale, price, isEntity) = s.getBlock(_id);
bytes32 infoHash = getInfoHash(imageURL, description, forSale, price);
b = Block(imageURL, description, blockOwner, forSale, price, infoHash, isEntity);
}
function buyBlock (
uint8 _x,
uint8 _y,
string _uniName,
string _imageURL,
string _description,
bool _forSale
)
public
payable
returns (bool success)
{
// blockID = getBlockID(_x, _y, _uniName);
Block memory currentBlock = getBlock(getBlockID(_x, _y, _uniName));
// check if block is already created
if(currentBlock.isEntity) {
require(currentBlock.forSale, "Block is not for sale.");
require(msg.value >= currentBlock.price, "Not enough ether to buy block.");
address oldOwner = currentBlock.blockOwner;
// currentBlock variable is read only, so we call the update function
//require(s.updateBlock(blockID, _imageURL, _description, msg.sender, _forSale, msg.value), "Failed to update block.");
// pull payment from OpenZeppelin
asyncTransfer(oldOwner, msg.value);
emit BlockBought(_x, _y, _uniName, oldOwner, msg.sender, msg.value);
}
else {
// created new variable to have it in scope and not read from storage twice
uint256 _blockCreationPrice = blockCreationPrice;
require(msg.value >= _blockCreationPrice, "Not enough ether to create block.");
//require(s.newBlock(blockID, _imageURL, _description, msg.sender, _forSale, _blockCreationPrice), "Failed to create new block.");
// when new block is created, block is being bought from this contract.
emit BlockBought(_x, _y, _uniName, this, msg.sender, msg.value);
}
// bool blockUpdated = oldInfoHash != newInfoHash;
// if(blockUpdated);
if(currentBlock.infoHash != getInfoHash(_imageURL, _description, _forSale, msg.value)){
emit BlockInformationUpdated(_x, _y, _uniName, _imageURL, _description, msg.sender, _forSale, msg.value);
}
success = true;
}
function updateBlock (
uint8 _x,
uint8 _y,
string _uniName,
string _imageURL,
string _description,
bool _forSale,
uint256 _price
)
public
returns (bool success)
{
bytes32 blockID = getBlockID(_x, _y, _uniName);
address blockOwner = s.getBlockOwner(blockID);
// Added admin access in case we need to change inappropriate content
require(msg.sender == blockOwner || msg.sender == owner, "Not block owner.");
require(_price > 0, "Can't put selling price lower than zero.");
s.updateBlock(blockID, _imageURL, _description, blockOwner, _forSale, _price);
emit BlockInformationUpdated(_x, _y, _uniName, _imageURL, _description, blockOwner, _forSale, _price);
success = true;
}
}
interface StorageInterface {
function newBlock (
bytes32 _blockID,
string _imageURL,
string _description,
address _blockOwner,
bool _forSale,
uint256 _price
) external returns (bool success);
function updateBlock (
bytes32 _blockID,
string _imageURL,
string _description,
address _blockOwner,
bool _forSale,
uint256 _price
) external returns (bool success);
function deleteBlock (bytes32 _blockID) external returns (bool success);
function getBlock(bytes32 _blockID) external view returns (
string imageURL,
string description,
address blockOwner,
bool forSale,
uint256 price,
bool isEntity
);
function getBlockOwner(bytes32 _blockID) external view returns (address blockOwner);
function transferOwnership(address _newOwner) external;
}
contract KolStorageV1 is Ownable {
struct Block{
string imageURL;
string description;
address blockOwner;
bool forSale;
uint256 price;
// If block is available, means it is not an entity
bool isEntity;
}
// design decision to make this internal with getters.
// if visibility public, solc would auto-generate getters.
mapping(bytes32 => Block) internal blocks;
function newBlock (
bytes32 _blockID,
string _imageURL,
string _description,
address _blockOwner,
bool _forSale,
uint256 _price
)
external
onlyOwner
returns (bool success)
{
require(blocks[_blockID].isEntity == false, "Block was already created.");
blocks[_blockID] = Block(_imageURL, _description, _blockOwner, _forSale, _price, true);
success = true;
}
function updateBlock (
bytes32 _blockID,
string _imageURL,
string _description,
address _blockOwner,
bool _forSale,
uint256 _price
)
external
onlyOwner
returns (bool success)
{
require(blocks[_blockID].isEntity == true, "Block was not created, can't be updated.");
blocks[_blockID] = Block(_imageURL, _description, _blockOwner, _forSale, _price, true);
success = true;
}
function deleteBlock(bytes32 _blockID) external onlyOwner returns (bool success) {
blocks[_blockID].isEntity = false;
success = true;
}
function getBlock(bytes32 _blockID)
external
view
onlyOwner
returns (
string imageURL,
string description,
address blockOwner,
bool forSale,
uint256 price,
bool isEntity
)
{
Block memory b = blocks[_blockID];
imageURL = b.imageURL;
description = b.description;
blockOwner = b.blockOwner;
forSale = b.forSale;
price = b.price;
isEntity = b.isEntity;
}
function getBlockOwner(bytes32 _blockID) external view returns (address blockOwner) {
blockOwner = blocks[_blockID].blockOwner;
}
}
|
If block is available, means it is not an entity
|
struct Block{
string imageURL;
string description;
address blockOwner;
bool forSale;
uint256 price;
bool isEntity;
}
| 5,367,453 |
[
1,
2047,
1203,
353,
2319,
16,
4696,
518,
353,
486,
392,
1522,
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,
565,
1958,
3914,
95,
203,
3639,
533,
1316,
1785,
31,
203,
3639,
533,
2477,
31,
203,
3639,
1758,
1203,
5541,
31,
203,
3639,
1426,
364,
30746,
31,
203,
3639,
2254,
5034,
6205,
31,
203,
3639,
1426,
353,
1943,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: @openzeppelin\upgrades\contracts\Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol
pragma solidity ^0.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 is Initializable {
// 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;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {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 Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_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);
}
/**
* @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);
}
/**
* @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"));
}
uint256[50] private ______gap;
}
// File: contracts\modules\staking\IERC900.sol
pragma solidity ^0.5.12;
/**
* @title ERC900 Simple Staking Interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md
*/
interface IERC900 {
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
function stake(uint256 amount, bytes calldata data) external;
function stakeFor(address user, uint256 amount, bytes calldata data) external;
function unstake(uint256 amount, bytes calldata data) external;
function totalStakedFor(address addr) external view returns (uint256);
function totalStaked() external view returns (uint256);
function token() external view returns (address);
function supportsHistory() external pure returns (bool);
// NOTE: Not implementing the optional functions
// function lastStakedFor(address addr) external view returns (uint256);
// function totalStakedForAt(address addr, uint256 blockNumber) external view returns (uint256);
// function totalStakedAt(uint256 blockNumber) external view returns (uint256);
}
// File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _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;
}
uint256[50] private ______gap;
}
// File: contracts\common\Base.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Base is Initializable, Context, Ownable {
address constant ZERO_ADDRESS = address(0);
function initialize() public initializer {
Ownable.initialize(_msgSender());
}
}
// File: contracts\core\ModuleNames.sol
pragma solidity ^0.5.12;
/**
* @dev List of module names
*/
contract ModuleNames {
// Pool Modules
string internal constant MODULE_ACCESS = "access";
string internal constant MODULE_SAVINGS = "savings";
string internal constant MODULE_INVESTING = "investing";
string internal constant MODULE_STAKING = "staking";
string internal constant MODULE_DCA = "dca";
// External Modules (used to store addresses of external contracts)
string internal constant CONTRACT_RAY = "ray";
}
// File: contracts\common\Module.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Module is Base, ModuleNames {
event PoolAddressChanged(address newPool);
address public pool;
function initialize(address _pool) public initializer {
Base.initialize();
setPool(_pool);
}
function setPool(address _pool) public onlyOwner {
require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero");
pool = _pool;
emit PoolAddressChanged(_pool);
}
function getModuleAddress(string memory module) public view returns(address){
require(pool != ZERO_ADDRESS, "Module: no pool");
(bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module));
//Forward error from Pool contract
if (!success) assembly {
revert(add(result, 32), result)
}
address moduleAddress = abi.decode(result, (address));
// string memory error = string(abi.encodePacked("Module: requested module not found - ", module));
// require(moduleAddress != ZERO_ADDRESS, error);
require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found");
return moduleAddress;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\Roles.sol
pragma solidity ^0.5.0;
/**
* @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];
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\roles\CapperRole.sol
pragma solidity ^0.5.0;
contract CapperRole is Initializable, Context {
using Roles for Roles.Role;
event CapperAdded(address indexed account);
event CapperRemoved(address indexed account);
Roles.Role private _cappers;
function initialize(address sender) public initializer {
if (!isCapper(sender)) {
_addCapper(sender);
}
}
modifier onlyCapper() {
require(isCapper(_msgSender()), "CapperRole: caller does not have the Capper role");
_;
}
function isCapper(address account) public view returns (bool) {
return _cappers.has(account);
}
function addCapper(address account) public onlyCapper {
_addCapper(account);
}
function renounceCapper() public {
_removeCapper(_msgSender());
}
function _addCapper(address account) internal {
_cappers.add(account);
emit CapperAdded(account);
}
function _removeCapper(address account) internal {
_cappers.remove(account);
emit CapperRemoved(account);
}
uint256[50] private ______gap;
}
// File: contracts\modules\staking\StakingPool.sol
pragma solidity ^0.5.12;
/**
* @title ERC900 Simple Staking Interface basic implementation
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md
*/
contract StakingPool is Module, IERC900, CapperRole {
// @TODO: deploy this separately so we don't have to deploy it multiple times for each contract
using SafeMath for uint256;
// Token used for staking
ERC20 stakingToken;
// The default duration of stake lock-in (in seconds)
uint256 public defaultLockInDuration;
// To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes,
// both data structures are stored in a single mapping for a given addresses.
//
// It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor
// if other users are staking on behalf of a given address.
mapping (address => StakeContract) public stakeHolders;
// Struct for personal stakes (i.e., stakes made by this address)
// unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch)
// actualAmount - the amount of tokens in the stake
// stakedFor - the address the stake was staked for
struct Stake {
uint256 unlockedTimestamp;
uint256 actualAmount;
address stakedFor;
}
// Struct for all stake metadata at a particular address
// totalStakedFor - the number of tokens staked for this address
// personalStakeIndex - the index in the personalStakes array.
// personalStakes - append only array of stakes made by this address
// exists - whether or not there are stakes that involve this address
struct StakeContract {
uint256 totalStakedFor;
uint256 personalStakeIndex;
Stake[] personalStakes;
bool exists;
}
bool public userCapEnabled;
mapping(address => uint256) public userCap; //Limit of pool tokens which can be minted for a user during deposit
uint256 public defaultUserCap;
bool public stakingCapEnabled;
uint256 public stakingCap;
bool public vipUserEnabled;
mapping(address => bool) public isVipUser;
event VipUserEnabledChange(bool enabled);
event VipUserChanged(address indexed user, bool isVip);
event StakingCapChanged(uint256 newCap);
event StakingCapEnabledChange(bool enabled);
//global cap
event DefaultUserCapChanged(uint256 newCap);
event UserCapEnabledChange(bool enabled);
event UserCapChanged(address indexed user, uint256 newCap);
event Staked(address indexed user, uint256 amount, uint256 totalStacked, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 totalStacked, bytes data);
event setLockInDuration(uint256 defaultLockInDuration);
/**
* @dev Modifier that checks that this contract can transfer tokens from the
* balance in the stakingToken contract for the given address.
* @dev This modifier also transfers the tokens.
* @param _address address to transfer tokens from
* @param _amount uint256 the number of tokens
*/
modifier canStake(address _address, uint256 _amount) {
require(
stakingToken.transferFrom(_address, address(this), _amount),
"Stake required");
_;
}
modifier isUserCapEnabledForStakeFor(uint256 stake) {
if (stakingCapEnabled && !(vipUserEnabled && isVipUser[_msgSender()])) {
require((stakingCap > totalStaked() && (stakingCap-totalStaked() >= stake)), "StakingModule: stake exeeds staking cap");
}
if(userCapEnabled) {
uint256 cap = userCap[_msgSender()];
//check default user cap settings
if (defaultUserCap > 0) {
uint256 totalStaked = totalStakedFor(_msgSender());
//get new cap
if (defaultUserCap >= totalStaked) {
cap = defaultUserCap.sub(totalStaked);
} else {
cap = 0;
}
}
require(cap >= stake, "StakingModule: stake exeeds cap");
cap = cap.sub(stake);
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
_;
}
modifier isUserCapEnabledForUnStakeFor(uint256 unStake) {
_;
if(userCapEnabled){
uint256 cap = userCap[_msgSender()];
cap = cap.add(unStake);
if (cap > defaultUserCap) {
cap = defaultUserCap;
}
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
}
modifier checkUserCapDisabled() {
require(isUserCapEnabled() == false, "UserCapEnabled");
_;
}
modifier checkUserCapEnabled() {
require(isUserCapEnabled(), "UserCapDisabled");
_;
}
function initialize(address _pool, ERC20 _stakingToken, uint256 _defaultLockInDuration) public initializer {
stakingToken = _stakingToken;
defaultLockInDuration = _defaultLockInDuration;
Module.initialize(_pool);
CapperRole.initialize(_msgSender());
}
function setDefaultLockInDuration(uint256 _defaultLockInDuration) public onlyOwner {
defaultLockInDuration = _defaultLockInDuration;
emit setLockInDuration(_defaultLockInDuration);
}
function setUserCapEnabled(bool _userCapEnabled) public onlyCapper {
userCapEnabled = _userCapEnabled;
emit UserCapEnabledChange(userCapEnabled);
}
function setStakingCapEnabled(bool _stakingCapEnabled) public onlyCapper {
stakingCapEnabled= _stakingCapEnabled;
emit StakingCapEnabledChange(stakingCapEnabled);
}
function setDefaultUserCap(uint256 _newCap) public onlyCapper {
defaultUserCap = _newCap;
emit DefaultUserCapChanged(_newCap);
}
function setStakingCap(uint256 _newCap) public onlyCapper {
stakingCap = _newCap;
emit StakingCapChanged(_newCap);
}
function setUserCap(address user, uint256 cap) public onlyCapper {
userCap[user] = cap;
emit UserCapChanged(user, cap);
}
function setUserCap(address[] memory users, uint256[] memory caps) public onlyCapper {
require(users.length == caps.length, "SavingsModule: arrays length not match");
for(uint256 i=0; i < users.length; i++) {
userCap[users[i]] = caps[i];
emit UserCapChanged(users[i], caps[i]);
}
}
function setVipUserEnabled(bool _vipUserEnabled) public onlyCapper {
vipUserEnabled = _vipUserEnabled;
emit VipUserEnabledChange(_vipUserEnabled);
}
function setVipUser(address user, bool isVip) public onlyCapper {
isVipUser[user] = isVip;
emit VipUserChanged(user, isVip);
}
function isUserCapEnabled() public view returns(bool) {
return userCapEnabled;
}
function iStakingCapEnabled() public view returns(bool) {
return stakingCapEnabled;
}
/**
* @dev Returns the timestamps for when active personal stakes for an address will unlock
* @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved
* @param _address address that created the stakes
* @return uint256[] array of timestamps
*/
function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[] memory) {
uint256[] memory timestamps;
(timestamps,,) = getPersonalStakes(_address);
return timestamps;
}
/**
* @dev Returns the stake actualAmount for active personal stakes for an address
* @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved
* @param _address address that created the stakes
* @return uint256[] array of actualAmounts
*/
function getPersonalStakeActualAmounts(address _address) external view returns (uint256[] memory) {
uint256[] memory actualAmounts;
(,actualAmounts,) = getPersonalStakes(_address);
return actualAmounts;
}
/**
* @dev Returns the addresses that each personal stake was created for by an address
* @dev These accessors functions are needed until https://github.com/ethereum/web3.js/issues/1241 is solved
* @param _address address that created the stakes
* @return address[] array of amounts
*/
function getPersonalStakeForAddresses(address _address) external view returns (address[] memory) {
address[] memory stakedFor;
(,,stakedFor) = getPersonalStakes(_address);
return stakedFor;
}
/**
* @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the user
* @notice MUST trigger Staked event
* @param _amount uint256 the amount of tokens to stake
* @param _data bytes optional data to include in the Stake event
*/
function stake(uint256 _amount, bytes memory _data) public isUserCapEnabledForStakeFor(_amount) {
createStake(
_msgSender(),
_amount,
defaultLockInDuration,
_data);
}
/**
* @notice Stakes a certain amount of tokens, this MUST transfer the given amount from the caller
* @notice MUST trigger Staked event
* @param _user address the address the tokens are staked for
* @param _amount uint256 the amount of tokens to stake
* @param _data bytes optional data to include in the Stake event
*/
function stakeFor(address _user, uint256 _amount, bytes memory _data) public checkUserCapDisabled {
createStake(
_user,
_amount,
defaultLockInDuration,
_data);
}
/**
* @notice Unstakes a certain amount of tokens, this SHOULD return the given amount of tokens to the user, if unstaking is currently not possible the function MUST revert
* @notice MUST trigger Unstaked event
* @dev Unstaking tokens is an atomic operation—either all of the tokens in a stake, or none of the tokens.
* @dev Users can only unstake a single stake at a time, it is must be their oldest active stake. Upon releasing that stake, the tokens will be
* transferred back to their account, and their personalStakeIndex will increment to the next active stake.
* @param _amount uint256 the amount of tokens to unstake
* @param _data bytes optional data to include in the Unstake event
*/
function unstake(uint256 _amount, bytes memory _data) public {
withdrawStake(
_amount,
_data);
}
function unstakeAllUnlocked(bytes memory _data) public returns(uint256) {
uint256 unstakeAllAmount = 0;
uint256 personalStakeIndex = stakeHolders[_msgSender()].personalStakeIndex;
for(uint256 i=personalStakeIndex; i<stakeHolders[_msgSender()].personalStakes.length; i++) {
if (stakeHolders[_msgSender()].personalStakes[i].unlockedTimestamp <= block.timestamp) {
unstakeAllAmount = unstakeAllAmount+stakeHolders[_msgSender()].personalStakes[i].actualAmount;
withdrawStake(stakeHolders[_msgSender()].personalStakes[i].actualAmount, _data);
}
}
return unstakeAllAmount;
}
/**
* @notice Returns the current total of tokens staked for an address
* @param _address address The address to query
* @return uint256 The number of tokens staked for the given address
*/
function totalStakedFor(address _address) public view returns (uint256) {
return stakeHolders[_address].totalStakedFor;
}
/**
* @notice Returns the current total of tokens staked
* @return uint256 The number of tokens staked in the contract
*/
function totalStaked() public view returns (uint256) {
return stakingToken.balanceOf(address(this));
}
/**
* @notice Address of the token being used by the staking interface
* @return address The address of the ERC20 token used for staking
*/
function token() public view returns (address) {
return address(stakingToken);
}
/**
* @notice MUST return true if the optional history functions are implemented, otherwise false
* @dev Since we don't implement the optional interface, this always returns false
* @return bool Whether or not the optional history functions are implemented
*/
function supportsHistory() public pure returns (bool) {
return false;
}
/**
* @dev Helper function to get specific properties of all of the personal stakes created by an address
* @param _address address The address to query
* @return (uint256[], uint256[], address[])
* timestamps array, actualAmounts array, stakedFor array
*/
function getPersonalStakes(
address _address
)
public view
returns(uint256[] memory, uint256[] memory, address[] memory)
{
StakeContract storage stakeContract = stakeHolders[_address];
uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex;
uint256[] memory unlockedTimestamps = new uint256[](arraySize);
uint256[] memory actualAmounts = new uint256[](arraySize);
address[] memory stakedFor = new address[](arraySize);
for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) {
uint256 index = i - stakeContract.personalStakeIndex;
unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp;
actualAmounts[index] = stakeContract.personalStakes[i].actualAmount;
stakedFor[index] = stakeContract.personalStakes[i].stakedFor;
}
return (
unlockedTimestamps,
actualAmounts,
stakedFor
);
}
/**
* @dev Helper function to create stakes for a given address
* @param _address address The address the stake is being created for
* @param _amount uint256 The number of tokens being staked
* @param _lockInDuration uint256 The duration to lock the tokens for
* @param _data bytes optional data to include in the Stake event
*/
function createStake(
address _address,
uint256 _amount,
uint256 _lockInDuration,
bytes memory _data)
internal
canStake(_msgSender(), _amount)
{
if (!stakeHolders[_msgSender()].exists) {
stakeHolders[_msgSender()].exists = true;
}
stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount);
stakeHolders[_msgSender()].personalStakes.push(
Stake(
block.timestamp.add(_lockInDuration),
_amount,
_address)
);
emit Staked(
_address,
_amount,
totalStakedFor(_address),
_data);
}
/**
* @dev Helper function to withdraw stakes for the _msgSender()
* @param _amount uint256 The amount to withdraw. MUST match the stake amount for the
* stake at personalStakeIndex.
* @param _data bytes optional data to include in the Unstake event
*/
function withdrawStake(
uint256 _amount,
bytes memory _data)
internal isUserCapEnabledForUnStakeFor(_amount)
{
Stake storage personalStake = stakeHolders[_msgSender()].personalStakes[stakeHolders[_msgSender()].personalStakeIndex];
// Check that the current stake has unlocked & matches the unstake amount
require(
personalStake.unlockedTimestamp <= block.timestamp,
"The current stake hasn't unlocked yet");
require(
personalStake.actualAmount == _amount,
"The unstake amount does not match the current stake");
// Transfer the staked tokens from this contract back to the sender
// Notice that we are using transfer instead of transferFrom here, so
// no approval is needed beforehand.
require(
stakingToken.transfer(_msgSender(), _amount),
"Unable to withdraw stake");
stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor]
.totalStakedFor.sub(personalStake.actualAmount);
personalStake.actualAmount = 0;
stakeHolders[_msgSender()].personalStakeIndex++;
emit Unstaked(
personalStake.stakedFor,
_amount,
totalStakedFor(personalStake.stakedFor),
_data);
}
}
|
* @title ERC900 Simple Staking Interface basic implementation/ @TODO: deploy this separately so we don't have to deploy it multiple times for each contract Token used for staking The default duration of stake lock-in (in seconds) To save on gas, rather than create a separate mapping for totalStakedFor & personalStakes, both data structures are stored in a single mapping for a given addresses. It's possible to have a non-existing personalStakes, but have tokens in totalStakedFor if other users are staking on behalf of a given address. Struct for personal stakes (i.e., stakes made by this address) unlockedTimestamp - when the stake unlocks (in seconds since Unix epoch) actualAmount - the amount of tokens in the stake stakedFor - the address the stake was staked for
|
contract StakingPool is Module, IERC900, CapperRole {
using SafeMath for uint256;
ERC20 stakingToken;
uint256 public defaultLockInDuration;
mapping (address => StakeContract) public stakeHolders;
struct Stake {
uint256 unlockedTimestamp;
uint256 actualAmount;
address stakedFor;
}
struct StakeContract {
uint256 totalStakedFor;
uint256 personalStakeIndex;
Stake[] personalStakes;
bool exists;
}
bool public userCapEnabled;
uint256 public defaultUserCap;
bool public stakingCapEnabled;
uint256 public stakingCap;
bool public vipUserEnabled;
mapping(address => bool) public isVipUser;
event VipUserEnabledChange(bool enabled);
event VipUserChanged(address indexed user, bool isVip);
event StakingCapChanged(uint256 newCap);
event StakingCapEnabledChange(bool enabled);
event UserCapEnabledChange(bool enabled);
event UserCapChanged(address indexed user, uint256 newCap);
event Staked(address indexed user, uint256 amount, uint256 totalStacked, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 totalStacked, bytes data);
event setLockInDuration(uint256 defaultLockInDuration);
event DefaultUserCapChanged(uint256 newCap);
modifier canStake(address _address, uint256 _amount) {
require(
stakingToken.transferFrom(_address, address(this), _amount),
"Stake required");
_;
}
modifier isUserCapEnabledForStakeFor(uint256 stake) {
if (stakingCapEnabled && !(vipUserEnabled && isVipUser[_msgSender()])) {
require((stakingCap > totalStaked() && (stakingCap-totalStaked() >= stake)), "StakingModule: stake exeeds staking cap");
}
if(userCapEnabled) {
uint256 cap = userCap[_msgSender()];
if (defaultUserCap > 0) {
uint256 totalStaked = totalStakedFor(_msgSender());
if (defaultUserCap >= totalStaked) {
cap = defaultUserCap.sub(totalStaked);
cap = 0;
}
}
require(cap >= stake, "StakingModule: stake exeeds cap");
cap = cap.sub(stake);
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
_;
}
modifier isUserCapEnabledForStakeFor(uint256 stake) {
if (stakingCapEnabled && !(vipUserEnabled && isVipUser[_msgSender()])) {
require((stakingCap > totalStaked() && (stakingCap-totalStaked() >= stake)), "StakingModule: stake exeeds staking cap");
}
if(userCapEnabled) {
uint256 cap = userCap[_msgSender()];
if (defaultUserCap > 0) {
uint256 totalStaked = totalStakedFor(_msgSender());
if (defaultUserCap >= totalStaked) {
cap = defaultUserCap.sub(totalStaked);
cap = 0;
}
}
require(cap >= stake, "StakingModule: stake exeeds cap");
cap = cap.sub(stake);
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
_;
}
modifier isUserCapEnabledForStakeFor(uint256 stake) {
if (stakingCapEnabled && !(vipUserEnabled && isVipUser[_msgSender()])) {
require((stakingCap > totalStaked() && (stakingCap-totalStaked() >= stake)), "StakingModule: stake exeeds staking cap");
}
if(userCapEnabled) {
uint256 cap = userCap[_msgSender()];
if (defaultUserCap > 0) {
uint256 totalStaked = totalStakedFor(_msgSender());
if (defaultUserCap >= totalStaked) {
cap = defaultUserCap.sub(totalStaked);
cap = 0;
}
}
require(cap >= stake, "StakingModule: stake exeeds cap");
cap = cap.sub(stake);
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
_;
}
modifier isUserCapEnabledForStakeFor(uint256 stake) {
if (stakingCapEnabled && !(vipUserEnabled && isVipUser[_msgSender()])) {
require((stakingCap > totalStaked() && (stakingCap-totalStaked() >= stake)), "StakingModule: stake exeeds staking cap");
}
if(userCapEnabled) {
uint256 cap = userCap[_msgSender()];
if (defaultUserCap > 0) {
uint256 totalStaked = totalStakedFor(_msgSender());
if (defaultUserCap >= totalStaked) {
cap = defaultUserCap.sub(totalStaked);
cap = 0;
}
}
require(cap >= stake, "StakingModule: stake exeeds cap");
cap = cap.sub(stake);
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
_;
}
modifier isUserCapEnabledForStakeFor(uint256 stake) {
if (stakingCapEnabled && !(vipUserEnabled && isVipUser[_msgSender()])) {
require((stakingCap > totalStaked() && (stakingCap-totalStaked() >= stake)), "StakingModule: stake exeeds staking cap");
}
if(userCapEnabled) {
uint256 cap = userCap[_msgSender()];
if (defaultUserCap > 0) {
uint256 totalStaked = totalStakedFor(_msgSender());
if (defaultUserCap >= totalStaked) {
cap = defaultUserCap.sub(totalStaked);
cap = 0;
}
}
require(cap >= stake, "StakingModule: stake exeeds cap");
cap = cap.sub(stake);
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
_;
}
} else {
modifier isUserCapEnabledForUnStakeFor(uint256 unStake) {
_;
if(userCapEnabled){
uint256 cap = userCap[_msgSender()];
cap = cap.add(unStake);
if (cap > defaultUserCap) {
cap = defaultUserCap;
}
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
}
modifier isUserCapEnabledForUnStakeFor(uint256 unStake) {
_;
if(userCapEnabled){
uint256 cap = userCap[_msgSender()];
cap = cap.add(unStake);
if (cap > defaultUserCap) {
cap = defaultUserCap;
}
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
}
modifier isUserCapEnabledForUnStakeFor(uint256 unStake) {
_;
if(userCapEnabled){
uint256 cap = userCap[_msgSender()];
cap = cap.add(unStake);
if (cap > defaultUserCap) {
cap = defaultUserCap;
}
userCap[_msgSender()] = cap;
emit UserCapChanged(_msgSender(), cap);
}
}
modifier checkUserCapDisabled() {
require(isUserCapEnabled() == false, "UserCapEnabled");
_;
}
modifier checkUserCapEnabled() {
require(isUserCapEnabled(), "UserCapDisabled");
_;
}
function initialize(address _pool, ERC20 _stakingToken, uint256 _defaultLockInDuration) public initializer {
stakingToken = _stakingToken;
defaultLockInDuration = _defaultLockInDuration;
Module.initialize(_pool);
CapperRole.initialize(_msgSender());
}
function setDefaultLockInDuration(uint256 _defaultLockInDuration) public onlyOwner {
defaultLockInDuration = _defaultLockInDuration;
emit setLockInDuration(_defaultLockInDuration);
}
function setUserCapEnabled(bool _userCapEnabled) public onlyCapper {
userCapEnabled = _userCapEnabled;
emit UserCapEnabledChange(userCapEnabled);
}
function setStakingCapEnabled(bool _stakingCapEnabled) public onlyCapper {
stakingCapEnabled= _stakingCapEnabled;
emit StakingCapEnabledChange(stakingCapEnabled);
}
function setDefaultUserCap(uint256 _newCap) public onlyCapper {
defaultUserCap = _newCap;
emit DefaultUserCapChanged(_newCap);
}
function setStakingCap(uint256 _newCap) public onlyCapper {
stakingCap = _newCap;
emit StakingCapChanged(_newCap);
}
function setUserCap(address user, uint256 cap) public onlyCapper {
userCap[user] = cap;
emit UserCapChanged(user, cap);
}
function setUserCap(address[] memory users, uint256[] memory caps) public onlyCapper {
require(users.length == caps.length, "SavingsModule: arrays length not match");
for(uint256 i=0; i < users.length; i++) {
userCap[users[i]] = caps[i];
emit UserCapChanged(users[i], caps[i]);
}
}
function setUserCap(address[] memory users, uint256[] memory caps) public onlyCapper {
require(users.length == caps.length, "SavingsModule: arrays length not match");
for(uint256 i=0; i < users.length; i++) {
userCap[users[i]] = caps[i];
emit UserCapChanged(users[i], caps[i]);
}
}
function setVipUserEnabled(bool _vipUserEnabled) public onlyCapper {
vipUserEnabled = _vipUserEnabled;
emit VipUserEnabledChange(_vipUserEnabled);
}
function setVipUser(address user, bool isVip) public onlyCapper {
isVipUser[user] = isVip;
emit VipUserChanged(user, isVip);
}
function isUserCapEnabled() public view returns(bool) {
return userCapEnabled;
}
function iStakingCapEnabled() public view returns(bool) {
return stakingCapEnabled;
}
function getPersonalStakeUnlockedTimestamps(address _address) external view returns (uint256[] memory) {
uint256[] memory timestamps;
(timestamps,,) = getPersonalStakes(_address);
return timestamps;
}
function getPersonalStakeActualAmounts(address _address) external view returns (uint256[] memory) {
uint256[] memory actualAmounts;
(,actualAmounts,) = getPersonalStakes(_address);
return actualAmounts;
}
function getPersonalStakeForAddresses(address _address) external view returns (address[] memory) {
address[] memory stakedFor;
(,,stakedFor) = getPersonalStakes(_address);
return stakedFor;
}
function stake(uint256 _amount, bytes memory _data) public isUserCapEnabledForStakeFor(_amount) {
createStake(
_msgSender(),
_amount,
defaultLockInDuration,
_data);
}
function stakeFor(address _user, uint256 _amount, bytes memory _data) public checkUserCapDisabled {
createStake(
_user,
_amount,
defaultLockInDuration,
_data);
}
function unstake(uint256 _amount, bytes memory _data) public {
withdrawStake(
_amount,
_data);
}
function unstakeAllUnlocked(bytes memory _data) public returns(uint256) {
uint256 unstakeAllAmount = 0;
uint256 personalStakeIndex = stakeHolders[_msgSender()].personalStakeIndex;
for(uint256 i=personalStakeIndex; i<stakeHolders[_msgSender()].personalStakes.length; i++) {
if (stakeHolders[_msgSender()].personalStakes[i].unlockedTimestamp <= block.timestamp) {
unstakeAllAmount = unstakeAllAmount+stakeHolders[_msgSender()].personalStakes[i].actualAmount;
withdrawStake(stakeHolders[_msgSender()].personalStakes[i].actualAmount, _data);
}
}
return unstakeAllAmount;
}
function unstakeAllUnlocked(bytes memory _data) public returns(uint256) {
uint256 unstakeAllAmount = 0;
uint256 personalStakeIndex = stakeHolders[_msgSender()].personalStakeIndex;
for(uint256 i=personalStakeIndex; i<stakeHolders[_msgSender()].personalStakes.length; i++) {
if (stakeHolders[_msgSender()].personalStakes[i].unlockedTimestamp <= block.timestamp) {
unstakeAllAmount = unstakeAllAmount+stakeHolders[_msgSender()].personalStakes[i].actualAmount;
withdrawStake(stakeHolders[_msgSender()].personalStakes[i].actualAmount, _data);
}
}
return unstakeAllAmount;
}
function unstakeAllUnlocked(bytes memory _data) public returns(uint256) {
uint256 unstakeAllAmount = 0;
uint256 personalStakeIndex = stakeHolders[_msgSender()].personalStakeIndex;
for(uint256 i=personalStakeIndex; i<stakeHolders[_msgSender()].personalStakes.length; i++) {
if (stakeHolders[_msgSender()].personalStakes[i].unlockedTimestamp <= block.timestamp) {
unstakeAllAmount = unstakeAllAmount+stakeHolders[_msgSender()].personalStakes[i].actualAmount;
withdrawStake(stakeHolders[_msgSender()].personalStakes[i].actualAmount, _data);
}
}
return unstakeAllAmount;
}
function totalStakedFor(address _address) public view returns (uint256) {
return stakeHolders[_address].totalStakedFor;
}
function totalStaked() public view returns (uint256) {
return stakingToken.balanceOf(address(this));
}
function token() public view returns (address) {
return address(stakingToken);
}
function supportsHistory() public pure returns (bool) {
return false;
}
function getPersonalStakes(
address _address
)
public view
returns(uint256[] memory, uint256[] memory, address[] memory)
{
StakeContract storage stakeContract = stakeHolders[_address];
uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex;
uint256[] memory unlockedTimestamps = new uint256[](arraySize);
uint256[] memory actualAmounts = new uint256[](arraySize);
address[] memory stakedFor = new address[](arraySize);
for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) {
uint256 index = i - stakeContract.personalStakeIndex;
unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp;
actualAmounts[index] = stakeContract.personalStakes[i].actualAmount;
stakedFor[index] = stakeContract.personalStakes[i].stakedFor;
}
return (
unlockedTimestamps,
actualAmounts,
stakedFor
);
}
function getPersonalStakes(
address _address
)
public view
returns(uint256[] memory, uint256[] memory, address[] memory)
{
StakeContract storage stakeContract = stakeHolders[_address];
uint256 arraySize = stakeContract.personalStakes.length - stakeContract.personalStakeIndex;
uint256[] memory unlockedTimestamps = new uint256[](arraySize);
uint256[] memory actualAmounts = new uint256[](arraySize);
address[] memory stakedFor = new address[](arraySize);
for (uint256 i = stakeContract.personalStakeIndex; i < stakeContract.personalStakes.length; i++) {
uint256 index = i - stakeContract.personalStakeIndex;
unlockedTimestamps[index] = stakeContract.personalStakes[i].unlockedTimestamp;
actualAmounts[index] = stakeContract.personalStakes[i].actualAmount;
stakedFor[index] = stakeContract.personalStakes[i].stakedFor;
}
return (
unlockedTimestamps,
actualAmounts,
stakedFor
);
}
function createStake(
address _address,
uint256 _amount,
uint256 _lockInDuration,
bytes memory _data)
internal
canStake(_msgSender(), _amount)
{
if (!stakeHolders[_msgSender()].exists) {
stakeHolders[_msgSender()].exists = true;
}
stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount);
stakeHolders[_msgSender()].personalStakes.push(
Stake(
block.timestamp.add(_lockInDuration),
_amount,
_address)
);
emit Staked(
_address,
_amount,
totalStakedFor(_address),
_data);
}
function createStake(
address _address,
uint256 _amount,
uint256 _lockInDuration,
bytes memory _data)
internal
canStake(_msgSender(), _amount)
{
if (!stakeHolders[_msgSender()].exists) {
stakeHolders[_msgSender()].exists = true;
}
stakeHolders[_address].totalStakedFor = stakeHolders[_address].totalStakedFor.add(_amount);
stakeHolders[_msgSender()].personalStakes.push(
Stake(
block.timestamp.add(_lockInDuration),
_amount,
_address)
);
emit Staked(
_address,
_amount,
totalStakedFor(_address),
_data);
}
function withdrawStake(
uint256 _amount,
bytes memory _data)
internal isUserCapEnabledForUnStakeFor(_amount)
{
Stake storage personalStake = stakeHolders[_msgSender()].personalStakes[stakeHolders[_msgSender()].personalStakeIndex];
require(
personalStake.unlockedTimestamp <= block.timestamp,
"The current stake hasn't unlocked yet");
require(
personalStake.actualAmount == _amount,
"The unstake amount does not match the current stake");
require(
stakingToken.transfer(_msgSender(), _amount),
"Unable to withdraw stake");
stakeHolders[personalStake.stakedFor].totalStakedFor = stakeHolders[personalStake.stakedFor]
.totalStakedFor.sub(personalStake.actualAmount);
personalStake.actualAmount = 0;
stakeHolders[_msgSender()].personalStakeIndex++;
emit Unstaked(
personalStake.stakedFor,
_amount,
totalStakedFor(personalStake.stakedFor),
_data);
}
}
| 6,942,021 |
[
1,
654,
39,
29,
713,
4477,
934,
6159,
6682,
5337,
4471,
19,
632,
6241,
30,
7286,
333,
18190,
1427,
732,
2727,
1404,
1240,
358,
7286,
518,
3229,
4124,
364,
1517,
6835,
3155,
1399,
364,
384,
6159,
1021,
805,
3734,
434,
384,
911,
2176,
17,
267,
261,
267,
3974,
13,
2974,
1923,
603,
16189,
16,
9178,
2353,
752,
279,
9004,
2874,
364,
2078,
510,
9477,
1290,
473,
17816,
510,
3223,
16,
225,
3937,
501,
12597,
854,
4041,
316,
279,
2202,
2874,
364,
279,
864,
6138,
18,
2597,
1807,
3323,
358,
1240,
279,
1661,
17,
11711,
17816,
510,
3223,
16,
1496,
1240,
2430,
316,
2078,
510,
9477,
1290,
225,
309,
1308,
3677,
854,
384,
6159,
603,
12433,
6186,
434,
279,
864,
1758,
18,
7362,
364,
17816,
384,
3223,
261,
77,
18,
73,
12990,
384,
3223,
7165,
635,
333,
1758,
13,
25966,
4921,
300,
1347,
326,
384,
911,
7186,
87,
261,
267,
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,
934,
6159,
2864,
353,
5924,
16,
467,
654,
39,
29,
713,
16,
11200,
457,
2996,
225,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
4232,
39,
3462,
384,
6159,
1345,
31,
203,
203,
225,
2254,
5034,
1071,
805,
2531,
382,
5326,
31,
203,
203,
225,
2874,
261,
2867,
516,
934,
911,
8924,
13,
1071,
384,
911,
27003,
31,
203,
203,
203,
225,
1958,
934,
911,
288,
203,
565,
2254,
5034,
25966,
4921,
31,
203,
565,
2254,
5034,
3214,
6275,
31,
203,
565,
1758,
384,
9477,
1290,
31,
203,
225,
289,
203,
203,
225,
1958,
934,
911,
8924,
288,
203,
565,
2254,
5034,
2078,
510,
9477,
1290,
31,
203,
203,
565,
2254,
5034,
17816,
510,
911,
1016,
31,
203,
203,
565,
934,
911,
8526,
17816,
510,
3223,
31,
203,
203,
565,
1426,
1704,
31,
203,
225,
289,
203,
203,
225,
1426,
1071,
729,
4664,
1526,
31,
203,
203,
203,
21281,
225,
2254,
5034,
1071,
805,
1299,
4664,
31,
203,
225,
1426,
1071,
384,
6159,
4664,
1526,
31,
203,
225,
2254,
5034,
1071,
384,
6159,
4664,
31,
203,
203,
203,
225,
1426,
1071,
26180,
1299,
1526,
31,
203,
225,
2874,
12,
2867,
516,
1426,
13,
1071,
353,
58,
625,
1299,
31,
203,
21281,
203,
203,
225,
871,
776,
625,
1299,
1526,
3043,
12,
6430,
3696,
1769,
203,
225,
871,
776,
625,
1299,
5033,
12,
2867,
8808,
729,
16,
1426,
353,
58,
625,
1769,
203,
203,
225,
871,
934,
6159,
4664,
5033,
12,
11890,
5034,
394,
4664,
1769,
203,
225,
871,
2
] |
./partial_match/1/0xCA8586d15187D31eeF8B006Fc298e0F4fB2519fA/sources/CannathaiNFTShop.sol
|
* @notice free mint/
|
function freeMint(
uint256 quantity
) external nonReentrant whenFreeMintNotPaused {
require(quantity <= maxMintPerTx, "limit per tx");
require(
freeMintNumberByAddress[msg.sender] >= quantity,
"exceeded mint"
);
freeMintNumberByAddress[msg.sender] -= quantity;
_mintTransfer(quantity);
emit FreeMint(msg.sender, quantity);
}
| 2,763,451 |
[
1,
9156,
312,
474,
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,
565,
445,
4843,
49,
474,
12,
203,
3639,
2254,
5034,
10457,
203,
565,
262,
3903,
1661,
426,
8230,
970,
1347,
9194,
49,
474,
1248,
28590,
288,
203,
3639,
2583,
12,
16172,
1648,
943,
49,
474,
2173,
4188,
16,
315,
3595,
1534,
2229,
8863,
203,
3639,
2583,
12,
203,
5411,
4843,
49,
474,
1854,
858,
1887,
63,
3576,
18,
15330,
65,
1545,
10457,
16,
203,
5411,
315,
338,
5816,
312,
474,
6,
203,
3639,
11272,
203,
3639,
4843,
49,
474,
1854,
858,
1887,
63,
3576,
18,
15330,
65,
3947,
10457,
31,
203,
203,
3639,
389,
81,
474,
5912,
12,
16172,
1769,
203,
203,
3639,
3626,
15217,
49,
474,
12,
3576,
18,
15330,
16,
10457,
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
] |
pragma solidity 0.5.17;
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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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;
}
}
/**
* @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}.
*
* 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;
/**
* @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);
}
/**
* @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);
}
/**
* @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 Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @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];
}
}
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
/**
* @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20Mintable-mint}.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @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, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @title Pausable token
* @dev ERC20 with pausable transfers and allowances.
*
* Useful if you want to stop trades until the end of a crowdsale, or have
* an emergency switch for freezing all token transfers in the event of a large
* bug.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
/**
* @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;
}
}
contract RICEToken is ERC20, ERC20Detailed, ERC20Capped, ERC20Pausable, ERC20Burnable, Ownable {
address FoundingTeam = 0x12B8665E7b4684178a54122e121B83CC41d9d9C3;
address UserAcquisition = 0xdf7E62218B2f889a35a5510e65f9CD4288CB6D6E;
address PublicSales = 0x876443e20778Daa70BFd2552e815A674D0aA7BF8;
address PrivateSales = 0x20b803C1d5C9408Bdc5D76648A6F23EB519CD2bD;
struct LockTime {
uint256 releaseDate;
uint256 amount;
}
mapping (address => LockTime[]) public lockList;
mapping (uint => uint) public FoundingTeamMap;
mapping (uint => uint) public PrivateSalesMap;
struct Investor {
address wallet;
uint256 amount;
}
mapping (uint => Investor) public investorsList;
uint8 private _d = 18;
uint256 private totalTokens = 1000000000 * 10 ** uint256(_d);
uint256 private initialSupply = 600000000 * 10 ** uint256(_d);
address [] private lockedAddressList;
constructor() public ERC20Detailed("RICE", "RICE", _d) ERC20Capped(totalTokens) {
_mint(owner(), initialSupply);
FoundingTeamMap[1]=1658275200; // 2022-07-20T00:00:00Z
FoundingTeamMap[2]=1689811200; // 2023-07-20T00:00:00Z
FoundingTeamMap[3]=1721433600; // 2024-07-20T00:00:00Z
FoundingTeamMap[4]=1752969600; // 2025-07-20T00:00:00Z
FoundingTeamMap[5]=1784505600; // 2026-07-20T00:00:00Z
PrivateSalesMap[1]=1634688000; // 2021-10-20T00:00:00Z
PrivateSalesMap[2]=1642636800; // 2022-01-20T00:00:00Z
PrivateSalesMap[3]=1650412800; // 2022-04-20T00:00:00Z
PrivateSalesMap[4]=1658275200; // 2022-07-20T00:00:00Z
PrivateSalesMap[5]=1666224000; // 2022-10-20T00:00:00Z
PrivateSalesMap[6]=1674172800; // 2023-01-20T00:00:00Z
PrivateSalesMap[7]=1681948800; // 2023-04-20T00:00:00Z
PrivateSalesMap[8]=1689811200; // 2023-07-20T00:00:00Z
PrivateSalesMap[9]=1697760000; // 2023-10-20T00:00:00Z
PrivateSalesMap[10]=1705708800; // 2024-01-20T00:00:00Z
for(uint i = 1; i <= 5; i++) {
transferWithLock(FoundingTeam, 30000000 * 10 ** uint256(decimals()), FoundingTeamMap[i]);
}
investorsList[1] = Investor({wallet: 0xaDd68b582C54004aaa7eEefA849e47671023Fb9c, amount: 25000000});
investorsList[2] = Investor({wallet: 0x05f56BA72F05787AD57b6A5b803f2b92b9faa294, amount: 2500000});
investorsList[3] = Investor({wallet: 0xaC13b80e2880A5e0A4630039273FEefc91315638, amount: 3500000});
investorsList[4] = Investor({wallet: 0xDe4F4Fd9AE375196cDC22b891Dd13f019d5dd64C, amount: 2500000});
investorsList[5] = Investor({wallet: 0x0794c84AF1280D25D3CbED6256E11B33F426d59f, amount: 500000});
investorsList[6] = Investor({wallet: 0x788152f1b4610B74686C5E774e57B9E0986E958c, amount: 1000000});
investorsList[7] = Investor({wallet: 0x68dCfB21d343b7bD85599a30aAE2521788E09eB7, amount: 5000000});
investorsList[8] = Investor({wallet: 0xcbf155A2Ec6C35F5af1C2a1dF1bC3BB49980645B, amount: 15000000});
investorsList[9] = Investor({wallet: 0x7B9f1e95e08A09680c3DB9Fe95b7faEC574a8bBD, amount: 12500000});
investorsList[10] = Investor({wallet: 0x20b803C1d5C9408Bdc5D76648A6F23EB519CD2bD, amount: 100000000});
investorsList[11] = Investor({wallet: 0xf6e6715E0B075178c39D07386bE1bf55BAFd9180, amount: 57500000});
investorsList[12] = Investor({wallet: 0xaCCa1EF5efA7D2C5e8AcAC07F35cD939C1b0C960, amount: 15000000});
transfer(UserAcquisition, 200000000 * 10 ** uint256(decimals()));
transfer(PublicSales, 10000000 * 10 ** uint256(decimals()));
}
function transfer(address _receiver, uint256 _amount) public returns (bool success) {
require(_receiver != address(0));
require(_amount <= getAvailableBalance(msg.sender));
return ERC20.transfer(_receiver, _amount);
}
function transferFrom(address _from, address _receiver, uint256 _amount) public returns (bool) {
require(_from != address(0));
require(_receiver != address(0));
require(_amount <= allowance(_from, msg.sender));
require(_amount <= getAvailableBalance(_from));
return ERC20.transferFrom(_from, _receiver, _amount);
}
function transferWithLock(address _receiver, uint256 _amount, uint256 _releaseDate) public returns (bool success) {
require(msg.sender == FoundingTeam || msg.sender == PrivateSales || msg.sender == owner());
ERC20._transfer(msg.sender,_receiver,_amount);
if (lockList[_receiver].length==0) lockedAddressList.push(_receiver);
LockTime memory item = LockTime({amount:_amount, releaseDate:_releaseDate});
lockList[_receiver].push(item);
return true;
}
function getLockedAmount(address lockedAddress) public view returns (uint256 _amount) {
uint256 lockedAmount =0;
for(uint256 j = 0; j<lockList[lockedAddress].length; j++) {
if(now < lockList[lockedAddress][j].releaseDate) {
uint256 temp = lockList[lockedAddress][j].amount;
lockedAmount += temp;
}
}
return lockedAmount;
}
function getAvailableBalance(address lockedAddress) public view returns (uint256 _amount) {
uint256 bal = balanceOf(lockedAddress);
uint256 locked = getLockedAmount(lockedAddress);
return bal.sub(locked);
}
function getLockedAddresses() public view returns (address[] memory) {
return lockedAddressList;
}
function getNumberOfLockedAddresses() public view returns (uint256 _count) {
return lockedAddressList.length;
}
function getNumberOfLockedAddressesCurrently() public view returns (uint256 _count) {
uint256 count=0;
for(uint256 i = 0; i<lockedAddressList.length; i++) {
if (getLockedAmount(lockedAddressList[i])>0) count++;
}
return count;
}
function getLockedAddressesCurrently() public view returns (address[] memory) {
address [] memory list = new address[](getNumberOfLockedAddressesCurrently());
uint256 j = 0;
for(uint256 i = 0; i<lockedAddressList.length; i++) {
if (getLockedAmount(lockedAddressList[i])>0) {
list[j] = lockedAddressList[i];
j++;
}
}
return list;
}
function getLockedAmountTotal() public view returns (uint256 _amount) {
uint256 sum =0;
for(uint256 i = 0; i<lockedAddressList.length; i++) {
uint256 lockedAmount = getLockedAmount(lockedAddressList[i]);
sum = sum.add(lockedAmount);
}
return sum;
}
function getCirculatingSupplyTotal() public view returns (uint256 _amount) {
return totalSupply().sub(getLockedAmountTotal());
}
function getBurnedAmountTotal() public view returns (uint256 _amount) {
return totalTokens.sub(totalSupply());
}
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
}
function lockInvestor(uint256 investorId) public onlyOwner {
for(uint y = 3; y <= 10; y++) {
transferWithLock(investorsList[investorId].wallet, (investorsList[investorId].amount / 8) * 10 ** uint256(decimals()), PrivateSalesMap[y]);
}
}
function () payable external {
revert();
}
}
|
2023-07-20T00:00:00Z
|
PrivateSalesMap[8]=1689811200;
| 5,803,927 |
[
1,
18212,
23,
17,
8642,
17,
3462,
56,
713,
30,
713,
30,
713,
62,
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,
3639,
8726,
23729,
863,
63,
28,
65,
33,
2313,
6675,
11861,
2138,
713,
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
] |
pragma solidity ^0.4.11;
// define new contract
contract ArithValue{
uint number;
function ArithValue() public { //constructor function with default value
number = 100;
}
// constructor function to set new value
function setNumber(uint theValue) public {
number = theValue;
}
// constructor function to fetch the new value
function fetchNumber() public constant returns (uint) {
return number;
}
// constructor function to increment by one
function incrementNumber() public {
number=number + 1;
}
// constructor function to decrement by one
function decrementNumber() public {
number=number - 1;
}
}
|
define new contract
|
contract ArithValue{
uint number;
number = 100;
}
| 6,359,729 |
[
1,
11255,
394,
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,
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,
16351,
1201,
483,
620,
95,
203,
202,
11890,
1300,
31,
203,
202,
202,
2696,
273,
2130,
31,
203,
202,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x4eBa9A768edfc7a136159c2d6EEB95638D896bD7/sources/contracts/Contract.sol
|
Struct of complaints
|
struct complaint{
uint256 id;
address complaintRegisteredBy;
string title;
string description;
string approvalRemark;
string resolutionRemark;
bool isApproved;
bool isResolved;
bool exists;
}
uint256 id,
address complaintRegisteredBy,
string title
);
| 9,452,458 |
[
1,
3823,
434,
27534,
1598,
87,
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,
27534,
1598,
95,
203,
3639,
2254,
5034,
612,
31,
203,
3639,
1758,
27534,
1598,
10868,
858,
31,
203,
3639,
533,
2077,
31,
203,
3639,
533,
2477,
31,
203,
3639,
533,
23556,
1933,
1313,
31,
203,
3639,
533,
7861,
1933,
1313,
31,
203,
3639,
1426,
353,
31639,
31,
203,
3639,
1426,
353,
12793,
31,
203,
3639,
1426,
1704,
31,
203,
565,
289,
203,
203,
203,
3639,
2254,
5034,
612,
16,
203,
3639,
1758,
27534,
1598,
10868,
858,
16,
203,
3639,
533,
2077,
203,
565,
11272,
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
] |
pragma solidity 0.5.9; // optimization enabled, runs: 10000, evm: constantinople
/**
* @title HomeWork Interface (version 1) - EIP165 ID 0xe5399799
* @author 0age
* @notice Homework is a utility to find, share, and reuse "home" addresses for
* contracts. Anyone can work to find a new home address by searching for keys,
* a 32-byte value with the first 20 bytes equal to the finder's calling address
* (or derived by hashing an arbitrary 32-byte salt and the caller's address),
* and can then deploy any contract they like (even one with a constructor) to
* the address, or mint an ERC721 token that the owner can redeem that will then
* allow them to do the same. Also, if the contract is `SELFDESTRUCT`ed, a new
* contract can be redeployed by the current controller to the same address!
* @dev This contract allows contract addresses to be located ahead of time, and
* for arbitrary bytecode to be deployed (and redeployed if so desired, i.e.
* metamorphic contracts) to the located address by a designated controller. To
* enable this, the contract first deploys an "initialization-code-in-runtime"
* contract, with the creation code of the contract you want to deploy stored in
* RUNTIME code. Then, to deploy the actual contract, it retrieves the address
* of the storage contract and `DELEGATECALL`s into it to execute the init code
* and, if successful, retrieves and returns the contract runtime code. Rather
* than using a located address directly, you can also lock it in the contract
* and mint and ERC721 token for it, which can then be redeemed in order to gain
* control over deployment to the address (note that tokens may not be minted if
* the contract they control currently has a deployed contract at that address).
* Once a contract undergoes metamorphosis, all existing storage will be deleted
* and any existing contract code will be replaced with the deployed contract
* code of the new implementation contract. The mechanisms behind this contract
* are highly experimental - proceed with caution and please share any exploits
* or optimizations you discover.
*/
interface IHomeWork {
// Fires when a contract is deployed or redeployed to a given home address.
event NewResident(
address indexed homeAddress,
bytes32 key,
bytes32 runtimeCodeHash
);
// Fires when a new runtime storage contract is deployed.
event NewRuntimeStorageContract(
address runtimeStorageContract,
bytes32 runtimeCodeHash
);
// Fires when a controller is changed from the default controller.
event NewController(bytes32 indexed key, address newController);
// Fires when a new high score is submitted.
event NewHighScore(bytes32 key, address submitter, uint256 score);
// Track total contract deploys and current controller for each home address.
struct HomeAddress {
bool exists;
address controller;
uint88 deploys;
}
// Track derivation of key for a given home address based on salt & submitter.
struct KeyInformation {
bytes32 key;
bytes32 salt;
address submitter;
}
/**
* @notice Deploy a new contract with the desired initialization code to the
* home address corresponding to a given key. Two conditions must be met: the
* submitter must be designated as the controller of the home address (with
* the initial controller set to the address corresponding to the first twenty
* bytes of the key), and there must not be a contract currently deployed at
* the home address. These conditions can be checked by calling
* `getHomeAddressInformation` and `isDeployable` with the same key.
* @param key bytes32 The unique value used to derive the home address.
* @param initializationCode bytes The contract creation code that will be
* used to deploy the contract to the home address.
* @return The home address of the deployed contract.
* @dev In order to deploy the contract to the home address, a new contract
* will be deployed with runtime code set to the initialization code of the
* contract that will be deployed to the home address. Then, metamorphic
* initialization code will retrieve that initialization code and use it to
* set up and deploy the desired contract to the home address. Bear in mind
* that the deployed contract will interpret msg.sender as the address of THIS
* contract, and not the address of the submitter - if the constructor of the
* deployed contract uses msg.sender to set up ownership or other variables,
* you must modify it to accept a constructor argument with the appropriate
* address, or alternately to hard-code the intended address. Also, if your
* contract DOES have constructor arguments, remember to include them as
* ABI-encoded arguments at the end of the initialization code, just as you
* would when performing a standard deploy. You may also want to provide the
* key to `setReverseLookup` in order to find it again using only the home
* address to prevent accidentally losing the key.
*/
function deploy(bytes32 key, bytes calldata initializationCode)
external
payable
returns (address homeAddress, bytes32 runtimeCodeHash);
/**
* @notice Mint an ERC721 token to the supplied owner that can be redeemed in
* order to gain control of a home address corresponding to a given key. Two
* conditions must be met: the submitter must be designated as the controller
* of the home address (with the initial controller set to the address
* corresponding to the first 20 bytes of the key), and there must not be a
* contract currently deployed at the home address. These conditions can be
* checked by calling `getHomeAddressInformation` and `isDeployable` with the
* same key.
* @param key bytes32 The unique value used to derive the home address.
* @param owner address The account that will be granted ownership of the
* ERC721 token.
* @dev In order to mint an ERC721 token, the assocated home address cannot be
* in use, or else the token will not be able to deploy to the home address.
* The controller is set to this contract until the token is redeemed, at
* which point the redeemer designates a new controller for the home address.
* The key of the home address and the tokenID of the ERC721 token are the
* same value, but different types (bytes32 vs. uint256).
*/
function lock(bytes32 key, address owner) external;
/**
* @notice Burn an ERC721 token to allow the supplied controller to gain the
* ability to deploy to the home address corresponding to the key matching the
* burned token. The submitter must be designated as either the owner of the
* token or as an approved spender.
* @param tokenId uint256 The ID of the ERC721 token to redeem.
* @param controller address The account that will be granted control of the
* home address corresponding to the given token.
* @dev The controller cannot be designated as the address of this contract,
* the null address, or the home address (the restriction on setting the home
* address as the controller is due to the fact that the home address will not
* be able to deploy to itself, as it needs to be empty before a contract can
* be deployed to it).
*/
function redeem(uint256 tokenId, address controller) external;
/**
* @notice Transfer control over deployment to the home address corresponding
* to a given key. The caller must be designated as the current controller of
* the home address (with the initial controller set to the address
* corresponding to the first 20 bytes of the key) - This condition can be
* checked by calling `getHomeAddressInformation` with the same key.
* @param key bytes32 The unique value used to derive the home address.
* @param controller address The account that will be granted control of the
* home address corresponding to the given key.
* @dev The controller cannot be designated as the address of this contract,
* the null address, or the home address (the restriction on setting the home
* address as the controller is due to the fact that the home address will not
* be able to deploy to itself, as it needs to be empty before a contract can
* be deployed to it).
*/
function assignController(bytes32 key, address controller) external;
/**
* @notice Transfer control over deployment to the home address corresponding
* to a given key to the null address, which will prevent it from being
* deployed to again in the future. The caller must be designated as the
* current controller of the corresponding home address (with the initial
* controller set to the address corresponding to the first 20 bytes of the
* key) - This condition can be checked by calling `getHomeAddressInformation`
* with the same key.
* @param key bytes32 The unique value used to derive the home address.
*/
function relinquishControl(bytes32 key) external;
/**
* @notice Burn an ERC721 token, set a supplied controller, and deploy a new
* contract with the supplied initialization code to the corresponding home
* address for the given token. The submitter must be designated as either the
* owner of the token or as an approved spender.
* @param tokenId uint256 The ID of the ERC721 token to redeem.
* @param controller address The account that will be granted control of the
* home address corresponding to the given token.
* @param initializationCode bytes The contract creation code that will be
* used to deploy the contract to the home address.
* @return The home address and runtime code hash of the deployed contract.
* @dev In order to deploy the contract to the home address, a new contract
* will be deployed with runtime code set to the initialization code of the
* contract that will be deployed to the home address. Then, metamorphic
* initialization code will retrieve that initialization code and use it to
* set up and deploy the desired contract to the home address. Bear in mind
* that the deployed contract will interpret msg.sender as the address of THIS
* contract, and not the address of the submitter - if the constructor of the
* deployed contract uses msg.sender to set up ownership or other variables,
* you must modify it to accept a constructor argument with the appropriate
* address, or alternately to hard-code the intended address. Also, if your
* contract DOES have constructor arguments, remember to include them as
* ABI-encoded arguments at the end of the initialization code, just as you
* would when performing a standard deploy. You may also want to provide the
* key to `setReverseLookup` in order to find it again using only the home
* address to prevent accidentally losing the key. The controller cannot be
* designated as the address of this contract, the null address, or the home
* address (the restriction on setting the home address as the controller is
* due to the fact that the home address will not be able to deploy to itself,
* as it needs to be empty before a contract can be deployed to it). Also,
* checks on the contract at the home address being empty or not having the
* correct controller are unnecessary, as they are performed when minting the
* token and cannot be altered until the token is redeemed.
*/
function redeemAndDeploy(
uint256 tokenId,
address controller,
bytes calldata initializationCode
)
external
payable
returns (address homeAddress, bytes32 runtimeCodeHash);
/**
* @notice Derive a new key by concatenating an arbitrary 32-byte salt value
* and the address of the caller and performing a keccak256 hash. This allows
* for the creation of keys with additional entropy where desired while also
* preventing collisions with standard keys. The caller will be set as the
* controller of the derived key.
* @param salt bytes32 The desired salt value to use (along with the address
* of the caller) when deriving the resultant key and corresponding home
* address.
* @return The derived key.
* @dev Home addresses from derived keys will take longer to "mine" or locate,
* as an additional hash must be performed when computing the corresponding
* home address for each given salt input. Each caller will derive a different
* key even if they are supplying the same salt value.
*/
function deriveKey(bytes32 salt) external returns (bytes32 key);
/**
* @notice Mint an ERC721 token to the supplied owner that can be redeemed in
* order to gain control of a home address corresponding to a given derived
* key. Two conditions must be met: the submitter must be designated as the
* current controller of the home address, and there must not be a contract
* currently deployed at the home address. These conditions can be checked by
* calling `getHomeAddressInformation` and `isDeployable` with the key
* determined by calling `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @param owner address The account that will be granted ownership of the
* ERC721 token.
* @return The derived key.
* @dev In order to mint an ERC721 token, the assocated home address cannot be
* in use, or else the token will not be able to deploy to the home address.
* The controller is set to this contract until the token is redeemed, at
* which point the redeemer designates a new controller for the home address.
* The key of the home address and the tokenID of the ERC721 token are the
* same value, but different types (bytes32 vs. uint256).
*/
function deriveKeyAndLock(bytes32 salt, address owner)
external
returns (bytes32 key);
/**
* @notice Transfer control over deployment to the home address corresponding
* to a given derived key. The caller must be designated as the current
* controller of the home address - This condition can be checked by calling
* `getHomeAddressInformation` with the key obtained via `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @param controller address The account that will be granted control of the
* home address corresponding to the given derived key.
* @return The derived key.
* @dev The controller cannot be designated as the address of this contract,
* the null address, or the home address (the restriction on setting the home
* address as the controller is due to the fact that the home address will not
* be able to deploy to itself, as it needs to be empty before a contract can
* be deployed to it).
*/
function deriveKeyAndAssignController(bytes32 salt, address controller)
external
returns (bytes32 key);
/**
* @notice Transfer control over deployment to the home address corresponding
* to a given derived key to the null address, which will prevent it from
* being deployed to again in the future. The caller must be designated as the
* current controller of the home address - This condition can be checked by
* calling `getHomeAddressInformation` with the key determined by calling
* `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @return The derived key.
*/
function deriveKeyAndRelinquishControl(bytes32 salt)
external
returns (bytes32 key);
/**
* @notice Record a key that corresponds to a given home address by supplying
* said key and using it to derive the address. This enables reverse lookup
* of a key using only the home address in question. This method may be called
* by anyone - control of the key is not required.
* @param key bytes32 The unique value used to derive the home address.
* @dev This does not set the salt or submitter fields, as those apply only to
* derived keys (although a derived key may also be set with this method, just
* without the derived fields).
*/
function setReverseLookup(bytes32 key) external;
/**
* @notice Record the derived key that corresponds to a given home address by
* supplying the salt and submitter that were used to derive the key. This
* facititates reverse lookup of the derivation method of a key using only the
* home address in question. This method may be called by anyone - control of
* the derived key is not required.
* @param salt bytes32 The salt value that is used to derive the key.
* @param submitter address The account that submits the salt that is used to
* derive the key.
*/
function setDerivedReverseLookup(bytes32 salt, address submitter) external;
/**
* @notice Deploy a new storage contract with the supplied code as runtime
* code without deploying a contract to a home address. This can be used to
* store the contract creation code for use in future deployments of contracts
* to home addresses.
* @param codePayload bytes The code to set as the runtime code of the
* deployed contract.
* @return The address of the deployed storage contract.
* @dev Consider placing adequate protections on the storage contract to
* prevent unwanted callers from modifying or destroying it. Also, if you are
* placing contract contract creation code into the runtime storage contract,
* remember to include any constructor parameters as ABI-encoded arguments at
* the end of the contract creation code, similar to how you would perform a
* standard deployment.
*/
function deployRuntimeStorageContract(bytes calldata codePayload)
external
returns (address runtimeStorageContract);
/**
* @notice Deploy a new contract with the initialization code stored in the
* runtime code at the specified initialization runtime storage contract to
* the home address corresponding to a given key. Two conditions must be met:
* the submitter must be designated as the controller of the home address
* (with the initial controller set to the address corresponding to the first
* 20 bytes of the key), and there must not be a contract currently deployed
* at the home address. These conditions can be checked by calling
* `getHomeAddressInformation` and `isDeployable` with the same key.
* @param key bytes32 The unique value used to derive the home address.
* @param initializationRuntimeStorageContract address The storage contract
* with runtime code equal to the contract creation code that will be used to
* deploy the contract to the home address.
* @return The home address and runtime code hash of the deployed contract.
* @dev When deploying a contract to a home address via this method, the
* metamorphic initialization code will retrieve whatever initialization code
* currently resides at the specified address and use it to set up and deploy
* the desired contract to the home address. Bear in mind that the deployed
* contract will interpret msg.sender as the address of THIS contract, and not
* the address of the submitter - if the constructor of the deployed contract
* uses msg.sender to set up ownership or other variables, you must modify it
* to accept a constructor argument with the appropriate address, or
* alternately to hard-code the intended address. Also, if your contract DOES
* have constructor arguments, remember to include them as ABI-encoded
* arguments at the end of the initialization code, just as you would when
* performing a standard deploy. You may also want to provide the key to
* `setReverseLookup` in order to find it again using only the home address to
* prevent accidentally losing the key.
*/
function deployViaExistingRuntimeStorageContract(
bytes32 key,
address initializationRuntimeStorageContract
)
external
payable
returns (address homeAddress, bytes32 runtimeCodeHash);
/**
* @notice Burn an ERC721 token, set a supplied controller, and deploy a new
* contract with the initialization code stored in the runtime code at the
* specified initialization runtime storage contract to the home address
* corresponding to a given key. The submitter must be designated as either
* the owner of the token or as an approved spender.
* @param tokenId uint256 The ID of the ERC721 token to redeem.
* @param controller address The account that will be granted control of the
* home address corresponding to the given token.
* @param initializationRuntimeStorageContract address The storage contract
* with runtime code equal to the contract creation code that will be used to
* deploy the contract to the home address.
* @return The home address and runtime code hash of the deployed contract.
* @dev When deploying a contract to a home address via this method, the
* metamorphic initialization code will retrieve whatever initialization code
* currently resides at the specified address and use it to set up and deploy
* the desired contract to the home address. Bear in mind that the deployed
* contract will interpret msg.sender as the address of THIS contract, and not
* the address of the submitter - if the constructor of the deployed contract
* uses msg.sender to set up ownership or other variables, you must modify it
* to accept a constructor argument with the appropriate address, or
* alternately to hard-code the intended address. Also, if your contract DOES
* have constructor arguments, remember to include them as ABI-encoded
* arguments at the end of the initialization code, just as you would when
* performing a standard deploy. You may also want to provide the key to
* `setReverseLookup` in order to find it again using only the home address to
* prevent accidentally losing the key. The controller cannot be designated as
* the address of this contract, the null address, or the home address (the
* restriction on setting the home address as the controller is due to the
* fact that the home address will not be able to deploy to itself, as it
* needs to be empty before a contract can be deployed to it). Also, checks on
* the contract at the home address being empty or not having the correct
* controller are unnecessary, as they are performed when minting the token
* and cannot be altered until the token is redeemed.
*/
function redeemAndDeployViaExistingRuntimeStorageContract(
uint256 tokenId,
address controller,
address initializationRuntimeStorageContract
)
external
payable
returns (address homeAddress, bytes32 runtimeCodeHash);
/**
* @notice Deploy a new contract with the desired initialization code to the
* home address corresponding to a given derived key. Two conditions must be
* met: the submitter must be designated as the controller of the home
* address, and there must not be a contract currently deployed at the home
* address. These conditions can be checked by calling
* `getHomeAddressInformation` and `isDeployable` with the key obtained by
* calling `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @param initializationCode bytes The contract creation code that will be
* used to deploy the contract to the home address.
* @return The home address, derived key, and runtime code hash of the
* deployed contract.
* @dev In order to deploy the contract to the home address, a new contract
* will be deployed with runtime code set to the initialization code of the
* contract that will be deployed to the home address. Then, metamorphic
* initialization code will retrieve that initialization code and use it to
* set up and deploy the desired contract to the home address. Bear in mind
* that the deployed contract will interpret msg.sender as the address of THIS
* contract, and not the address of the submitter - if the constructor of the
* deployed contract uses msg.sender to set up ownership or other variables,
* you must modify it to accept a constructor argument with the appropriate
* address, or alternately to hard-code the intended address. Also, if your
* contract DOES have constructor arguments, remember to include them as
* ABI-encoded arguments at the end of the initialization code, just as you
* would when performing a standard deploy. You may want to provide the salt
* and submitter to `setDerivedReverseLookup` in order to find the salt,
* submitter, and derived key using only the home address to prevent
* accidentally losing them.
*/
function deriveKeyAndDeploy(bytes32 salt, bytes calldata initializationCode)
external
payable
returns (address homeAddress, bytes32 key, bytes32 runtimeCodeHash);
/**
* @notice Deploy a new contract with the initialization code stored in the
* runtime code at the specified initialization runtime storage contract to
* the home address corresponding to a given derived key. Two conditions must
* be met: the submitter must be designated as the controller of the home
* address, and there must not be a contract currently deployed at the home
* address. These conditions can be checked by calling
* `getHomeAddressInformation` and `isDeployable` with the key obtained by
* calling `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @param initializationRuntimeStorageContract address The storage contract
* with runtime code equal to the contract creation code that will be used to
* deploy the contract to the home address.
* @return The home address, derived key, and runtime code hash of the
* deployed contract.
* @dev When deploying a contract to a home address via this method, the
* metamorphic initialization code will retrieve whatever initialization code
* currently resides at the specified address and use it to set up and deploy
* the desired contract to the home address. Bear in mind that the deployed
* contract will interpret msg.sender as the address of THIS contract, and not
* the address of the submitter - if the constructor of the deployed contract
* uses msg.sender to set up ownership or other variables, you must modify it
* to accept a constructor argument with the appropriate address, or
* alternately to hard-code the intended address. Also, if your contract DOES
* have constructor arguments, remember to include them as ABI-encoded
* arguments at the end of the initialization code, just as you would when
* performing a standard deploy. You may want to provide the salt and
* submitter to `setDerivedReverseLookup` in order to find the salt,
* submitter, and derived key using only the home address to prevent
* accidentally losing them.
*/
function deriveKeyAndDeployViaExistingRuntimeStorageContract(
bytes32 salt,
address initializationRuntimeStorageContract
)
external
payable
returns (address homeAddress, bytes32 key, bytes32 runtimeCodeHash);
/**
* @notice Mint multiple ERC721 tokens, designated by their keys, to the
* specified owner. Keys that aren't controlled, or that point to home
* addresses that are currently deployed, will be skipped.
* @param owner address The account that will be granted ownership of the
* ERC721 tokens.
* @param keys bytes32[] An array of values used to derive each home address.
* @dev If you plan to use this method regularly or want to keep gas costs to
* an absolute minimum, and are willing to go without standard ABI encoding,
* see `batchLock_63efZf` for a more efficient (and unforgiving)
* implementation. For batch token minting with *derived* keys, see
* `deriveKeysAndBatchLock`.
*/
function batchLock(address owner, bytes32[] calldata keys) external;
/**
* @notice Mint multiple ERC721 tokens, designated by salts that are hashed
* with the caller's address to derive each key, to the specified owner.
* Derived keys that aren't controlled, or that point to home addresses that
* are currently deployed, will be skipped.
* @param owner address The account that will be granted ownership of the
* ERC721 tokens.
* @param salts bytes32[] An array of values used to derive each key and
* corresponding home address.
* @dev See `batchLock` for batch token minting with standard, non-derived
* keys.
*/
function deriveKeysAndBatchLock(address owner, bytes32[] calldata salts)
external;
/**
* @notice Efficient version of `batchLock` that uses less gas. The first 20
* bytes of each key are automatically populated using msg.sender, and the
* remaining key segments are passed in as a packed byte array, using twelve
* bytes per segment, with a function selector of 0x00000000 followed by a
* twenty-byte segment for the desired owner of the minted ERC721 tokens. Note
* that an attempt to lock a key that is not controlled or with its contract
* already deployed will cause the entire batch to revert. Checks on whether
* the owner is a valid ERC721 receiver are also skipped, similar to using
* `transferFrom` instead of `safeTransferFrom`.
*/
function batchLock_63efZf(/* packed owner and key segments */) external;
/**
* @notice Submit a key to claim the "high score" - the lower the uint160
* value of the key's home address, the higher the score. The high score
* holder has the exclusive right to recover lost ether and tokens on this
* contract.
* @param key bytes32 The unique value used to derive the home address that
* will determine the resultant score.
* @dev The high score must be claimed by a direct key (one that is submitted
* by setting the first 20 bytes of the key to the address of the submitter)
* and not by a derived key, and is non-transferrable. If you want to help
* people recover their lost tokens, you might consider deploying a contract
* to the high score address (probably a metamorphic one so that you can use
* the home address later) with your contact information.
*/
function claimHighScore(bytes32 key) external;
/**
* @notice Transfer any ether or ERC20 tokens that have somehow ended up at
* this contract by specifying a token address (set to the null address for
* ether) as well as a recipient address. Only the high score holder can
* recover lost ether and tokens on this contract.
* @param token address The contract address of the ERC20 token to recover, or
* the null address for recovering Ether.
* @param recipient address payable The account where recovered funds should
* be transferred.
* @dev If you are trying to recover funds that were accidentally sent into
* this contract, see if you can contact the holder of the current high score,
* found by calling `getHighScore`. Better yet, try to find a new high score
* yourself!
*/
function recover(IERC20 token, address payable recipient) external;
/**
* @notice "View" function to determine if a contract can currently be
* deployed to a home address given the corresponding key. A contract is only
* deployable if no account currently exists at the address - any existing
* contract must be destroyed via `SELFDESTRUCT` before a new contract can be
* deployed to a home address. This method does not modify state but is
* inaccessible via staticcall.
* @param key bytes32 The unique value used to derive the home address.
* @return A boolean signifying if a contract can be deployed to the home
* address that corresponds to the provided key.
* @dev This will not detect if a contract is not deployable due control
* having been relinquished on the key.
*/
function isDeployable(bytes32 key)
external
/* view */
returns (bool deployable);
/**
* @notice View function to get the current "high score", or the lowest
* uint160 value of a home address of all keys submitted. The high score
* holder has the exclusive right to recover lost ether and tokens on this
* contract.
* @return The current high score holder, their score, and the submitted key.
*/
function getHighScore()
external
view
returns (address holder, uint256 score, bytes32 key);
/**
* @notice View function to get information on a home address given the
* corresponding key.
* @param key bytes32 The unique value used to derive the home address.
* @return The home address, the current controller of the address, the number
* of times the home address has been deployed to, and the code hash of the
* runtime currently found at the home address, if any.
* @dev There is also an `isDeployable` method for determining if a contract
* can be deployed to the address, but in extreme cases it must actually
* perform a dry-run to determine if the contract is deployable, which means
* that it does not support staticcalls. There is also a convenience method,
* `hasNeverBeenDeployed`, but the information it conveys can be determined
* from this method alone as well.
*/
function getHomeAddressInformation(bytes32 key)
external
view
returns (
address homeAddress,
address controller,
uint256 deploys,
bytes32 currentRuntimeCodeHash
);
/**
* @notice View function to determine if no contract has ever been deployed to
* a home address given the corresponding key. This can be used to ensure that
* a given key or corresponding token is "new" or not.
* @param key bytes32 The unique value used to derive the home address.
* @return A boolean signifying if a contract has never been deployed using
* the supplied key before.
*/
function hasNeverBeenDeployed(bytes32 key)
external
view
returns (bool neverBeenDeployed);
/**
* @notice View function to search for a known key, salt, and/or submitter
* given a supplied home address. Keys can be controlled directly by an
* address that matches the first 20 bytes of the key, or they can be derived
* from a salt and a submitter - if the key is not a derived key, the salt and
* submitter fields will both have a value of zero.
* @param homeAddress address The home address to check for key information.
* @return The key, salt, and/or submitter used to deploy to the home address,
* assuming they have been submitted to the reverse lookup.
* @dev To populate these values, call `setReverseLookup` for cases where keys
* are used directly or are the only value known, or `setDerivedReverseLookup`
* for cases where keys are derived from a known salt and submitter.
*/
function reverseLookup(address homeAddress)
external
view
returns (bytes32 key, bytes32 salt, address submitter);
/**
* @notice Pure function to determine the key that is derived from a given
* salt and submitting address.
* @param salt bytes32 The salt value that is used to derive the key.
* @param submitter address The submitter of the salt value used to derive the
* key.
* @return The derived key.
*/
function getDerivedKey(bytes32 salt, address submitter)
external
pure
returns (bytes32 key);
/**
* @notice Pure function to determine the home address that corresponds to
* a given key.
* @param key bytes32 The unique value used to derive the home address.
* @return The home address.
*/
function getHomeAddress(bytes32 key)
external
pure
returns (address homeAddress);
/**
* @notice Pure function for retrieving the metamorphic initialization code
* used to deploy arbitrary contracts to home addresses. Provided for easy
* verification and for use in other applications.
* @return The 32-byte metamorphic initialization code.
* @dev This metamorphic init code works via the "metamorphic delegator"
* mechanism, which is explained in greater detail at `_deployToHomeAddress`.
*/
function getMetamorphicDelegatorInitializationCode()
external
pure
returns (bytes32 metamorphicDelegatorInitializationCode);
/**
* @notice Pure function for retrieving the keccak256 of the metamorphic
* initialization code used to deploy arbitrary contracts to home addresses.
* This is the value that you should use, along with this contract's address
* and a caller address that you control, to mine for an partucular type of
* home address (such as one at a compact or gas-efficient address).
* @return The keccak256 hash of the metamorphic initialization code.
*/
function getMetamorphicDelegatorInitializationCodeHash()
external
pure
returns (bytes32 metamorphicDelegatorInitializationCodeHash);
/**
* @notice Pure function for retrieving the prelude that will be inserted
* ahead of the code payload in order to deploy a runtime storage contract.
* @return The 11-byte "arbitrary runtime" prelude.
*/
function getArbitraryRuntimeCodePrelude()
external
pure
returns (bytes11 prelude);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721 {
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) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) external;
function safeTransferFrom(address from, address to, uint256 tokenId) external;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata {
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external
returns (bytes4);
}
/**
* @title ERC1412 Batch Transfers For Non-Fungible Tokens
* @dev the ERC-165 identifier for this interface is 0x2b89bcaa
*/
interface IERC1412 {
/// @notice Transfers the ownership of multiple NFTs from one address to another address
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenIds The NFTs to transfer
/// @param _data Additional data with no specified format, sent in call to `_to`
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds, bytes calldata _data) external;
/// @notice Transfers the ownership of multiple NFTs from one address to another address
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenIds The NFTs to transfer
function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _tokenIds) external;
}
/**
* @title IERC165
* @dev https://eips.ethereum.org/EIPS/eip-165
*/
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);
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
/**
* @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 () internal {
// 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 returns (bool) { //inject PUBLIC FUNC TO EXTERNAL
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 {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// 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 => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _INTERFACE_ID_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(_INTERFACE_ID_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].current();
}
/**
* @dev Gets the owner of the specified token ID
* @param tokenId uint256 ID of the token to query the owner of
* @return 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));
_transferFrom(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 {
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);
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return bool 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);
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
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
require(!_exists(tokenId));
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner);
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), 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
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @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) internal {
require(ownerOf(tokenId) == from);
require(to != address(0));
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @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 bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(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);
}
/**
* @dev Private function to clear current approval of a given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
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(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 Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @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), "ERC721Enumerable: owner index out of bounds");
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(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @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) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @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
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the _ownedTokensIndex mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length.sub(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
/**
* @title HomeWork (version 1)
* @author 0age
* @notice Homework is a utility to find, share, and reuse "home" addresses for
* contracts. Anyone can work to find a new home address by searching for keys,
* a 32-byte value with the first 20 bytes equal to the finder's calling address
* (or derived by hashing an arbitrary 32-byte salt and the caller's address),
* and can then deploy any contract they like (even one with a constructor) to
* the address, or mint an ERC721 token that the owner can redeem that will then
* allow them to do the same. Also, if the contract is `SELFDESTRUCT`ed, a new
* contract can be redeployed by the current controller to the same address!
* @dev This contract allows contract addresses to be located ahead of time, and
* for arbitrary bytecode to be deployed (and redeployed if so desired, i.e.
* metamorphic contracts) to the located address by a designated controller. To
* enable this, the contract first deploys an "initialization-code-in-runtime"
* contract, with the creation code of the contract you want to deploy stored in
* RUNTIME code. Then, to deploy the actual contract, it retrieves the address
* of the storage contract and `DELEGATECALL`s into it to execute the init code
* and, if successful, retrieves and returns the contract runtime code. Rather
* than using a located address directly, you can also lock it in the contract
* and mint and ERC721 token for it, which can then be redeemed in order to gain
* control over deployment to the address (note that tokens may not be minted if
* the contract they control currently has a deployed contract at that address).
* Once a contract undergoes metamorphosis, all existing storage will be deleted
* and any existing contract code will be replaced with the deployed contract
* code of the new implementation contract. The mechanisms behind this contract
* are highly experimental - proceed with caution and please share any exploits
* or optimizations you discover.
*/
contract HomeWork is IHomeWork, ERC721Enumerable, IERC721Metadata, IERC1412 {
// Allocate storage to track the current initialization-in-runtime contract.
address private _initializationRuntimeStorageContract;
// Finder of home address with lowest uint256 value can recover lost funds.
bytes32 private _highScoreKey;
// Track information on the Home address corresponding to each key.
mapping (bytes32 => HomeAddress) private _home;
// Provide optional reverse-lookup for key derivation of a given home address.
mapping (address => KeyInformation) private _key;
// Set 0xff + address(this) as a constant to use when deriving home addresses.
bytes21 private constant _FF_AND_THIS_CONTRACT = bytes21(
0xff0000000000001b84b1cb32787B0D64758d019317
);
// Set the address of the tokenURI runtime storage contract as a constant.
address private constant _URI_END_SEGMENT_STORAGE = address(
0x000000000071C1c84915c17BF21728BfE4Dac3f3
);
// Deploy arbitrary contracts to home addresses using metamorphic init code.
bytes32 private constant _HOME_INIT_CODE = bytes32(
0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
);
// Compute hash of above metamorphic init code in order to compute addresses.
bytes32 private constant _HOME_INIT_CODE_HASH = bytes32(
0x7816562e7f85866cae07183593075f3b5ec32aeff914a0693e20aaf39672babc
);
// Write arbitrary code to a contract's runtime using the following prelude.
bytes11 private constant _ARBITRARY_RUNTIME_PRELUDE = bytes11(
0x600b5981380380925939f3
);
// Set EIP165 interface IDs as constants (already set 165 and 721+enumerable).
bytes4 private constant _INTERFACE_ID_HOMEWORK = 0xe5399799;
/* this.deploy.selector ^ this.lock.selector ^ this.redeem.selector ^
this.assignController.selector ^ this.relinquishControl.selector ^
this.redeemAndDeploy.selector ^ this.deriveKey.selector ^
this.deriveKeyAndLock.selector ^
this.deriveKeyAndAssignController.selector ^
this.deriveKeyAndRelinquishControl.selector ^
this.setReverseLookup.selector ^ this.setDerivedReverseLookup.selector ^
this.deployRuntimeStorageContract.selector ^
this.deployViaExistingRuntimeStorageContract.selector ^
this.redeemAndDeployViaExistingRuntimeStorageContract.selector ^
this.deriveKeyAndDeploy.selector ^
this.deriveKeyAndDeployViaExistingRuntimeStorageContract.selector ^
this.batchLock.selector ^ this.deriveKeysAndBatchLock.selector ^
this.batchLock_63efZf.selector ^ this.claimHighScore.selector ^
this.recover.selector ^ this.isDeployable.selector ^
this.getHighScore.selector ^ this.getHomeAddressInformation.selector ^
this.hasNeverBeenDeployed.selector ^ this.reverseLookup.selector ^
this.getDerivedKey.selector ^ this.getHomeAddress.selector ^
this.getMetamorphicDelegatorInitializationCode.selector ^
this.getMetamorphicDelegatorInitializationCodeHash.selector ^
this.getArbitraryRuntimeCodePrelude.selector == 0xe5399799
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC1412_BATCH_TRANSFERS = 0x2b89bcaa;
// Set name of this contract as a constant (hex encoding is to support emoji).
string private constant _NAME = (
hex"486f6d65576f726b20f09f8fa0f09f9ba0efb88f"
);
// Set symbol of this contract as a constant.
string private constant _SYMBOL = "HWK";
// Set the start of each token URI for issued ERC721 tokens as a constant.
bytes private constant _URI_START_SEGMENT = abi.encodePacked(
hex"646174613a6170706c69636174696f6e2f6a736f6e2c7b226e616d65223a22486f6d65",
hex"253230416464726573732532302d2532303078"
); /* data:application/json,{"name":"Home%20Address%20-%200x */
// Store reused revert messages as constants.
string private constant _ACCOUNT_EXISTS = string(
"Only non-existent accounts can be deployed or used to mint tokens."
);
string private constant _ONLY_CONTROLLER = string(
"Only the designated controller can call this function."
);
string private constant _NO_INIT_CODE_SUPPLIED = string(
"Cannot deploy a contract with no initialization code supplied."
);
/**
* @notice In the constructor, verify that deployment addresses are correct
* and that supplied constant hash value of the contract creation code used to
* deploy arbitrary contracts to home addresses is valid, and set an initial
* high score key with the null address as the high score "holder". ERC165
* supported interfaces are all registered during initizialization as well.
*/
constructor() public {
// Verify that the deployment address is set correctly as a constant.
assert(address(this) == address(uint160(uint168(_FF_AND_THIS_CONTRACT))));
// Verify the derivation of the deployment address.
bytes32 initialDeployKey = bytes32(
0x486f6d65576f726b20f09f8fa0f09f9ba0efb88faa3c548a76f9bd3c000c0000
);
assert(address(this) == address(
uint160( // Downcast to match the address type.
uint256( // Convert to uint to truncate upper digits.
keccak256( // Compute the CREATE2 hash using 4 inputs.
abi.encodePacked( // Pack all inputs to the hash together.
bytes1(0xff), // Start with 0xff to distinguish from RLP.
msg.sender, // The deployer will be the caller.
initialDeployKey, // Pass in the supplied key as the salt.
_HOME_INIT_CODE_HASH // The metamorphic initialization code hash.
)
)
)
)
));
// Verify the derivation of the tokenURI runtime storage address.
bytes32 uriDeployKey = bytes32(
0x486f6d65576f726b202d20746f6b656e55524920c21352fee5a62228db000000
);
bytes32 uriInitCodeHash = bytes32(
0xdea98294867e3fdc48eb5975ecc53a79e2e1ea6e7e794137a9c34c4dd1565ba2
);
assert(_URI_END_SEGMENT_STORAGE == address(
uint160( // Downcast to match the address type.
uint256( // Convert to uint to truncate upper digits.
keccak256( // Compute the CREATE2 hash using 4 inputs.
abi.encodePacked( // Pack all inputs to the hash together.
bytes1(0xff), // Start with 0xff to distinguish from RLP.
msg.sender, // The deployer will be the caller.
uriDeployKey, // Pass in the supplied key as the salt.
uriInitCodeHash // The storage contract init code hash.
)
)
)
)
));
// Verify that the correct runtime code is at the tokenURI storage contract.
bytes32 expectedRuntimeStorageHash = bytes32(
0x8834602968080bb1df9c44c9834c0a93533b72bbfa3865ee2c5be6a0c4125fc3
);
address runtimeStorage = _URI_END_SEGMENT_STORAGE;
bytes32 runtimeStorageHash;
assembly { runtimeStorageHash := extcodehash(runtimeStorage) }
assert(runtimeStorageHash == expectedRuntimeStorageHash);
// Verify that the supplied hash for the metamorphic init code is valid.
assert(keccak256(abi.encode(_HOME_INIT_CODE)) == _HOME_INIT_CODE_HASH);
// Set an initial high score key with the null address as the submitter.
_highScoreKey = bytes32(
0x0000000000000000000000000000000000000000ffffffffffffffffffffffff
);
// Register EIP165 interface for HomeWork.
_registerInterface(_INTERFACE_ID_HOMEWORK);
// Register EIP165 interface for ERC721 metadata.
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
// Register EIP165 interface for ERC1412 (batch transfers).
_registerInterface(_INTERFACE_ID_ERC1412_BATCH_TRANSFERS);
}
/**
* @notice Deploy a new contract with the desired initialization code to the
* home address corresponding to a given key. Two conditions must be met: the
* submitter must be designated as the controller of the home address (with
* the initial controller set to the address corresponding to the first twenty
* bytes of the key), and there must not be a contract currently deployed at
* the home address. These conditions can be checked by calling
* `getHomeAddressInformation` and `isDeployable` with the same key.
* @param key bytes32 The unique value used to derive the home address.
* @param initializationCode bytes The contract creation code that will be
* used to deploy the contract to the home address.
* @return The home address of the deployed contract.
* @dev In order to deploy the contract to the home address, a new contract
* will be deployed with runtime code set to the initialization code of the
* contract that will be deployed to the home address. Then, metamorphic
* initialization code will retrieve that initialization code and use it to
* set up and deploy the desired contract to the home address. Bear in mind
* that the deployed contract will interpret msg.sender as the address of THIS
* contract, and not the address of the submitter - if the constructor of the
* deployed contract uses msg.sender to set up ownership or other variables,
* you must modify it to accept a constructor argument with the appropriate
* address, or alternately to hard-code the intended address. Also, if your
* contract DOES have constructor arguments, remember to include them as
* ABI-encoded arguments at the end of the initialization code, just as you
* would when performing a standard deploy. You may also want to provide the
* key to `setReverseLookup` in order to find it again using only the home
* address to prevent accidentally losing the key.
*/
function deploy(bytes32 key, bytes calldata initializationCode)
external
payable
onlyEmpty(key)
onlyControllerDeployer(key)
returns (address homeAddress, bytes32 runtimeCodeHash)
{
// Ensure that initialization code was supplied.
require(initializationCode.length > 0, _NO_INIT_CODE_SUPPLIED);
// Deploy the initialization storage contract and set address in storage.
_initializationRuntimeStorageContract = _deployRuntimeStorageContract(
initializationCode
);
// Use metamorphic initialization code to deploy contract to home address.
(homeAddress, runtimeCodeHash) = _deployToHomeAddress(key);
}
/**
* @notice Mint an ERC721 token to the supplied owner that can be redeemed in
* order to gain control of a home address corresponding to a given key. Two
* conditions must be met: the submitter must be designated as the controller
* of the home address (with the initial controller set to the address
* corresponding to the first 20 bytes of the key), and there must not be a
* contract currently deployed at the home address. These conditions can be
* checked by calling `getHomeAddressInformation` and `isDeployable` with the
* same key.
* @param key bytes32 The unique value used to derive the home address.
* @param owner address The account that will be granted ownership of the
* ERC721 token.
* @dev In order to mint an ERC721 token, the assocated home address cannot be
* in use, or else the token will not be able to deploy to the home address.
* The controller is set to this contract until the token is redeemed, at
* which point the redeemer designates a new controller for the home address.
* The key of the home address and the tokenID of the ERC721 token are the
* same value, but different types (bytes32 vs. uint256).
*/
function lock(bytes32 key, address owner)
public //inject PUBLIC FUNC TO EXTERNAL
onlyEmpty(key)
onlyController(key)
{
// Ensure that the specified owner is a valid ERC721 receiver.
_validateOwner(owner, key);
// Get the HomeAddress storage struct from the mapping using supplied key.
HomeAddress storage home = _home[key];
// Set the exists flag to true and the controller to this contract.
home.exists = true;
home.controller = address(this);
// Emit an event signifying that this contract is now the controller.
emit NewController(key, address(this));
// Mint the ERC721 token to the designated owner.
_mint(owner, uint256(key));
}
/**
* @notice Burn an ERC721 token to allow the supplied controller to gain the
* ability to deploy to the home address corresponding to the key matching the
* burned token. The submitter must be designated as either the owner of the
* token or as an approved spender.
* @param tokenId uint256 The ID of the ERC721 token to redeem.
* @param controller address The account that will be granted control of the
* home address corresponding to the given token.
* @dev The controller cannot be designated as the address of this contract,
* the null address, or the home address (the restriction on setting the home
* address as the controller is due to the fact that the home address will not
* be able to deploy to itself, as it needs to be empty before a contract can
* be deployed to it).
*/
function redeem(uint256 tokenId, address controller)
public //inject PUBLIC FUNC TO EXTERNAL
onlyTokenOwnerOrApprovedSpender(tokenId)
{
// Convert the token ID to a bytes32 key.
bytes32 key = bytes32(tokenId);
// Prevent the controller from being set to prohibited account values.
_validateController(controller, key);
// Burn the ERC721 token in question.
_burn(tokenId);
// Assign the new controller to the corresponding home address.
_home[key].controller = controller;
// Emit an event with the new controller.
emit NewController(key, controller);
}
/**
* @notice Transfer control over deployment to the home address corresponding
* to a given key. The caller must be designated as the current controller of
* the home address (with the initial controller set to the address
* corresponding to the first 20 bytes of the key) - This condition can be
* checked by calling `getHomeAddressInformation` with the same key.
* @param key bytes32 The unique value used to derive the home address.
* @param controller address The account that will be granted control of the
* home address corresponding to the given key.
* @dev The controller cannot be designated as the address of this contract,
* the null address, or the home address (the restriction on setting the home
* address as the controller is due to the fact that the home address will not
* be able to deploy to itself, as it needs to be empty before a contract can
* be deployed to it).
*/
function assignController(bytes32 key, address controller)
public //inject PUBLIC FUNC TO EXTERNAL
onlyController(key)
{
// Prevent the controller from being set to prohibited account values.
_validateController(controller, key);
// Assign the new controller to the corresponding home address.
HomeAddress storage home = _home[key];
home.exists = true;
home.controller = controller;
// Emit an event with the new controller.
emit NewController(key, controller);
}
/**
* @notice Transfer control over deployment to the home address corresponding
* to a given key to the null address, which will prevent it from being
* deployed to again in the future. The caller must be designated as the
* current controller of the corresponding home address (with the initial
* controller set to the address corresponding to the first 20 bytes of the
* key) - This condition can be checked by calling `getHomeAddressInformation`
* with the same key.
* @param key bytes32 The unique value used to derive the home address.
*/
function relinquishControl(bytes32 key)
public //inject PUBLIC FUNC TO EXTERNAL
onlyController(key)
{
// Assign the null address as the controller of the given key.
HomeAddress storage home = _home[key];
home.exists = true;
home.controller = address(0);
// Emit an event with the null address as the controller.
emit NewController(key, address(0));
}
/**
* @notice Burn an ERC721 token, set a supplied controller, and deploy a new
* contract with the supplied initialization code to the corresponding home
* address for the given token. The submitter must be designated as either the
* owner of the token or as an approved spender.
* @param tokenId uint256 The ID of the ERC721 token to redeem.
* @param controller address The account that will be granted control of the
* home address corresponding to the given token.
* @param initializationCode bytes The contract creation code that will be
* used to deploy the contract to the home address.
* @return The home address and runtime code hash of the deployed contract.
* @dev In order to deploy the contract to the home address, a new contract
* will be deployed with runtime code set to the initialization code of the
* contract that will be deployed to the home address. Then, metamorphic
* initialization code will retrieve that initialization code and use it to
* set up and deploy the desired contract to the home address. Bear in mind
* that the deployed contract will interpret msg.sender as the address of THIS
* contract, and not the address of the submitter - if the constructor of the
* deployed contract uses msg.sender to set up ownership or other variables,
* you must modify it to accept a constructor argument with the appropriate
* address, or alternately to hard-code the intended address. Also, if your
* contract DOES have constructor arguments, remember to include them as
* ABI-encoded arguments at the end of the initialization code, just as you
* would when performing a standard deploy. You may also want to provide the
* key to `setReverseLookup` in order to find it again using only the home
* address to prevent accidentally losing the key. The controller cannot be
* designated as the address of this contract, the null address, or the home
* address (the restriction on setting the home address as the controller is
* due to the fact that the home address will not be able to deploy to itself,
* as it needs to be empty before a contract can be deployed to it). Also,
* checks on the contract at the home address being empty or not having the
* correct controller are unnecessary, as they are performed when minting the
* token and cannot be altered until the token is redeemed.
*/
function redeemAndDeploy(
uint256 tokenId,
address controller,
bytes calldata initializationCode
)
external
payable
onlyTokenOwnerOrApprovedSpender(tokenId)
returns (address homeAddress, bytes32 runtimeCodeHash)
{
// Ensure that initialization code was supplied.
require(initializationCode.length > 0, _NO_INIT_CODE_SUPPLIED);
// Convert the token ID to a bytes32 key.
bytes32 key = bytes32(tokenId);
// Prevent the controller from being set to prohibited account values.
_validateController(controller, key);
// Burn the ERC721 token in question.
_burn(tokenId);
// Deploy the initialization storage contract and set address in storage.
_initializationRuntimeStorageContract = _deployRuntimeStorageContract(
initializationCode
);
// Set provided controller and increment contract deploy count at once.
HomeAddress storage home = _home[key];
home.exists = true;
home.controller = controller;
home.deploys += 1;
// Emit an event with the new controller.
emit NewController(key, controller);
// Use metamorphic initialization code to deploy contract to home address.
(homeAddress, runtimeCodeHash) = _deployToHomeAddress(key);
}
/**
* @notice Derive a new key by concatenating an arbitrary 32-byte salt value
* and the address of the caller and performing a keccak256 hash. This allows
* for the creation of keys with additional entropy where desired while also
* preventing collisions with standard keys. The caller will be set as the
* controller of the derived key.
* @param salt bytes32 The desired salt value to use (along with the address
* of the caller) when deriving the resultant key and corresponding home
* address.
* @return The derived key.
* @dev Home addresses from derived keys will take longer to "mine" or locate,
* as an additional hash must be performed when computing the corresponding
* home address for each given salt input. Each caller will derive a different
* key even if they are supplying the same salt value.
*/
function deriveKey(bytes32 salt) public returns (bytes32 key) { //inject PUBLIC FUNC TO EXTERNAL
// Derive the key using the supplied salt and the calling address.
key = _deriveKey(salt, msg.sender);
// Register key and set caller as controller if it is not yet registered.
HomeAddress storage home = _home[key];
if (!home.exists) {
home.exists = true;
home.controller = msg.sender;
// Emit an event with the sender as the new controller.
emit NewController(key, msg.sender);
}
}
/**
* @notice Mint an ERC721 token to the supplied owner that can be redeemed in
* order to gain control of a home address corresponding to a given derived
* key. Two conditions must be met: the submitter must be designated as the
* current controller of the home address, and there must not be a contract
* currently deployed at the home address. These conditions can be checked by
* calling `getHomeAddressInformation` and `isDeployable` with the key
* determined by calling `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @param owner address The account that will be granted ownership of the
* ERC721 token.
* @return The derived key.
* @dev In order to mint an ERC721 token, the assocated home address cannot be
* in use, or else the token will not be able to deploy to the home address.
* The controller is set to this contract until the token is redeemed, at
* which point the redeemer designates a new controller for the home address.
* The key of the home address and the tokenID of the ERC721 token are the
* same value, but different types (bytes32 vs. uint256).
*/
function deriveKeyAndLock(bytes32 salt, address owner)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bytes32 key)
{
// Derive the key using the supplied salt and the calling address.
key = _deriveKey(salt, msg.sender);
// Ensure that the specified owner is a valid ERC721 receiver.
_validateOwner(owner, key);
// Ensure that a contract is not currently deployed to the home address.
require(_isNotDeployed(key), _ACCOUNT_EXISTS);
// Ensure that the caller is the controller of the derived key.
HomeAddress storage home = _home[key];
if (home.exists) {
require(home.controller == msg.sender, _ONLY_CONTROLLER);
}
// Set the exists flag to true and the controller to this contract.
home.exists = true;
home.controller = address(this);
// Mint the ERC721 token to the designated owner.
_mint(owner, uint256(key));
// Emit an event signifying that this contract is now the controller.
emit NewController(key, address(this));
}
/**
* @notice Transfer control over deployment to the home address corresponding
* to a given derived key. The caller must be designated as the current
* controller of the home address - This condition can be checked by calling
* `getHomeAddressInformation` with the key obtained via `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @param controller address The account that will be granted control of the
* home address corresponding to the given derived key.
* @return The derived key.
* @dev The controller cannot be designated as the address of this contract,
* the null address, or the home address (the restriction on setting the home
* address as the controller is due to the fact that the home address will not
* be able to deploy to itself, as it needs to be empty before a contract can
* be deployed to it).
*/
function deriveKeyAndAssignController(bytes32 salt, address controller)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bytes32 key)
{
// Derive the key using the supplied salt and the calling address.
key = _deriveKey(salt, msg.sender);
// Prevent the controller from being set to prohibited account values.
_validateController(controller, key);
// Ensure that the caller is the controller of the derived key.
HomeAddress storage home = _home[key];
if (home.exists) {
require(home.controller == msg.sender, _ONLY_CONTROLLER);
}
// Assign the new controller to the corresponding home address.
home.exists = true;
home.controller = controller;
// Emit an event with the new controller.
emit NewController(key, controller);
}
/**
* @notice Transfer control over deployment to the home address corresponding
* to a given derived key to the null address, which will prevent it from
* being deployed to again in the future. The caller must be designated as the
* current controller of the home address - This condition can be checked by
* calling `getHomeAddressInformation` with the key determined by calling
* `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @return The derived key.
*/
function deriveKeyAndRelinquishControl(bytes32 salt)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bytes32 key)
{
// Derive the key using the supplied salt and the calling address.
key = _deriveKey(salt, msg.sender);
// Ensure that the caller is the controller of the derived key.
HomeAddress storage home = _home[key];
if (home.exists) {
require(home.controller == msg.sender, _ONLY_CONTROLLER);
}
// Assign the null address as the controller of the given derived key.
home.exists = true;
home.controller = address(0);
// Emit an event with the null address as the controller.
emit NewController(key, address(0));
}
/**
* @notice Record a key that corresponds to a given home address by supplying
* said key and using it to derive the address. This enables reverse lookup
* of a key using only the home address in question. This method may be called
* by anyone - control of the key is not required.
* @param key bytes32 The unique value used to derive the home address.
* @dev This does not set the salt or submitter fields, as those apply only to
* derived keys (although a derived key may also be set with this method, just
* without the derived fields).
*/
function setReverseLookup(bytes32 key) public { //inject PUBLIC FUNC TO EXTERNAL
// Derive home address of given key and set home address and key in mapping.
_key[_getHomeAddress(key)].key = key;
}
/**
* @notice Record the derived key that corresponds to a given home address by
* supplying the salt and submitter that were used to derive the key. This
* facititates reverse lookup of the derivation method of a key using only the
* home address in question. This method may be called by anyone - control of
* the derived key is not required.
* @param salt bytes32 The salt value that is used to derive the key.
* @param submitter address The account that submits the salt that is used to
* derive the key.
*/
function setDerivedReverseLookup(bytes32 salt, address submitter) public { //inject PUBLIC FUNC TO EXTERNAL
// Derive the key using the supplied salt and submitter.
bytes32 key = _deriveKey(salt, submitter);
// Derive home address and set it along with all other relevant information.
_key[_getHomeAddress(key)] = KeyInformation({
key: key,
salt: salt,
submitter: submitter
});
}
/**
* @notice Deploy a new storage contract with the supplied code as runtime
* code without deploying a contract to a home address. This can be used to
* store the contract creation code for use in future deployments of contracts
* to home addresses.
* @param codePayload bytes The code to set as the runtime code of the
* deployed contract.
* @return The address of the deployed storage contract.
* @dev Consider placing adequate protections on the storage contract to
* prevent unwanted callers from modifying or destroying it. Also, if you are
* placing contract contract creation code into the runtime storage contract,
* remember to include any constructor parameters as ABI-encoded arguments at
* the end of the contract creation code, similar to how you would perform a
* standard deployment.
*/
function deployRuntimeStorageContract(bytes calldata codePayload)
external
returns (address runtimeStorageContract)
{
// Ensure that a code payload was supplied.
require(codePayload.length > 0, "No runtime code payload supplied.");
// Deploy payload to the runtime storage contract and return the address.
runtimeStorageContract = _deployRuntimeStorageContract(codePayload);
}
/**
* @notice Deploy a new contract with the initialization code stored in the
* runtime code at the specified initialization runtime storage contract to
* the home address corresponding to a given key. Two conditions must be met:
* the submitter must be designated as the controller of the home address
* (with the initial controller set to the address corresponding to the first
* 20 bytes of the key), and there must not be a contract currently deployed
* at the home address. These conditions can be checked by calling
* `getHomeAddressInformation` and `isDeployable` with the same key.
* @param key bytes32 The unique value used to derive the home address.
* @param initializationRuntimeStorageContract address The storage contract
* with runtime code equal to the contract creation code that will be used to
* deploy the contract to the home address.
* @return The home address and runtime code hash of the deployed contract.
* @dev When deploying a contract to a home address via this method, the
* metamorphic initialization code will retrieve whatever initialization code
* currently resides at the specified address and use it to set up and deploy
* the desired contract to the home address. Bear in mind that the deployed
* contract will interpret msg.sender as the address of THIS contract, and not
* the address of the submitter - if the constructor of the deployed contract
* uses msg.sender to set up ownership or other variables, you must modify it
* to accept a constructor argument with the appropriate address, or
* alternately to hard-code the intended address. Also, if your contract DOES
* have constructor arguments, remember to include them as ABI-encoded
* arguments at the end of the initialization code, just as you would when
* performing a standard deploy. You may also want to provide the key to
* `setReverseLookup` in order to find it again using only the home address to
* prevent accidentally losing the key.
*/
function deployViaExistingRuntimeStorageContract(
bytes32 key,
address initializationRuntimeStorageContract
)
public //inject PUBLIC FUNC TO EXTERNAL
payable
onlyEmpty(key)
onlyControllerDeployer(key)
returns (address homeAddress, bytes32 runtimeCodeHash)
{
// Ensure that the supplied runtime storage contract is not empty.
_validateRuntimeStorageIsNotEmpty(initializationRuntimeStorageContract);
// Set initialization runtime storage contract address in contract storage.
_initializationRuntimeStorageContract = initializationRuntimeStorageContract;
// Use metamorphic initialization code to deploy contract to home address.
(homeAddress, runtimeCodeHash) = _deployToHomeAddress(key);
}
/**
* @notice Burn an ERC721 token, set a supplied controller, and deploy a new
* contract with the initialization code stored in the runtime code at the
* specified initialization runtime storage contract to the home address
* corresponding to a given key. The submitter must be designated as either
* the owner of the token or as an approved spender.
* @param tokenId uint256 The ID of the ERC721 token to redeem.
* @param controller address The account that will be granted control of the
* home address corresponding to the given token.
* @param initializationRuntimeStorageContract address The storage contract
* with runtime code equal to the contract creation code that will be used to
* deploy the contract to the home address.
* @return The home address and runtime code hash of the deployed contract.
* @dev When deploying a contract to a home address via this method, the
* metamorphic initialization code will retrieve whatever initialization code
* currently resides at the specified address and use it to set up and deploy
* the desired contract to the home address. Bear in mind that the deployed
* contract will interpret msg.sender as the address of THIS contract, and not
* the address of the submitter - if the constructor of the deployed contract
* uses msg.sender to set up ownership or other variables, you must modify it
* to accept a constructor argument with the appropriate address, or
* alternately to hard-code the intended address. Also, if your contract DOES
* have constructor arguments, remember to include them as ABI-encoded
* arguments at the end of the initialization code, just as you would when
* performing a standard deploy. You may also want to provide the key to
* `setReverseLookup` in order to find it again using only the home address to
* prevent accidentally losing the key. The controller cannot be designated as
* the address of this contract, the null address, or the home address (the
* restriction on setting the home address as the controller is due to the
* fact that the home address will not be able to deploy to itself, as it
* needs to be empty before a contract can be deployed to it). Also, checks on
* the contract at the home address being empty or not having the correct
* controller are unnecessary, as they are performed when minting the token
* and cannot be altered until the token is redeemed.
*/
function redeemAndDeployViaExistingRuntimeStorageContract(
uint256 tokenId,
address controller,
address initializationRuntimeStorageContract
)
public //inject PUBLIC FUNC TO EXTERNAL
payable
onlyTokenOwnerOrApprovedSpender(tokenId)
returns (address homeAddress, bytes32 runtimeCodeHash)
{
// Ensure that the supplied runtime storage contract is not empty.
_validateRuntimeStorageIsNotEmpty(initializationRuntimeStorageContract);
// Convert the token ID to a bytes32 key.
bytes32 key = bytes32(tokenId);
// Prevent the controller from being set to prohibited account values.
_validateController(controller, key);
// Burn the ERC721 token in question.
_burn(tokenId);
// Set initialization runtime storage contract address in contract storage.
_initializationRuntimeStorageContract = initializationRuntimeStorageContract;
// Set provided controller and increment contract deploy count at once.
HomeAddress storage home = _home[key];
home.exists = true;
home.controller = controller;
home.deploys += 1;
// Emit an event with the new controller.
emit NewController(key, controller);
// Use metamorphic initialization code to deploy contract to home address.
(homeAddress, runtimeCodeHash) = _deployToHomeAddress(key);
}
/**
* @notice Deploy a new contract with the desired initialization code to the
* home address corresponding to a given derived key. Two conditions must be
* met: the submitter must be designated as the controller of the home
* address, and there must not be a contract currently deployed at the home
* address. These conditions can be checked by calling
* `getHomeAddressInformation` and `isDeployable` with the key obtained by
* calling `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @param initializationCode bytes The contract creation code that will be
* used to deploy the contract to the home address.
* @return The home address, derived key, and runtime code hash of the
* deployed contract.
* @dev In order to deploy the contract to the home address, a new contract
* will be deployed with runtime code set to the initialization code of the
* contract that will be deployed to the home address. Then, metamorphic
* initialization code will retrieve that initialization code and use it to
* set up and deploy the desired contract to the home address. Bear in mind
* that the deployed contract will interpret msg.sender as the address of THIS
* contract, and not the address of the submitter - if the constructor of the
* deployed contract uses msg.sender to set up ownership or other variables,
* you must modify it to accept a constructor argument with the appropriate
* address, or alternately to hard-code the intended address. Also, if your
* contract DOES have constructor arguments, remember to include them as
* ABI-encoded arguments at the end of the initialization code, just as you
* would when performing a standard deploy. You may want to provide the salt
* and submitter to `setDerivedReverseLookup` in order to find the salt,
* submitter, and derived key using only the home address to prevent
* accidentally losing them.
*/
function deriveKeyAndDeploy(bytes32 salt, bytes calldata initializationCode)
external
payable
returns (address homeAddress, bytes32 key, bytes32 runtimeCodeHash)
{
// Ensure that initialization code was supplied.
require(initializationCode.length > 0, _NO_INIT_CODE_SUPPLIED);
// Derive key and prepare to deploy using supplied salt and calling address.
key = _deriveKeyAndPrepareToDeploy(salt);
// Deploy the initialization storage contract and set address in storage.
_initializationRuntimeStorageContract = _deployRuntimeStorageContract(
initializationCode
);
// Use metamorphic initialization code to deploy contract to home address.
(homeAddress, runtimeCodeHash) = _deployToHomeAddress(key);
}
/**
* @notice Deploy a new contract with the initialization code stored in the
* runtime code at the specified initialization runtime storage contract to
* the home address corresponding to a given derived key. Two conditions must
* be met: the submitter must be designated as the controller of the home
* address, and there must not be a contract currently deployed at the home
* address. These conditions can be checked by calling
* `getHomeAddressInformation` and `isDeployable` with the key obtained by
* calling `getDerivedKey`.
* @param salt bytes32 The salt value that is used to derive the key.
* @param initializationRuntimeStorageContract address The storage contract
* with runtime code equal to the contract creation code that will be used to
* deploy the contract to the home address.
* @return The home address, derived key, and runtime code hash of the
* deployed contract.
* @dev When deploying a contract to a home address via this method, the
* metamorphic initialization code will retrieve whatever initialization code
* currently resides at the specified address and use it to set up and deploy
* the desired contract to the home address. Bear in mind that the deployed
* contract will interpret msg.sender as the address of THIS contract, and not
* the address of the submitter - if the constructor of the deployed contract
* uses msg.sender to set up ownership or other variables, you must modify it
* to accept a constructor argument with the appropriate address, or
* alternately to hard-code the intended address. Also, if your contract DOES
* have constructor arguments, remember to include them as ABI-encoded
* arguments at the end of the initialization code, just as you would when
* performing a standard deploy. You may want to provide the salt and
* submitter to `setDerivedReverseLookup` in order to find the salt,
* submitter, and derived key using only the home address to prevent
* accidentally losing them.
*/
function deriveKeyAndDeployViaExistingRuntimeStorageContract(
bytes32 salt,
address initializationRuntimeStorageContract
)
public //inject PUBLIC FUNC TO EXTERNAL
payable
returns (address homeAddress, bytes32 key, bytes32 runtimeCodeHash)
{
// Ensure that the supplied runtime storage contract is not empty.
_validateRuntimeStorageIsNotEmpty(initializationRuntimeStorageContract);
// Derive key and prepare to deploy using supplied salt and calling address.
key = _deriveKeyAndPrepareToDeploy(salt);
// Set the initialization runtime storage contract in contract storage.
_initializationRuntimeStorageContract = initializationRuntimeStorageContract;
// Use metamorphic initialization code to deploy contract to home address.
(homeAddress, runtimeCodeHash) = _deployToHomeAddress(key);
}
/**
* @notice Mint multiple ERC721 tokens, designated by their keys, to the
* specified owner. Keys that aren't controlled, or that point to home
* addresses that are currently deployed, will be skipped.
* @param owner address The account that will be granted ownership of the
* ERC721 tokens.
* @param keys bytes32[] An array of values used to derive each home address.
* @dev If you plan to use this method regularly or want to keep gas costs to
* an absolute minimum, and are willing to go without standard ABI encoding,
* see `batchLock_63efZf` for a more efficient (and unforgiving)
* implementation. For batch token minting with *derived* keys, see
* `deriveKeysAndBatchLock`.
*/
function batchLock(address owner, bytes32[] calldata keys) external {
// Track each key in the array of keys.
bytes32 key;
// Ensure that the specified owner is a valid ERC721 receiver.
if (keys.length > 0) {
_validateOwner(owner, keys[0]);
}
// Iterate through each provided key argument.
for (uint256 i; i < keys.length; i++) {
key = keys[i];
// Skip if the key currently has a contract deployed to its home address.
if (!_isNotDeployed(key)) {
continue;
}
// Skip if the caller is not the controller.
if (_getController(key) != msg.sender) {
continue;
}
// Set the exists flag to true and the controller to this contract.
HomeAddress storage home = _home[key];
home.exists = true;
home.controller = address(this);
// Emit an event signifying that this contract is now the controller.
emit NewController(key, address(this));
// Mint the ERC721 token to the designated owner.
_mint(owner, uint256(key));
}
}
/**
* @notice Mint multiple ERC721 tokens, designated by salts that are hashed
* with the caller's address to derive each key, to the specified owner.
* Derived keys that aren't controlled, or that point to home addresses that
* are currently deployed, will be skipped.
* @param owner address The account that will be granted ownership of the
* ERC721 tokens.
* @param salts bytes32[] An array of values used to derive each key and
* corresponding home address.
* @dev See `batchLock` for batch token minting with standard, non-derived
* keys.
*/
function deriveKeysAndBatchLock(address owner, bytes32[] calldata salts)
external
{
// Track each key derived from the array of salts.
bytes32 key;
// Ensure that the specified owner is a valid ERC721 receiver.
if (salts.length > 0) {
_validateOwner(owner, _deriveKey(salts[0], msg.sender));
}
// Iterate through each provided salt argument.
for (uint256 i; i < salts.length; i++) {
// Derive the key using the supplied salt and the calling address.
key = _deriveKey(salts[i], msg.sender);
// Skip if the key currently has a contract deployed to its home address.
if (!_isNotDeployed(key)) {
continue;
}
// Skip if the caller is not the controller.
HomeAddress storage home = _home[key];
if (home.exists && home.controller != msg.sender) {
continue;
}
// Set the exists flag to true and the controller to this contract.
home.exists = true;
home.controller = address(this);
// Emit an event signifying that this contract is now the controller.
emit NewController(key, address(this));
// Mint the ERC721 token to the designated owner.
_mint(owner, uint256(key));
}
}
/**
* @notice Safely transfers the ownership of a group of token IDs to another
* address in a batch. If the target address is a contract, it must implement
* `onERC721Received`, called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`;
* otherwise, or if another error occurs, the entire batch is reverted.
* Requires msg.sender to be the owner, approved, or operator of the tokens.
* @param from address The current owner of the tokens.
* @param to address The account to receive ownership of the given tokens.
* @param tokenIds uint256[] ID of the tokens to be transferred.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata tokenIds
)
external
{
// Track each token ID in the batch.
uint256 tokenId;
// Iterate over each supplied token ID.
for (uint256 i = 0; i < tokenIds.length; i++) {
// Set the current token ID.
tokenId = tokenIds[i];
// Perform the token transfer.
safeTransferFrom(from, to, tokenId);
}
}
/**
* @notice Safely transfers the ownership of a group of token IDs to another
* address in a batch. If the target address is a contract, it must implement
* `onERC721Received`, called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`;
* otherwise, or if another error occurs, the entire batch is reverted.
* Requires msg.sender to be the owner, approved, or operator of the tokens.
* @param from address The current owner of the tokens.
* @param to address The account to receive ownership of the given tokens.
* @param tokenIds uint256[] ID of the tokens to be transferred.
* @param data bytes A data payload to include with each transfer.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata tokenIds,
bytes calldata data
)
external
{
// Track each token ID in the batch.
uint256 tokenId;
// Iterate over each supplied token ID.
for (uint256 i = 0; i < tokenIds.length; i++) {
// Set the current token ID.
tokenId = tokenIds[i];
// Perform the token transfer.
safeTransferFrom(from, to, tokenId, data);
}
}
/**
* @notice Efficient version of `batchLock` that uses less gas. The first 20
* bytes of each key are automatically populated using msg.sender, and the
* remaining key segments are passed in as a packed byte array, using twelve
* bytes per segment, with a function selector of 0x00000000 followed by a
* twenty-byte segment for the desired owner of the minted ERC721 tokens. Note
* that an attempt to lock a key that is not controlled or with its contract
* already deployed will cause the entire batch to revert. Checks on whether
* the owner is a valid ERC721 receiver are also skipped, similar to using
* `transferFrom` instead of `safeTransferFrom`.
*/
function batchLock_63efZf(/* packed owner and key segments */) public { //inject PUBLIC FUNC TO EXTERNAL
// Get the owner from calldata, located at bytes 4-23 (sig is bytes 0-3).
address owner;
// Determine number of 12-byte key segments in calldata from byte 24 on.
uint256 passedSaltSegments;
// Get the owner and calculate the total number of key segments.
assembly {
owner := shr(0x60, calldataload(4)) // comes after sig
passedSaltSegments := div(sub(calldatasize, 24), 12) // after sig & owner
}
// Track each key, located at each 12-byte segment from byte 24 on.
bytes32 key;
// Iterate through each provided key segment argument.
for (uint256 i; i < passedSaltSegments; i++) {
// Construct keys by concatenating msg.sender with each key segment.
assembly {
key := add( // Combine msg.sender & provided key.
shl(0x60, caller), // Place msg.sender at start of word.
shr(0xa0, calldataload(add(24, mul(i, 12)))) // Segment at end.
)
}
// Ensure that the key does not currently have a deployed contract.
require(_isNotDeployed(key), _ACCOUNT_EXISTS);
// Ensure that the caller is the controller of the key.
HomeAddress storage home = _home[key];
if (home.exists) {
require(home.controller == msg.sender, _ONLY_CONTROLLER);
}
// Set the exists flag to true and the controller to this contract.
home.exists = true;
home.controller = address(this);
// Emit an event signifying that this contract is now the controller.
emit NewController(key, address(this));
// Mint the ERC721 token to the designated owner.
_mint(owner, uint256(key));
}
}
/**
* @notice Perform a dry-run of the deployment of a contract using a given key
* and revert on successful deployment. It cannot be called from outside the
* contract (even though it is marked as external).
* @param key bytes32 The unique value used to derive the home address.
* @dev This contract is called by `_isNotDeployable` in extreme cases where
* the deployability of the contract cannot be determined conclusively.
*/
function staticCreate2Check(bytes32 key) public { //inject PUBLIC FUNC TO EXTERNAL
require(
msg.sender == address(this),
"This function can only be called by this contract."
);
assembly {
// Write the 32-byte metamorphic initialization code to scratch space.
mstore(
0,
0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
)
// Call `CREATE2` using metamorphic init code with supplied key as salt.
let deploymentAddress := create2(0, 0, 32, key)
// Revert and return the metamorphic init code on successful deployment.
if deploymentAddress {
revert(0, 32)
}
}
}
/**
* @notice Submit a key to claim the "high score" - the lower the uint160
* value of the key's home address, the higher the score. The high score
* holder has the exclusive right to recover lost ether and tokens on this
* contract.
* @param key bytes32 The unique value used to derive the home address that
* will determine the resultant score.
* @dev The high score must be claimed by a direct key (one that is submitted
* by setting the first 20 bytes of the key to the address of the submitter)
* and not by a derived key, and is non-transferrable. If you want to help
* people recover their lost tokens, you might consider deploying a contract
* to the high score address (probably a metamorphic one so that you can use
* the home address later) with your contact information.
*/
function claimHighScore(bytes32 key) public { //inject PUBLIC FUNC TO EXTERNAL
require(
msg.sender == address(bytes20(key)),
"Only submitters directly encoded in a given key may claim a high score."
);
// Derive the "home address" of the current high score key.
address currentHighScore = _getHomeAddress(_highScoreKey);
// Derive the "home address" of the new high score key.
address newHighScore = _getHomeAddress(key);
// Use addresses to ensure that supplied key is in fact a new high score.
require(
uint160(newHighScore) < uint160(currentHighScore),
"Submitted high score is not better than the current high score."
);
// Set the new high score to the supplied key.
_highScoreKey = key;
// The score is equal to (2^160 - 1) - ("home address" of high score key).
uint256 score = uint256(uint160(-1) - uint160(newHighScore));
// Emit an event to signify that a new high score has been reached.
emit NewHighScore(key, msg.sender, score);
}
/**
* @notice Transfer any ether or ERC20 tokens that have somehow ended up at
* this contract by specifying a token address (set to the null address for
* ether) as well as a recipient address. Only the high score holder can
* recover lost ether and tokens on this contract.
* @param token address The contract address of the ERC20 token to recover, or
* the null address for recovering Ether.
* @param recipient address payable The account where recovered funds should
* be transferred.
* @dev If you are trying to recover funds that were accidentally sent into
* this contract, see if you can contact the holder of the current high score,
* found by calling `getHighScore`. Better yet, try to find a new high score
* yourself!
*/
function recover(IERC20 token, address payable recipient) public { //inject PUBLIC FUNC TO EXTERNAL
require(
msg.sender == address(bytes20(_highScoreKey)),
"Only the current high score holder may recover tokens."
);
if (address(token) == address(0)) {
// Recover ETH if the token's contract address is set to the null address.
recipient.transfer(address(this).balance);
} else {
// Determine the given ERC20 token balance and transfer to the recipient.
uint256 balance = token.balanceOf(address(this));
token.transfer(recipient, balance);
}
}
/**
* @notice "View" function to determine if a contract can currently be
* deployed to a home address given the corresponding key. A contract is only
* deployable if no account currently exists at the address - any existing
* contract must be destroyed via `SELFDESTRUCT` before a new contract can be
* deployed to a home address. This method does not modify state but is
* inaccessible via staticcall.
* @param key bytes32 The unique value used to derive the home address.
* @return A boolean signifying if a contract can be deployed to the home
* address that corresponds to the provided key.
* @dev This will not detect if a contract is not deployable due control
* having been relinquished on the key.
*/
function isDeployable(bytes32 key)
public //inject PUBLIC FUNC TO EXTERNAL
/* view */
returns (bool deployable)
{
deployable = _isNotDeployed(key);
}
/**
* @notice View function to get the current "high score", or the lowest
* uint160 value of a home address of all keys submitted. The high score
* holder has the exclusive right to recover lost ether and tokens on this
* contract.
* @return The current high score holder, their score, and the submitted key.
*/
function getHighScore()
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (address holder, uint256 score, bytes32 key)
{
// Get the key and subbmitter holding the current high score.
key = _highScoreKey;
holder = address(bytes20(key));
// The score is equal to (2^160 - 1) - ("home address" of high score key).
score = uint256(uint160(-1) - uint160(_getHomeAddress(key)));
}
/**
* @notice View function to get information on a home address given the
* corresponding key.
* @param key bytes32 The unique value used to derive the home address.
* @return The home address, the current controller of the address, the number
* of times the home address has been deployed to, and the code hash of the
* runtime currently found at the home address, if any.
* @dev There is also an `isDeployable` method for determining if a contract
* can be deployed to the address, but in extreme cases it must actually
* perform a dry-run to determine if the contract is deployable, which means
* that it does not support staticcalls. There is also a convenience method,
* `hasNeverBeenDeployed`, but the information it conveys can be determined
* from this method alone as well.
*/
function getHomeAddressInformation(bytes32 key)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (
address homeAddress,
address controller,
uint256 deploys,
bytes32 currentRuntimeCodeHash
)
{
// Derive home address and retrieve other information using supplied key.
homeAddress = _getHomeAddress(key);
HomeAddress memory home = _home[key];
// If the home address has not been seen before, use the default controller.
if (!home.exists) {
controller = address(bytes20(key));
} else {
controller = home.controller;
}
// Retrieve the count of total deploys to the home address.
deploys = home.deploys;
// Retrieve keccak256 hash of runtime code currently at the home address.
assembly { currentRuntimeCodeHash := extcodehash(homeAddress) }
}
/**
* @notice View function to determine if no contract has ever been deployed to
* a home address given the corresponding key. This can be used to ensure that
* a given key or corresponding token is "new" or not.
* @param key bytes32 The unique value used to derive the home address.
* @return A boolean signifying if a contract has never been deployed using
* the supplied key before.
*/
function hasNeverBeenDeployed(bytes32 key)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (bool neverBeenDeployed)
{
neverBeenDeployed = (_home[key].deploys == 0);
}
/**
* @notice View function to search for a known key, salt, and/or submitter
* given a supplied home address. Keys can be controlled directly by an
* address that matches the first 20 bytes of the key, or they can be derived
* from a salt and a submitter - if the key is not a derived key, the salt and
* submitter fields will both have a value of zero.
* @param homeAddress address The home address to check for key information.
* @return The key, salt, and/or submitter used to deploy to the home address,
* assuming they have been submitted to the reverse lookup.
* @dev To populate these values, call `setReverseLookup` for cases where keys
* are used directly or are the only value known, or `setDerivedReverseLookup`
* for cases where keys are derived from a known salt and submitter.
*/
function reverseLookup(address homeAddress)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (bytes32 key, bytes32 salt, address submitter)
{
KeyInformation memory keyInformation = _key[homeAddress];
key = keyInformation.key;
salt = keyInformation.salt;
submitter = keyInformation.submitter;
}
/**
* @notice View function used by the metamorphic initialization code when
* deploying a contract to a home address. It returns the address of the
* runtime storage contract that holds the contract creation code, which the
* metamorphic creation code then `DELEGATECALL`s into in order to set up the
* contract and deploy the target runtime code.
* @return The current runtime storage contract that contains the target
* contract creation code.
* @dev This method is not meant to be part of the user-facing contract API,
* but is rather a mechanism for enabling the deployment of arbitrary code via
* fixed initialization code. The odd naming is chosen so that function
* selector will be 0x00000009 - that way, the metamorphic contract can simply
* use the `PC` opcode in order to push the selector to the stack.
*/
function getInitializationCodeFromContractRuntime_6CLUNS()
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (address initializationRuntimeStorageContract)
{
// Return address of contract with initialization code set as runtime code.
initializationRuntimeStorageContract = _initializationRuntimeStorageContract;
}
/**
* @notice View function to return an URI for a given token ID. Throws if the
* token ID does not exist.
* @param tokenId uint256 ID of the token to query.
* @return String representing the URI data encoding of JSON metadata.
* @dev The URI returned by this method takes the following form (with all
* returns and initial whitespace removed - it's just here for clarity):
*
* data:application/json,{
* "name":"Home%20Address%20-%200x********************",
* "description":"< ... HomeWork NFT desription ... >",
* "image":"data:image/svg+xml;charset=utf-8;base64,< ... Image ... >"}
*
* where ******************** represents the checksummed home address that the
* token confers control over.
*/
function tokenURI(uint256 tokenId)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (string memory)
{
// Only return a URI for tokens that exist.
require(_exists(tokenId), "A token with the given ID does not exist.");
// Get the home address that the given tokenId corresponds to.
address homeAddress = _getHomeAddress(bytes32(tokenId));
// Get the checksummed, ascii-encoded representation of the home address.
string memory asciiHomeAddress = _toChecksummedAsciiString(homeAddress);
bytes memory uriEndSegment = _getTokenURIStorageRuntime();
// Insert checksummed address into URI in name and image fields and return.
return string(
abi.encodePacked( // Concatenate all the string segments together.
_URI_START_SEGMENT, // Data URI ID and initial formatting is constant.
asciiHomeAddress, // Checksummed home address is in the name field.
uriEndSegment // Description, image, and formatting is constant.
)
);
}
/**
* @notice Pure function to get the token name.
* @return String representing the token name.
*/
function name() public pure returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL
return _NAME;
}
/**
* @notice Pure function to get the token symbol.
* @return String representing the token symbol.
*/
function symbol() public pure returns (string memory) { //inject PUBLIC FUNC TO EXTERNAL
return _SYMBOL;
}
/**
* @notice Pure function to determine the key that is derived from a given
* salt and submitting address.
* @param salt bytes32 The salt value that is used to derive the key.
* @param submitter address The submitter of the salt value used to derive the
* key.
* @return The derived key.
*/
function getDerivedKey(bytes32 salt, address submitter)
public //inject PUBLIC FUNC TO EXTERNAL
pure
returns (bytes32 key)
{
// Derive the key using the supplied salt and submitter.
key = _deriveKey(salt, submitter);
}
/**
* @notice Pure function to determine the home address that corresponds to
* a given key.
* @param key bytes32 The unique value used to derive the home address.
* @return The home address.
*/
function getHomeAddress(bytes32 key)
public //inject PUBLIC FUNC TO EXTERNAL
pure
returns (address homeAddress)
{
// Derive the home address using the supplied key.
homeAddress = _getHomeAddress(key);
}
/**
* @notice Pure function for retrieving the metamorphic initialization code
* used to deploy arbitrary contracts to home addresses. Provided for easy
* verification and for use in other applications.
* @return The 32-byte metamorphic initialization code.
* @dev This metamorphic init code works via the "metamorphic delegator"
* mechanism, which is explained in greater detail at `_deployToHomeAddress`.
*/
function getMetamorphicDelegatorInitializationCode()
public //inject PUBLIC FUNC TO EXTERNAL
pure
returns (bytes32 metamorphicDelegatorInitializationCode)
{
metamorphicDelegatorInitializationCode = _HOME_INIT_CODE;
}
/**
* @notice Pure function for retrieving the keccak256 of the metamorphic
* initialization code used to deploy arbitrary contracts to home addresses.
* This is the value that you should use, along with this contract's address
* and a caller address that you control, to mine for an partucular type of
* home address (such as one at a compact or gas-efficient address).
* @return The keccak256 hash of the metamorphic initialization code.
*/
function getMetamorphicDelegatorInitializationCodeHash()
public //inject PUBLIC FUNC TO EXTERNAL
pure
returns (bytes32 metamorphicDelegatorInitializationCodeHash)
{
metamorphicDelegatorInitializationCodeHash = _HOME_INIT_CODE_HASH;
}
/**
* @notice Pure function for retrieving the prelude that will be inserted
* ahead of the code payload in order to deploy a runtime storage contract.
* @return The 11-byte "arbitrary runtime" prelude.
*/
function getArbitraryRuntimeCodePrelude()
public //inject PUBLIC FUNC TO EXTERNAL
pure
returns (bytes11 prelude)
{
prelude = _ARBITRARY_RUNTIME_PRELUDE;
}
/**
* @notice Internal function for deploying a runtime storage contract given a
* particular payload.
* @return The address of the runtime storage contract.
* @dev To take the provided code payload and deploy a contract with that
* payload as its runtime code, use the following prelude:
*
* 0x600b5981380380925939f3...
*
* 00 60 push1 0b [11 -> offset]
* 02 59 msize [offset, 0]
* 03 81 dup2 [offset, 0, offset]
* 04 38 codesize [offset, 0, offset, codesize]
* 05 03 sub [offset, 0, codesize - offset]
* 06 80 dup1 [offset, 0, codesize - offset, codesize - offset]
* 07 92 swap3 [codesize - offset, 0, codesize - offset, offset]
* 08 59 msize [codesize - offset, 0, codesize - offset, offset, 0]
* 09 39 codecopy [codesize - offset, 0] <init_code_in_runtime>
* 10 f3 return [] *init_code_in_runtime*
* ... init_code
*/
function _deployRuntimeStorageContract(bytes memory payload)
internal
returns (address runtimeStorageContract)
{
// Construct the contract creation code using the prelude and the payload.
bytes memory runtimeStorageContractCreationCode = abi.encodePacked(
_ARBITRARY_RUNTIME_PRELUDE,
payload
);
assembly {
// Get the location and length of the newly-constructed creation code.
let encoded_data := add(0x20, runtimeStorageContractCreationCode)
let encoded_size := mload(runtimeStorageContractCreationCode)
// Deploy the runtime storage contract via standard `CREATE`.
runtimeStorageContract := create(0, encoded_data, encoded_size)
// Pass along revert message if the contract did not deploy successfully.
if iszero(runtimeStorageContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// Emit an event with address of newly-deployed runtime storage contract.
emit NewRuntimeStorageContract(runtimeStorageContract, keccak256(payload));
}
/**
* @notice Internal function for deploying arbitrary contract code to the home
* address corresponding to a suppied key via metamorphic initialization code.
* @return The home address and the hash of the deployed runtime code.
* @dev This deployment method uses the "metamorphic delegator" pattern, where
* it will retrieve the address of the contract that contains the target
* initialization code, then delegatecall into it, which executes the
* initialization code stored there and returns the runtime code (or reverts).
* Then, the runtime code returned by the delegatecall is returned, and since
* we are still in the initialization context, it will be set as the runtime
* code of the metamorphic contract. The 32-byte metamorphic initialization
* code is as follows:
*
* 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
*
* 00 58 PC [0]
* 01 59 MSIZE [0, 0]
* 02 38 CODESIZE [0, 0, codesize -> 32]
* returndatac03 59 MSIZE [0, 0, 32, 0]
* 04 58 PC [0, 0, 32, 0, 4]
* 05 60 PUSH1 0x1c [0, 0, 32, 0, 4, 28]
* 07 33 CALLER [0, 0, 32, 0, 4, 28, caller]
* 08 5a GAS [0, 0, 32, 0, 4, 28, caller, gas]
* 09 58 PC [0, 0, 32, 0, 4, 28, caller, gas, 9 -> selector]
* 10 59 MSIZE [0, 0, 32, 0, 4, 28, caller, gas, selector, 0]
* 11 52 MSTORE [0, 0, 32, 0, 4, 28, caller, gas] <selector>
* 12 fa STATICCALL [0, 0, 1 => success] <init_in_runtime_address>
* 13 15 ISZERO [0, 0, 0]
* 14 82 DUP3 [0, 0, 0, 0]
* 15 83 DUP4 [0, 0, 0, 0, 0]
* 16 83 DUP4 [0, 0, 0, 0, 0, 0]
* 17 82 DUP3 [0, 0, 0, 0, 0, 0, 0]
* 18 51 MLOAD [0, 0, 0, 0, 0, 0, init_in_runtime_address]
* 19 5a GAS [0, 0, 0, 0, 0, 0, init_in_runtime_address, gas]
* 20 f4 DELEGATECALL [0, 0, 1 => success] {runtime_code}
* 21 3d RETURNDATASIZE [0, 0, 1 => success, size]
* 22 3d RETURNDATASIZE [0, 0, 1 => success, size, size]
* 23 93 SWAP4 [size, 0, 1 => success, size, 0]
* 24 83 DUP4 [size, 0, 1 => success, size, 0, 0]
* 25 3e RETURNDATACOPY [size, 0, 1 => success] <runtime_code>
* 26 60 PUSH1 0x1e [size, 0, 1 => success, 30]
* 28 57 JUMPI [size, 0]
* 29 fd REVERT [] *runtime_code*
* 30 5b JUMPDEST [size, 0]
* 31 f3 RETURN []
*/
function _deployToHomeAddress(bytes32 key)
internal
returns (address homeAddress, bytes32 runtimeCodeHash)
{
assembly {
// Write the 32-byte metamorphic initialization code to scratch space.
mstore(
0,
0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
)
// Call `CREATE2` using above init code with the supplied key as the salt.
homeAddress := create2(callvalue, 0, 32, key)
// Pass along revert message if the contract did not deploy successfully.
if iszero(homeAddress) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
// Get the runtime hash of the deployed contract.
runtimeCodeHash := extcodehash(homeAddress)
}
// Clear the address of the runtime storage contract from storage.
delete _initializationRuntimeStorageContract;
// Emit an event with home address, key, and runtime hash of new contract.
emit NewResident(homeAddress, key, runtimeCodeHash);
}
/**
* @notice Internal function for deriving a key given a particular salt and
* caller and for performing verifications of, and modifications to, the
* information set on that key.
* @param salt bytes32 The value used to derive the key.
* @return The derived key.
*/
function _deriveKeyAndPrepareToDeploy(bytes32 salt)
internal
returns (bytes32 key)
{
// Derive the key using the supplied salt and the calling address.
key = _deriveKey(salt, msg.sender);
// Ensure that a contract is not currently deployed to the home address.
require(_isNotDeployed(key), _ACCOUNT_EXISTS);
// Set appropriate controller and increment contract deploy count at once.
HomeAddress storage home = _home[key];
if (!home.exists) {
home.exists = true;
home.controller = msg.sender;
home.deploys += 1;
// Emit an event signifying that this contract is now the controller.
emit NewController(key, msg.sender);
} else {
home.deploys += 1;
}
// Ensure that the caller is the designated controller before proceeding.
require(home.controller == msg.sender, _ONLY_CONTROLLER);
}
/**
* @notice Internal function for verifying that an owner that cannot accept
* ERC721 tokens has not been supplied.
* @param owner address The specified owner.
* @param key bytes32 The unique value used to derive the home address.
*/
function _validateOwner(address owner, bytes32 key) internal {
// Ensure that the specified owner is a valid ERC721 receiver.
require(
_checkOnERC721Received(address(0), owner, uint256(key), bytes("")),
"Owner must be an EOA or a contract that implements `onERC721Received`."
);
}
/**
* @notice Internal "view" function for determining if a contract currently
* exists at a given home address corresponding to a particular key.
* @param key bytes32 The unique value used to derive the home address.
* @return A boolean signifying whether the home address has a contract
* deployed or not.
*/
function _isNotDeployed(bytes32 key)
internal
/* view */
returns (bool notDeployed)
{
// Derive the home address using the supplied key.
address homeAddress = _getHomeAddress(key);
// Check whether account at home address is non-existent using EXTCODEHASH.
bytes32 hash;
assembly { hash := extcodehash(homeAddress) }
// Account does not exist, and contract is not deployed, if hash equals 0.
if (hash == bytes32(0)) {
return true;
}
// Contract is deployed (notDeployed = false) if codesize is greater than 0.
uint256 size;
assembly { size := extcodesize(homeAddress) }
if (size > 0) {
return false;
}
// Declare variable to move current runtime storage from storage to memory.
address currentStorage;
// Set runtime storage contract to null address temporarily if necessary.
if (_initializationRuntimeStorageContract != address(0)) {
// Place the current runtime storage contract address in memory.
currentStorage = _initializationRuntimeStorageContract;
// Remove the existing runtime storage contract address from storage.
delete _initializationRuntimeStorageContract;
}
// Set gas to use when performing dry-run deployment (future-proof a bit).
uint256 checkGas = 27000 + (block.gaslimit / 1000);
// As a last resort, deploy a contract to the address and revert on success.
(bool contractExists, bytes memory code) = address(this).call.gas(checkGas)(
abi.encodeWithSelector(this.staticCreate2Check.selector, key)
);
// Place runtime storage contract back in storage if necessary.
if (currentStorage != address(0)) {
_initializationRuntimeStorageContract = currentStorage;
}
// Check revert string to ensure failure is due to successful deployment.
bytes32 revertMessage;
assembly { revertMessage := mload(add(code, 32)) }
// Contract is not deployed if `staticCreate2Check` reverted with message.
notDeployed = !contractExists && revertMessage == _HOME_INIT_CODE;
}
/**
* @notice Internal view function for verifying that a restricted controller
* has not been supplied.
* @param controller address The specified controller.
* @param key bytes32 The unique value used to derive the home address.
*/
function _validateController(address controller, bytes32 key) internal view {
// Prevent the controller from being set to prohibited account values.
require(
controller != address(0),
"The null address may not be set as the controller using this function."
);
require(
controller != address(this),
"This contract may not be set as the controller using this function."
);
require(
controller != _getHomeAddress(key),
"Home addresses cannot be set as the controller of themselves."
);
}
/**
* @notice Internal view function for verifying that a supplied runtime
* storage contract is not empty.
* @param target address The runtime storage contract.
*/
function _validateRuntimeStorageIsNotEmpty(address target) internal view {
// Ensure that the runtime storage contract is not empty.
require(
target.isContract(),
"No runtime code found at the supplied runtime storage address."
);
}
/**
* @notice Internal view function for retrieving the controller of a home
* address corresponding to a particular key.
* @param key bytes32 The unique value used to derive the home address.
* @return The controller of the home address corresponding to the supplied
* key.
*/
function _getController(bytes32 key)
internal
view
returns (address controller)
{
// Get controller from mapping, defaulting to first 20 bytes of the key.
HomeAddress memory home = _home[key];
if (!home.exists) {
controller = address(bytes20(key));
} else {
controller = home.controller;
}
}
/**
* @notice Internal view function for getting the runtime code at the tokenURI
* data storage address.
* @return The runtime code at the tokenURI storage address.
*/
function _getTokenURIStorageRuntime()
internal
view
returns (bytes memory runtime)
{
// Bring the tokenURI storage address into memory for use in assembly block.
address target = _URI_END_SEGMENT_STORAGE;
assembly {
// Retrieve the size of the external code.
let size := extcodesize(target)
// Allocate output byte array.
runtime := mload(0x40)
// Set new "memory end" including padding.
mstore(0x40, add(runtime, and(add(size, 0x3f), not(0x1f))))
// Store length in memory.
mstore(runtime, size)
// Get the code using extcodecopy.
extcodecopy(target, add(runtime, 0x20), 0, size)
}
}
/**
* @notice Internal pure function for calculating a home address given a
* particular key.
* @param key bytes32 The unique value used to derive the home address.
* @return The home address corresponding to the supplied key.
*/
function _getHomeAddress(bytes32 key)
internal
pure
returns (address homeAddress)
{
// Determine the home address by replicating CREATE2 logic.
homeAddress = address(
uint160( // Downcast to match the address type.
uint256( // Cast to uint to truncate upper digits.
keccak256( // Compute CREATE2 hash using 4 inputs.
abi.encodePacked( // Pack all inputs to the hash together.
_FF_AND_THIS_CONTRACT, // This contract will be the caller.
key, // Pass in the supplied key as the salt.
_HOME_INIT_CODE_HASH // The metamorphic init code hash.
)
)
)
)
);
}
/**
* @notice Internal pure function for deriving a key given a particular salt
* and caller.
* @param salt bytes32 The value used to derive the key.
* @param submitter address The submitter of the salt used to derive the key.
* @return The derived key.
*/
function _deriveKey(bytes32 salt, address submitter)
internal
pure
returns (bytes32 key)
{
// Set the key as the keccak256 hash of the salt and submitter.
key = keccak256(abi.encodePacked(salt, submitter));
}
/**
* @notice Internal pure function for converting the bytes representation of
* an address to an ASCII string. This function is derived from the function
* at https://ethereum.stackexchange.com/a/56499/48410
* @param data bytes20 The account address to be converted.
* @return The account string in ASCII format. Note that leading "0x" is not
* included.
*/
function _toAsciiString(bytes20 data)
internal
pure
returns (string memory asciiString)
{
// Create an in-memory fixed-size bytes array.
bytes memory asciiBytes = new bytes(40);
// Declare variable types.
uint8 oneByte;
uint8 leftNibble;
uint8 rightNibble;
// Iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i = 0; i < data.length; i++) {
// locate the byte and extract each nibble.
oneByte = uint8(uint160(data) / (2 ** (8 * (19 - i))));
leftNibble = oneByte / 16;
rightNibble = oneByte - 16 * leftNibble;
// To convert to ascii characters, add 48 to 0-9 and 87 to a-f.
asciiBytes[2 * i] = byte(leftNibble + (leftNibble < 10 ? 48 : 87));
asciiBytes[2 * i + 1] = byte(rightNibble + (rightNibble < 10 ? 48 : 87));
}
asciiString = string(asciiBytes);
}
/**
* @notice Internal pure function for getting a fixed-size array of whether or
* not each character in an account will be capitalized in the checksum.
* @param account address The account to get the checksum capitalization
* information for.
* @return A fixed-size array of booleans that signify if each character or
* "nibble" of the hex encoding of the address will be capitalized by the
* checksum.
*/
function _getChecksumCapitalizedCharacters(address account)
internal
pure
returns (bool[40] memory characterIsCapitalized)
{
// Convert the address to bytes.
bytes20 addressBytes = bytes20(account);
// Hash the address (used to calculate checksum).
bytes32 hash = keccak256(abi.encodePacked(_toAsciiString(addressBytes)));
// Declare variable types.
uint8 leftNibbleAddress;
uint8 rightNibbleAddress;
uint8 leftNibbleHash;
uint8 rightNibbleHash;
// Iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i; i < addressBytes.length; i++) {
// locate the byte and extract each nibble for the address and the hash.
rightNibbleAddress = uint8(addressBytes[i]) % 16;
leftNibbleAddress = (uint8(addressBytes[i]) - rightNibbleAddress) / 16;
rightNibbleHash = uint8(hash[i]) % 16;
leftNibbleHash = (uint8(hash[i]) - rightNibbleHash) / 16;
// Set the capitalization flags based on the characters and the checksums.
characterIsCapitalized[2 * i] = (
leftNibbleAddress > 9 &&
leftNibbleHash > 7
);
characterIsCapitalized[2 * i + 1] = (
rightNibbleAddress > 9 &&
rightNibbleHash > 7
);
}
}
/**
* @notice Internal pure function for converting the bytes representation of
* an address to a checksummed ASCII string.
* @param account address The account address to be converted.
* @return The checksummed account string in ASCII format. Note that leading
* "0x" is not included.
*/
function _toChecksummedAsciiString(address account)
internal
pure
returns (string memory checksummedAsciiString)
{
// Get capitalized characters in the checksum.
bool[40] memory caps = _getChecksumCapitalizedCharacters(account);
// Create an in-memory fixed-size bytes array.
bytes memory asciiBytes = new bytes(40);
// Declare variable types.
uint8 oneByte;
uint8 leftNibble;
uint8 rightNibble;
uint8 leftNibbleOffset;
uint8 rightNibbleOffset;
// Convert account to bytes20.
bytes20 data = bytes20(account);
// Iterate over bytes, processing left and right nibble in each iteration.
for (uint256 i = 0; i < data.length; i++) {
// locate the byte and extract each nibble.
oneByte = uint8(uint160(data) / (2 ** (8 * (19 - i))));
leftNibble = oneByte / 16;
rightNibble = oneByte - 16 * leftNibble;
// To convert to ascii characters, add 48 to 0-9, 55 to A-F, & 87 to a-f.
if (leftNibble < 10) {
leftNibbleOffset = 48;
} else if (caps[i * 2]) {
leftNibbleOffset = 55;
} else {
leftNibbleOffset = 87;
}
if (rightNibble < 10) {
rightNibbleOffset = 48;
} else {
rightNibbleOffset = caps[(i * 2) + 1] ? 55 : 87; // instrumentation fix
}
asciiBytes[2 * i] = byte(leftNibble + leftNibbleOffset);
asciiBytes[2 * i + 1] = byte(rightNibble + rightNibbleOffset);
}
checksummedAsciiString = string(asciiBytes);
}
/**
* @notice Modifier to ensure that a contract is not currently deployed to the
* home address corresponding to a given key on the decorated function.
* @param key bytes32 The unique value used to derive the home address.
*/
modifier onlyEmpty(bytes32 key) {
require(_isNotDeployed(key), _ACCOUNT_EXISTS);
_;
}
/**
* @notice Modifier to ensure that the caller of the decorated function is the
* controller of the home address corresponding to a given key.
* @param key bytes32 The unique value used to derive the home address.
*/
modifier onlyController(bytes32 key) {
require(_getController(key) == msg.sender, _ONLY_CONTROLLER);
_;
}
/**
* @notice Modifier to track initial controllers and to count deploys, and to
* validate that only the designated controller has access to the decorated
* function.
* @param key bytes32 The unique value used to derive the home address.
*/
modifier onlyControllerDeployer(bytes32 key) {
HomeAddress storage home = _home[key];
// Set appropriate controller and increment contract deploy count at once.
if (!home.exists) {
home.exists = true;
home.controller = address(bytes20(key));
home.deploys += 1;
} else {
home.deploys += 1;
}
require(home.controller == msg.sender, _ONLY_CONTROLLER);
_;
}
/**
* @notice Modifier to ensure that only the owner of the supplied ERC721
* token, or an approved spender, can access the decorated function.
* @param tokenId uint256 The ID of the ERC721 token.
*/
modifier onlyTokenOwnerOrApprovedSpender(uint256 tokenId) {
require(
_isApprovedOrOwner(msg.sender, tokenId),
"Only the token owner or an approved spender may call this function."
);
_;
}
}
/**
* @title HomeWork Deployer (alpha version)
* @author 0age
* @notice This contract is a stripped-down version of HomeWork that is used to
* deploy HomeWork itself.
* HomeWork Deploy code at runtime: 0x7Cf7708ab4A064B14B02F34aecBd2511f3605395
* HomeWork Runtime code at: 0x0000000000001b84b1cb32787b0d64758d019317
*/
contract HomeWorkDeployer {
// Fires when HomeWork has been deployed.
event HomeWorkDeployment(address homeAddress, bytes32 key);
// Fires HomeWork's initialization-in-runtime storage contract is deployed.
event StorageContractDeployment(address runtimeStorageContract);
// Allocate storage to track the current initialization-in-runtime contract.
address private _initializationRuntimeStorageContract;
// Once HomeWork has been deployed, disable this contract.
bool private _disabled;
// Write arbitrary code to a contract's runtime using the following prelude.
bytes11 private constant _ARBITRARY_RUNTIME_PRELUDE = bytes11(
0x600b5981380380925939f3
);
/**
* @notice Perform phase one of the deployment.
* @param code bytes The contract creation code for HomeWork.
*/
function phaseOne(bytes calldata code) external onlyUntilDisabled {
// Deploy payload to the runtime storage contract and set the address.
_initializationRuntimeStorageContract = _deployRuntimeStorageContract(
bytes32(0),
code
);
}
/**
* @notice Perform phase two of the deployment (tokenURI data).
* @param key bytes32 The salt to provide to create2.
*/
function phaseTwo(bytes32 key) public onlyUntilDisabled { //inject PUBLIC FUNC TO EXTERNAL
// Deploy runtime storage contract with the string used to construct end of
// token URI for issued ERC721s (data URI with a base64-encoded jpeg image).
bytes memory code = abi.encodePacked(
hex"222c226465736372697074696f6e223a22546869732532304e465425323063616e25",
hex"3230626525323072656465656d65642532306f6e253230486f6d65576f726b253230",
hex"746f2532306772616e7425323061253230636f6e74726f6c6c657225323074686525",
hex"32306578636c75736976652532307269676874253230746f2532306465706c6f7925",
hex"3230636f6e7472616374732532307769746825323061726269747261727925323062",
hex"797465636f6465253230746f25323074686525323064657369676e61746564253230",
hex"686f6d65253230616464726573732e222c22696d616765223a22646174613a696d61",
hex"67652f7376672b786d6c3b636861727365743d7574662d383b6261736536342c5048",
hex"4e325a79423462577875637a30696148523063446f764c336433647935334d793576",
hex"636d63764d6a41774d43397a646d636949485a705a58644362336739496a41674d43",
hex"41784e4451674e7a4969506a787a64486c735a543438495674445245465551567375",
hex"516e747a64484a766132557462476c755a57707661573436636d3931626d52394c6b",
hex"4e37633352796232746c4c5731706447567962476c74615851364d5442394c6b5237",
hex"633352796232746c4c5864705a48526f4f6a4a394c6b56375a6d6c7362446f6a4f57",
hex"4935596a6c686653354765334e30636d39725a5331736157356c593246774f6e4a76",
hex"6457356b66563164506a7776633352356247552b5047636764484a68626e4e6d6233",
hex"4a7450534a74595852796158676f4d5334774d694177494441674d5334774d694134",
hex"4c6a45674d436b69506a78775958526f49475a706247773949694e6d5a6d59694947",
hex"5139496b30784f53417a4d6d677a4e4859794e4567784f586f694c7a34385a79427a",
hex"64484a766132553949694d774d44416949474e7359584e7a50534a4349454d675243",
hex"492b50484268644767675a6d6c7362443069493245314e7a6b7a4f5349675a443069",
hex"545449314944517761446c324d545a6f4c546c364969382b50484268644767675a6d",
hex"6c7362443069497a6b795a444e6d4e5349675a443069545451774944517761446832",
hex"4e3267744f486f694c7a3438634746306143426d615778735053496a5a5745315954",
hex"51334969426b50534a4e4e544d674d7a4a494d546c324c5446734d5459744d545967",
hex"4d5467674d545a364969382b50484268644767675a6d6c7362443069626d39755a53",
hex"49675a4430695454453549444d7961444d30646a49305344453565694976506a7877",
hex"5958526f49475a706247773949694e6c595456684e44636949475139496b30794f53",
hex"41794d5777744e53413164693035614456364969382b5043396e506a77765a7a3438",
hex"5a794230636d467563325a76636d3039496d316864484a70654367754f4451674d43",
hex"4177494334344e4341324e5341314b53492b50484268644767675a44306954546b75",
hex"4e5341794d693435624451754f4341324c6a52684d7934784d69417a4c6a45794944",
hex"41674d4341784c544d674d693479624330304c6a67744e6934305979347a4c544575",
hex"4e4341784c6a59744d69343049444d744d693479656949675a6d6c73624430694932",
hex"517759325a6a5a534976506a78775958526f49475a706247773949694d774d544178",
hex"4d44456949475139496b30304d53343349444d344c6a56734e5334784c5459754e53",
hex"4976506a78775958526f49475139496b30304d693435494449334c6a684d4d546775",
hex"4e4341314f4334784944493049445979624449784c6a67744d6a63754d7941794c6a",
hex"4d744d693434656949675932786863334d39496b55694c7a3438634746306143426d",
hex"615778735053496a4d4445774d5441784969426b50534a4e4e444d754e4341794f53",
hex"347a624330304c6a63674e5334344969382b50484268644767675a44306954545132",
hex"4c6a67674d7a4a6a4d793479494449754e6941344c6a63674d533479494445794c6a",
hex"45744d793479637a4d754e6930354c6a6b754d7930784d693431624330314c6a4567",
hex"4e6934314c5449754f4330754d5330754e7930794c6a63674e5334784c5459754e57",
hex"4d744d7934794c5449754e6930344c6a63744d5334794c5445794c6a45674d793479",
hex"6379307a4c6a59674f5334354c53347a494445794c6a556949474e7359584e7a5053",
hex"4a464969382b50484268644767675a6d6c7362443069493245314e7a6b7a4f534967",
hex"5a443069545449334c6a4d674d6a5a734d5445754f4341784e53343349444d754e43",
hex"41794c6a51674f533478494445304c6a51744d793479494449754d79307849433433",
hex"4c5445774c6a49744d544d754e6930784c6a4d744d7934354c5445784c6a67744d54",
hex"55754e336f694c7a3438634746306143426b50534a4e4d5449674d546b754f577731",
hex"4c6a6b674e793435494445774c6a49744e7934324c544d754e4330304c6a567a4e69",
hex"34344c5455754d5341784d4334334c5451754e574d77494441744e6934324c544d74",
hex"4d544d754d7941784c6a46544d5449674d546b754f5341784d6941784f5334356569",
hex"49675932786863334d39496b55694c7a34385a79426d6157787350534a756232356c",
hex"4969427a64484a766132553949694d774d44416949474e7359584e7a50534a434945",
hex"4d675243492b50484268644767675a44306954545579494455344c6a6c4d4e444175",
hex"4f5341304d7934796243307a4c6a45744d69347a4c5445774c6a59744d5451754e79",
hex"30794c6a6b674d693479494445774c6a59674d5451754e7941784c6a45674d793432",
hex"494445784c6a55674d5455754e58704e4d5449754e5341784f533434624455754f43",
hex"4134494445774c6a4d744e7934304c544d754d7930304c6a5a7a4e6934354c545567",
hex"4d5441754f4330304c6a4e6a4d4341774c5459754e69307a4c6a45744d544d754d79",
hex"3435637930784d43347a494463754e4330784d43347a494463754e4870744c544975",
hex"4e6941794c6a6c734e433433494459754e574d744c6a55674d53347a4c5445754e79",
hex"41794c6a45744d7941794c6a4a734c5451754e7930324c6a566a4c6a4d744d533430",
hex"494445754e6930794c6a51674d7930794c6a4a364969382b50484268644767675a44",
hex"3069545451784c6a4d674d7a67754e5777314c6a45744e6934316253307a4c6a5574",
hex"4d693433624330304c6a59674e533434625467754d53307a4c6a466a4d7934794944",
hex"49754e6941344c6a63674d533479494445794c6a45744d793479637a4d754e693035",
hex"4c6a6b754d7930784d693431624330314c6a45674e6934314c5449754f4330754d53",
hex"30754f4330794c6a63674e5334784c5459754e574d744d7934794c5449754e693034",
hex"4c6a63744d5334794c5445794c6a45674d7934794c544d754e4341304c6a4d744d79",
hex"343249446b754f5330754d7941784d6934314969426a6247467a637a306952694976",
hex"506a78775958526f49475139496b307a4d433434494451304c6a524d4d546b674e54",
hex"67754f57773049444d674d5441744d5449754e7949675932786863334d39496b5969",
hex"4c7a34384c32632b5043396e506a777663335a6e50673d3d227d"
); /* ","description":"This%20NFT%20can%20be%20redeemed%20on%20HomeWork%20
to%20grant%20a%20controller%20the%20exclusive%20right%20to%20deploy%20
contracts%20with%20arbitrary%20bytecode%20to%20the%20designated%20home
%20address.","image":"data:image/svg+xml;charset=utf-8;base64,..."} */
// Deploy payload to the runtime storage contract.
_deployRuntimeStorageContract(key, code);
}
/**
* @notice Perform phase three of the deployment and disable this contract.
* @param key bytes32 The salt to provide to create2.
*/
function phaseThree(bytes32 key) public onlyUntilDisabled { //inject PUBLIC FUNC TO EXTERNAL
// Use metamorphic initialization code to deploy contract to home address.
_deployToHomeAddress(key);
// Disable this contract from here on out - use HomeWork itself instead.
_disabled = true;
}
/**
* @notice View function used by the metamorphic initialization code when
* deploying a contract to a home address. It returns the address of the
* runtime storage contract that holds the contract creation code, which the
* metamorphic creation code then `DELEGATECALL`s into in order to set up the
* contract and deploy the target runtime code.
* @return The current runtime storage contract that contains the target
* contract creation code.
* @dev This method is not meant to be part of the user-facing contract API,
* but is rather a mechanism for enabling the deployment of arbitrary code via
* fixed initialization code. The odd naming is chosen so that function
* selector will be 0x00000009 - that way, the metamorphic contract can simply
* use the `PC` opcode in order to push the selector to the stack.
*/
function getInitializationCodeFromContractRuntime_6CLUNS()
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (address initializationRuntimeStorageContract)
{
// Return address of contract with initialization code set as runtime code.
initializationRuntimeStorageContract = _initializationRuntimeStorageContract;
}
/**
* @notice Internal function for deploying a runtime storage contract given a
* particular payload.
* @dev To take the provided code payload and deploy a contract with that
* payload as its runtime code, use the following prelude:
*
* 0x600b5981380380925939f3...
*
* 00 60 push1 0b [11 -> offset]
* 02 59 msize [offset, 0]
* 03 81 dup2 [offset, 0, offset]
* 04 38 codesize [offset, 0, offset, codesize]
* 05 03 sub [offset, 0, codesize - offset]
* 06 80 dup1 [offset, 0, codesize - offset, codesize - offset]
* 07 92 swap3 [codesize - offset, 0, codesize - offset, offset]
* 08 59 msize [codesize - offset, 0, codesize - offset, offset, 0]
* 09 39 codecopy [codesize - offset, 0] <init_code_in_runtime>
* 10 f3 return [] *init_code_in_runtime*
* ... init_code
*/
function _deployRuntimeStorageContract(bytes32 key, bytes memory payload)
internal
returns (address runtimeStorageContract)
{
// Construct the contract creation code using the prelude and the payload.
bytes memory runtimeStorageContractCreationCode = abi.encodePacked(
_ARBITRARY_RUNTIME_PRELUDE,
payload
);
assembly {
// Get the location and length of the newly-constructed creation code.
let encoded_data := add(0x20, runtimeStorageContractCreationCode)
let encoded_size := mload(runtimeStorageContractCreationCode)
// Deploy the runtime storage contract via `CREATE2`.
runtimeStorageContract := create2(0, encoded_data, encoded_size, key)
// Pass along revert message if the contract did not deploy successfully.
if iszero(runtimeStorageContract) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// Emit an event with address of newly-deployed runtime storage contract.
emit StorageContractDeployment(runtimeStorageContract);
}
/**
* @notice Internal function for deploying arbitrary contract code to the home
* address corresponding to a suppied key via metamorphic initialization code.
* @dev This deployment method uses the "metamorphic delegator" pattern, where
* it will retrieve the address of the contract that contains the target
* initialization code, then delegatecall into it, which executes the
* initialization code stored there and returns the runtime code (or reverts).
* Then, the runtime code returned by the delegatecall is returned, and since
* we are still in the initialization context, it will be set as the runtime
* code of the metamorphic contract. The 32-byte metamorphic initialization
* code is as follows:
*
* 0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
*
* 00 58 PC [0]
* 01 59 MSIZE [0, 0]
* 02 38 CODESIZE [0, 0, codesize -> 32]
* returndatac03 59 MSIZE [0, 0, 32, 0]
* 04 58 PC [0, 0, 32, 0, 4]
* 05 60 PUSH1 0x1c [0, 0, 32, 0, 4, 28]
* 07 33 CALLER [0, 0, 32, 0, 4, 28, caller]
* 08 5a GAS [0, 0, 32, 0, 4, 28, caller, gas]
* 09 58 PC [0, 0, 32, 0, 4, 28, caller, gas, 9 -> selector]
* 10 59 MSIZE [0, 0, 32, 0, 4, 28, caller, gas, selector, 0]
* 11 52 MSTORE [0, 0, 32, 0, 4, 28, caller, gas] <selector>
* 12 fa STATICCALL [0, 0, 1 => success] <init_in_runtime_address>
* 13 15 ISZERO [0, 0, 0]
* 14 82 DUP3 [0, 0, 0, 0]
* 15 83 DUP4 [0, 0, 0, 0, 0]
* 16 83 DUP4 [0, 0, 0, 0, 0, 0]
* 17 82 DUP3 [0, 0, 0, 0, 0, 0, 0]
* 18 51 MLOAD [0, 0, 0, 0, 0, 0, init_in_runtime_address]
* 19 5a GAS [0, 0, 0, 0, 0, 0, init_in_runtime_address, gas]
* 20 f4 DELEGATECALL [0, 0, 1 => success] {runtime_code}
* 21 3d RETURNDATASIZE [0, 0, 1 => success, size]
* 22 3d RETURNDATASIZE [0, 0, 1 => success, size, size]
* 23 93 SWAP4 [size, 0, 1 => success, size, 0]
* 24 83 DUP4 [size, 0, 1 => success, size, 0, 0]
* 25 3e RETURNDATACOPY [size, 0, 1 => success] <runtime_code>
* 26 60 PUSH1 0x1e [size, 0, 1 => success, 30]
* 28 57 JUMPI [size, 0]
* 29 fd REVERT [] *runtime_code*
* 30 5b JUMPDEST [size, 0]
* 31 f3 RETURN []
*/
function _deployToHomeAddress(bytes32 key) internal {
// Declare a variable for the home address.
address homeAddress;
assembly {
// Write the 32-byte metamorphic initialization code to scratch space.
mstore(
0,
0x5859385958601c335a585952fa1582838382515af43d3d93833e601e57fd5bf3
)
// Call `CREATE2` using above init code with the supplied key as the salt.
homeAddress := create2(callvalue, 0, 32, key)
// Pass along revert message if the contract did not deploy successfully.
if iszero(homeAddress) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
// Clear the address of the runtime storage contract from storage.
delete _initializationRuntimeStorageContract;
// Emit an event with home address and key for the newly-deployed contract.
emit HomeWorkDeployment(homeAddress, key);
}
/**
* @notice Modifier to disable the contract once deployment is complete.
*/
modifier onlyUntilDisabled() {
require(!_disabled, "Contract is disabled.");
_;
}
}
|
* @notice Mint multiple ERC721 tokens, designated by salts that are hashed with the caller's address to derive each key, to the specified owner. Derived keys that aren't controlled, or that point to home addresses that are currently deployed, will be skipped. @param owner address The account that will be granted ownership of the ERC721 tokens. @param salts bytes32[] An array of values used to derive each key and corresponding home address. @dev See `batchLock` for batch token minting with standard, non-derived keys./ Track each key derived from the array of salts. Ensure that the specified owner is a valid ERC721 receiver.
|
{
bytes32 key;
function deriveKeysAndBatchLock(address owner, bytes32[] calldata salts)
external
if (salts.length > 0) {
_validateOwner(owner, _deriveKey(salts[0], msg.sender));
}
for (uint256 i; i < salts.length; i++) {
key = _deriveKey(salts[i], msg.sender);
if (!_isNotDeployed(key)) {
continue;
}
if (home.exists && home.controller != msg.sender) {
continue;
}
home.controller = address(this);
}
for (uint256 i; i < salts.length; i++) {
key = _deriveKey(salts[i], msg.sender);
if (!_isNotDeployed(key)) {
continue;
}
if (home.exists && home.controller != msg.sender) {
continue;
}
home.controller = address(this);
}
HomeAddress storage home = _home[key];
for (uint256 i; i < salts.length; i++) {
key = _deriveKey(salts[i], msg.sender);
if (!_isNotDeployed(key)) {
continue;
}
if (home.exists && home.controller != msg.sender) {
continue;
}
home.controller = address(this);
}
home.exists = true;
emit NewController(key, address(this));
_mint(owner, uint256(key));
}
| 15,817,875 |
[
1,
49,
474,
3229,
4232,
39,
27,
5340,
2430,
16,
25264,
635,
4286,
87,
716,
854,
14242,
598,
326,
4894,
1807,
1758,
358,
14763,
1517,
498,
16,
358,
326,
1269,
3410,
18,
14969,
2950,
1311,
716,
11526,
1404,
25934,
16,
578,
716,
1634,
358,
6382,
6138,
716,
854,
4551,
19357,
16,
903,
506,
9700,
18,
225,
3410,
1758,
1021,
2236,
716,
903,
506,
17578,
23178,
434,
326,
4232,
39,
27,
5340,
2430,
18,
225,
4286,
87,
1731,
1578,
8526,
1922,
526,
434,
924,
1399,
358,
14763,
1517,
498,
471,
4656,
6382,
1758,
18,
225,
2164,
1375,
5303,
2531,
68,
364,
2581,
1147,
312,
474,
310,
598,
4529,
16,
1661,
17,
765,
2950,
1311,
18,
19,
11065,
1517,
498,
10379,
628,
326,
526,
434,
4286,
87,
18,
7693,
716,
326,
1269,
3410,
353,
279,
923,
4232,
39,
27,
5340,
5971,
18,
2,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
288,
203,
565,
1731,
1578,
498,
31,
203,
203,
225,
445,
14763,
2396,
1876,
4497,
2531,
12,
2867,
3410,
16,
1731,
1578,
8526,
745,
892,
4286,
87,
13,
203,
565,
3903,
203,
565,
309,
261,
5759,
87,
18,
2469,
405,
374,
13,
288,
203,
1377,
389,
5662,
5541,
12,
8443,
16,
389,
765,
688,
653,
12,
5759,
87,
63,
20,
6487,
1234,
18,
15330,
10019,
203,
565,
289,
203,
203,
565,
364,
261,
11890,
5034,
277,
31,
277,
411,
4286,
87,
18,
2469,
31,
277,
27245,
288,
203,
1377,
498,
273,
389,
765,
688,
653,
12,
5759,
87,
63,
77,
6487,
1234,
18,
15330,
1769,
203,
203,
1377,
309,
16051,
67,
291,
1248,
31954,
12,
856,
3719,
288,
203,
3639,
1324,
31,
203,
1377,
289,
203,
203,
1377,
309,
261,
8712,
18,
1808,
597,
6382,
18,
5723,
480,
1234,
18,
15330,
13,
288,
203,
3639,
1324,
31,
203,
1377,
289,
203,
203,
1377,
6382,
18,
5723,
273,
1758,
12,
2211,
1769,
203,
203,
203,
565,
289,
203,
565,
364,
261,
11890,
5034,
277,
31,
277,
411,
4286,
87,
18,
2469,
31,
277,
27245,
288,
203,
1377,
498,
273,
389,
765,
688,
653,
12,
5759,
87,
63,
77,
6487,
1234,
18,
15330,
1769,
203,
203,
1377,
309,
16051,
67,
291,
1248,
31954,
12,
856,
3719,
288,
203,
3639,
1324,
31,
203,
1377,
289,
203,
203,
1377,
309,
261,
8712,
18,
1808,
597,
6382,
18,
5723,
480,
1234,
18,
15330,
13,
288,
203,
3639,
1324,
31,
203,
1377,
289,
203,
203,
1377,
6382,
18,
5723,
2
] |
./full_match/4/0xdaa51b7BDfB1baC5bdF57dC52e94de3af0AF6353/sources/contracts/LotteryWinner.sol
|
Tracks the index of a value
|
mapping(address => uint256) index;
| 13,297,981 |
[
1,
22138,
326,
770,
434,
279,
460,
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,
3639,
2874,
12,
2867,
516,
2254,
5034,
13,
770,
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,
-100,
-100
] |
./full_match/97/0x0109c89bc47a13Aa0939d7292E2E38500F7AE9fC/sources/project_/contracts/CharacterToken.sol
|
Maketplace contract address => open for setting when in need Counter for tokenID Mapping from owner address to list of token IDs. Mapping from token ID to token details. Max tokens can mint in one order Max tokens can use in one call Total Supply Mapping address of user and its ability in whitelist or not Flag Free transfer NFT Flag: Enable or disable the feature of minting
|
{
using Counters for Counters.Counter;
using CharacterTokenDetails for CharacterTokenDetails.TokenDetail;
using CharacterTokenDetails for CharacterTokenDetails.MintingOrder;
using CharacterTokenDetails for CharacterTokenDetails.ReturnMintingOrder;
event TokenCreated(address to, uint256 tokenId, CharacterTokenDetails.TokenDetail details);
event BurnToken(uint256[] ids);
event SetNewMinter(address newMinter);
event SetCharacterItem(address itemAddress);
event SetMarketplace(address marketplaceAddress);
event AddNewNftType(uint8 maxNftType, uint8[] maxRarityList);
event MintOrderForDev(bytes callbackData, address to, CharacterTokenDetails.ReturnMintingOrder[] returnMintingOrder);
event MintOrderFromDaapCreator(string callbackData, address to, CharacterTokenDetails.ReturnMintingOrder[] returnMintingOrder);
event UseNFTs(address to, uint256[] usedTokenIds);
event SetMaxTokensInOneOrder(uint8 maxTokensInOneOrder);
event SetMaxTokensInOneUsing(uint8 maxTokenInOneUsing);
event SetNewMaxRarity(uint8 oldMaxRarity, uint8 newMaxRarity);
event SetWhiteList(address to);
event SwitchFreeTransferMode(bool oldMode, bool newMode);
event UpdateDiableMinting(bool oldState, bool newState);
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant OPEN_BOX_ROLE = keccak256("OPEN_BOX_ROLE");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
bytes32 public constant DESIGNER_ROLE = keccak256("DESIGNER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes32 public constant OPEN_NFT_ROLE = keccak256("OPEN_NFT_ROLE");
bytes32 public constant WHITELIST_ROLE = keccak256("WHITELIST_ROLE");
uint256 private constant maskLast8Bits = uint256(0xff);
uint256 private constant maskFirst248Bits = ~uint256(0xff);
IERC721 public marketPlace;
Counters.Counter public tokenIdCounter;
mapping(address => uint256[]) public tokenIds;
mapping(uint256 => CharacterTokenDetails.TokenDetail) public tokenDetails;
uint8 public MAX_TOKENS_IN_ORDER;
uint8 public MAX_TOKENS_IN_USING;
uint256 public totalSupply;
mapping(address => bool) public whiteList;
bool public FREE_TRANSFER;
bool public DISABLE_MINTING;
pragma solidity ^0.8.0;
modifier notContract() {
require(!_isContract(msg.sender), "Contract not allowed");
require(msg.sender == tx.origin, "Proxy contract not allowed");
_;
}
modifier onlyFromDaapCreator() {
require(msg.sender == getNftCreator(), "Not be called from Daap Creator");
_;
}
constructor () {
}
function initialize(
string memory _name,
string memory _symbol
) public initializer {
__ERC721_init("Character","CK");
__AccessControl_init();
__Pausable_init();
__UUPSUpgradeable_init();
_transferOwnership(msg.sender);
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(PAUSER_ROLE, msg.sender);
_setupRole(UPGRADER_ROLE, msg.sender);
_setupRole(DESIGNER_ROLE, msg.sender);
_setupRole(MINTER_ROLE, msg.sender);
_setupRole(OPEN_NFT_ROLE, msg.sender);
_setupRole(WHITELIST_ROLE, msg.sender);
MAX_TOKENS_IN_ORDER = 10;
MAX_TOKENS_IN_USING = 10;
totalSupply = 100000000;
whiteList[msg.sender] = true;
FREE_TRANSFER = false;
DISABLE_MINTING = false;
}
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
function setWhiteList(address _to) external onlyRole(DESIGNER_ROLE) {
whiteList[_to] = true;
emit SetWhiteList(_to);
}
function switchFreeTransferMode() external onlyRole(DESIGNER_ROLE) {
bool oldMode = FREE_TRANSFER;
if (FREE_TRANSFER) {
FREE_TRANSFER = false;
FREE_TRANSFER = true;
}
bool newMode = FREE_TRANSFER;
emit SwitchFreeTransferMode(oldMode, newMode);
}
function switchFreeTransferMode() external onlyRole(DESIGNER_ROLE) {
bool oldMode = FREE_TRANSFER;
if (FREE_TRANSFER) {
FREE_TRANSFER = false;
FREE_TRANSFER = true;
}
bool newMode = FREE_TRANSFER;
emit SwitchFreeTransferMode(oldMode, newMode);
}
} else {
function updateDisableMinting(bool _newState) external onlyRole(DESIGNER_ROLE) {
bool _oldState = DISABLE_MINTING;
DISABLE_MINTING = _newState;
emit UpdateDiableMinting(_oldState, _newState);
}
function setMinterRole(address _newMinter) external onlyRole(DEFAULT_ADMIN_ROLE) {
_setupRole(MINTER_ROLE, _newMinter);
emit SetNewMinter(_newMinter);
}
function setMaxTokensInOneMint(uint8 _maxTokensInOneMint) external onlyRole(DEFAULT_ADMIN_ROLE) {
MAX_TOKENS_IN_ORDER = _maxTokensInOneMint;
emit SetMaxTokensInOneOrder(_maxTokensInOneMint);
}
function setMaxTokensInOneUsing(uint8 _maxTokenInOneUsing) external onlyRole(DEFAULT_ADMIN_ROLE) {
MAX_TOKENS_IN_USING = _maxTokenInOneUsing;
emit SetMaxTokensInOneUsing(_maxTokenInOneUsing);
}
function pause() public onlyRole(PAUSER_ROLE) {
_pause();
}
function unpause() public onlyRole(PAUSER_ROLE) {
_unpause();
}
{}
function _authorizeUpgrade(address newImplementation)
internal
override
onlyRole(UPGRADER_ROLE)
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721Upgradeable, AccessControlUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function burn(uint256[] memory ids) override external onlyRole(BURNER_ROLE) {
for (uint256 i = 0; i < ids.length; ++i) {
_burn(ids[i]);
}
emit BurnToken(ids);
}
function burn(uint256[] memory ids) override external onlyRole(BURNER_ROLE) {
for (uint256 i = 0; i < ids.length; ++i) {
_burn(ids[i]);
}
emit BurnToken(ids);
}
function getTokenDetailsByOwner(address to)
external
view
returns (CharacterTokenDetails.TokenDetail[] memory)
{
uint256[] storage ids = tokenIds[to];
CharacterTokenDetails.TokenDetail[] memory result = new CharacterTokenDetails.TokenDetail[](ids.length);
for (uint256 i = 0; i < ids.length; ++i) {
result[i] = tokenDetails[ids[i]];
}
return result;
}
function getTokenDetailsByOwner(address to)
external
view
returns (CharacterTokenDetails.TokenDetail[] memory)
{
uint256[] storage ids = tokenIds[to];
CharacterTokenDetails.TokenDetail[] memory result = new CharacterTokenDetails.TokenDetail[](ids.length);
for (uint256 i = 0; i < ids.length; ++i) {
result[i] = tokenDetails[ids[i]];
}
return result;
}
function getTokenIdsByOwner(address to)
external
view
returns (uint256[] memory)
{
uint256[] memory ids = tokenIds[to];
return ids;
}
function getTokenDetailsByID(uint256 _tokenId) external view returns (CharacterTokenDetails.TokenDetail memory) {
return tokenDetails[_tokenId];
}
function getTotalSupply() internal view returns (uint256) {
return totalSupply;
}
function mintOrderForDev(
CharacterTokenDetails.MintingOrder[] memory _mintingOrders,
address _to,
bytes calldata _callbackData
) external onlyRole(MINTER_ROLE) {
CharacterTokenDetails.ReturnMintingOrder[] memory _returnOrder = _mintOneOrder(
_mintingOrders,
_to
);
emit MintOrderForDev(
_callbackData,
_to,
_returnOrder
);
}
function mintOrderFromDaapCreator(
CharacterTokenDetails.MintingOrder[] memory _mintingOrders,
address _to,
string calldata _callbackData
) external onlyFromDaapCreator {
CharacterTokenDetails.ReturnMintingOrder[] memory _returnOrder = _mintOneOrder(
_mintingOrders,
_to
);
emit MintOrderFromDaapCreator(
_callbackData,
_to,
_returnOrder
);
}
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
return(tokenDetails[_tokenId].tokenURI);
}
function lastId() public view returns (uint256) {
return tokenIdCounter.current();
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal override {
if (FREE_TRANSFER == false) {
require(
whiteList[to] == true || whiteList[from],
"Not support to transfer directly"
);
}
ERC721Upgradeable._transfer(from, to, tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal override {
if (FREE_TRANSFER == false) {
require(
whiteList[to] == true || whiteList[from],
"Not support to transfer directly"
);
}
ERC721Upgradeable._transfer(from, to, tokenId);
}
function _setTokenUri(
uint256 _tokenId,
uint256 _rarity,
uint256 _meshIndex,
uint256 _meshMaterial
) internal {
string memory _cid = INftConfigurations(getNftConfigurations()).getCid(
_rarity,
_meshIndex,
_meshMaterial
);
}
function _mintOneOrder(
CharacterTokenDetails.MintingOrder[] memory _mintingOrders,
address _to
) internal returns(CharacterTokenDetails.ReturnMintingOrder[] memory) {
require(_mintingOrders.length > 0, "No token to mint");
require(_mintingOrders.length <= MAX_TOKENS_IN_ORDER, "Maximum tokens in one mint reached");
require(
tokenIdCounter.current() + _mintingOrders.length <= getTotalSupply(),
"Total supply of NFT reached"
);
for (uint256 i=0; i < _mintingOrders.length; i++) {
require(
INftConfigurations(getNftConfigurations()).checkValidMintingAttributes(
address(this),
_mintingOrders[i]
),
"Invalid rarity"
);
}
CharacterTokenDetails.ReturnMintingOrder[] memory _returnOrder = new CharacterTokenDetails.ReturnMintingOrder[](_mintingOrders.length);
for (uint256 i=0; i < _mintingOrders.length; i++) {
uint256 _tokenId = createToken(
_to,
_mintingOrders[i]
);
_returnOrder[i] = CharacterTokenDetails.ReturnMintingOrder(
_tokenId,
_mintingOrders[i]
);
}
return _returnOrder;
}
function _mintOneOrder(
CharacterTokenDetails.MintingOrder[] memory _mintingOrders,
address _to
) internal returns(CharacterTokenDetails.ReturnMintingOrder[] memory) {
require(_mintingOrders.length > 0, "No token to mint");
require(_mintingOrders.length <= MAX_TOKENS_IN_ORDER, "Maximum tokens in one mint reached");
require(
tokenIdCounter.current() + _mintingOrders.length <= getTotalSupply(),
"Total supply of NFT reached"
);
for (uint256 i=0; i < _mintingOrders.length; i++) {
require(
INftConfigurations(getNftConfigurations()).checkValidMintingAttributes(
address(this),
_mintingOrders[i]
),
"Invalid rarity"
);
}
CharacterTokenDetails.ReturnMintingOrder[] memory _returnOrder = new CharacterTokenDetails.ReturnMintingOrder[](_mintingOrders.length);
for (uint256 i=0; i < _mintingOrders.length; i++) {
uint256 _tokenId = createToken(
_to,
_mintingOrders[i]
);
_returnOrder[i] = CharacterTokenDetails.ReturnMintingOrder(
_tokenId,
_mintingOrders[i]
);
}
return _returnOrder;
}
function _mintOneOrder(
CharacterTokenDetails.MintingOrder[] memory _mintingOrders,
address _to
) internal returns(CharacterTokenDetails.ReturnMintingOrder[] memory) {
require(_mintingOrders.length > 0, "No token to mint");
require(_mintingOrders.length <= MAX_TOKENS_IN_ORDER, "Maximum tokens in one mint reached");
require(
tokenIdCounter.current() + _mintingOrders.length <= getTotalSupply(),
"Total supply of NFT reached"
);
for (uint256 i=0; i < _mintingOrders.length; i++) {
require(
INftConfigurations(getNftConfigurations()).checkValidMintingAttributes(
address(this),
_mintingOrders[i]
),
"Invalid rarity"
);
}
CharacterTokenDetails.ReturnMintingOrder[] memory _returnOrder = new CharacterTokenDetails.ReturnMintingOrder[](_mintingOrders.length);
for (uint256 i=0; i < _mintingOrders.length; i++) {
uint256 _tokenId = createToken(
_to,
_mintingOrders[i]
);
_returnOrder[i] = CharacterTokenDetails.ReturnMintingOrder(
_tokenId,
_mintingOrders[i]
);
}
return _returnOrder;
}
function createToken(
address _to,
CharacterTokenDetails.MintingOrder memory _mintingOrder
) internal returns (uint256){
tokenIdCounter.increment();
uint256 _id = tokenIdCounter.current();
_setTokenUri(
_id,
_mintingOrder.rarity,
_mintingOrder.meshIndex,
_mintingOrder.meshMaterial
);
_mint(_to, _id);
CharacterTokenDetails.TokenDetail memory _tokenDetail;
_tokenDetail.mintingOrder = _mintingOrder;
_tokenDetail.tokenURI = tokenURI(_id);
tokenDetails[_id] = _tokenDetail;
emit TokenCreated(_to, _id, _tokenDetail);
return uint256(_id);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 id
) internal override {
if (from == address(0)) {
uint256[] storage ids = tokenIds[from];
uint256 index;
for (uint256 i=0; i < ids.length; i++) {
if (ids[i] == id) {
index = i;
break;
}
}
ids[index] = ids[ids.length - 1];
ids.pop();
}
if (to == address(0)) {
delete tokenDetails[id];
uint256[] storage ids = tokenIds[to];
ids.push(id);
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 id
) internal override {
if (from == address(0)) {
uint256[] storage ids = tokenIds[from];
uint256 index;
for (uint256 i=0; i < ids.length; i++) {
if (ids[i] == id) {
index = i;
break;
}
}
ids[index] = ids[ids.length - 1];
ids.pop();
}
if (to == address(0)) {
delete tokenDetails[id];
uint256[] storage ids = tokenIds[to];
ids.push(id);
}
}
} else {
function _beforeTokenTransfer(
address from,
address to,
uint256 id
) internal override {
if (from == address(0)) {
uint256[] storage ids = tokenIds[from];
uint256 index;
for (uint256 i=0; i < ids.length; i++) {
if (ids[i] == id) {
index = i;
break;
}
}
ids[index] = ids[ids.length - 1];
ids.pop();
}
if (to == address(0)) {
delete tokenDetails[id];
uint256[] storage ids = tokenIds[to];
ids.push(id);
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 id
) internal override {
if (from == address(0)) {
uint256[] storage ids = tokenIds[from];
uint256 index;
for (uint256 i=0; i < ids.length; i++) {
if (ids[i] == id) {
index = i;
break;
}
}
ids[index] = ids[ids.length - 1];
ids.pop();
}
if (to == address(0)) {
delete tokenDetails[id];
uint256[] storage ids = tokenIds[to];
ids.push(id);
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 id
) internal override {
if (from == address(0)) {
uint256[] storage ids = tokenIds[from];
uint256 index;
for (uint256 i=0; i < ids.length; i++) {
if (ids[i] == id) {
index = i;
break;
}
}
ids[index] = ids[ids.length - 1];
ids.pop();
}
if (to == address(0)) {
delete tokenDetails[id];
uint256[] storage ids = tokenIds[to];
ids.push(id);
}
}
} else {
function getNftCreator() internal view returns(address) {
return INftFactory(owner()).getCurrentDappCreatorAddress();
}
function getNftConfigurations() internal view returns(address) {
return INftFactory(owner()).getCurrentNftConfigurations();
}
function _isContract(address addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
function _isContract(address addr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(addr)
}
return size > 0;
}
}
| 3,278,307 |
[
1,
49,
581,
24577,
6835,
1758,
516,
1696,
364,
3637,
1347,
316,
1608,
9354,
364,
1147,
734,
9408,
628,
3410,
1758,
358,
666,
434,
1147,
7115,
18,
9408,
628,
1147,
1599,
358,
1147,
3189,
18,
4238,
2430,
848,
312,
474,
316,
1245,
1353,
4238,
2430,
848,
999,
316,
1245,
745,
10710,
3425,
1283,
9408,
1758,
434,
729,
471,
2097,
7123,
316,
10734,
578,
486,
9960,
15217,
7412,
423,
4464,
9960,
30,
9677,
578,
4056,
326,
2572,
434,
312,
474,
310,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
95,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
1450,
6577,
1345,
3790,
364,
6577,
1345,
3790,
18,
1345,
6109,
31,
203,
565,
1450,
6577,
1345,
3790,
364,
6577,
1345,
3790,
18,
49,
474,
310,
2448,
31,
203,
565,
1450,
6577,
1345,
3790,
364,
6577,
1345,
3790,
18,
990,
49,
474,
310,
2448,
31,
203,
203,
565,
871,
3155,
6119,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
16,
6577,
1345,
3790,
18,
1345,
6109,
3189,
1769,
203,
565,
871,
605,
321,
1345,
12,
11890,
5034,
8526,
3258,
1769,
203,
565,
871,
1000,
1908,
49,
2761,
12,
2867,
394,
49,
2761,
1769,
203,
565,
871,
1000,
7069,
1180,
12,
2867,
761,
1887,
1769,
203,
565,
871,
1000,
3882,
24577,
12,
2867,
29917,
1887,
1769,
203,
565,
871,
1436,
1908,
50,
1222,
559,
12,
11890,
28,
943,
50,
1222,
559,
16,
2254,
28,
8526,
943,
54,
20498,
682,
1769,
203,
565,
871,
490,
474,
2448,
1290,
8870,
12,
3890,
1348,
751,
16,
1758,
358,
16,
6577,
1345,
3790,
18,
990,
49,
474,
310,
2448,
8526,
327,
49,
474,
310,
2448,
1769,
203,
565,
871,
490,
474,
2448,
1265,
40,
69,
438,
10636,
12,
1080,
1348,
751,
16,
1758,
358,
16,
6577,
1345,
3790,
18,
990,
49,
474,
310,
2448,
8526,
327,
49,
474,
310,
2448,
1769,
203,
565,
871,
2672,
50,
4464,
87,
12,
2867,
358,
16,
2254,
5034,
8526,
1399,
1345,
2673,
1769,
203,
565,
871,
28113,
5157,
382,
3335,
2448,
12,
11890,
28,
943,
5157,
382,
3335,
2448,
2
] |
pragma solidity ^0.8.13;
// SPDX-License-Identifier: MIT
import "./TypesAndDecoders.sol";
import "./caveat-enforcers/CaveatEnforcer.sol";
import "hardhat/console.sol";
abstract contract Delegatable is EIP712Decoder {
bytes32 public immutable domainHash;
constructor (string memory contractName, string memory version) {
domainHash = getEIP712DomainHash(contractName,version,block.chainid,address(this));
}
// Allows external signers to submit batches of signed invocations for processing.
function invoke (SignedInvocation[] calldata signedInvocations) public returns (bool success) {
for (uint i = 0; i < signedInvocations.length; i++) {
SignedInvocation calldata signedInvocation = signedInvocations[i];
address invocationSigner = verifyInvocationSignature(signedInvocation);
enforceReplayProtection(invocationSigner, signedInvocations[i].invocations.replayProtection);
_invoke(signedInvocation.invocations.batch, invocationSigner);
}
}
// Allows external contracts to submit batches of invocations for processing.
function contractInvoke (Invocation[] calldata batch) public returns (bool) {
return _invoke(batch, msg.sender);
}
function _invoke (Invocation[] calldata batch, address sender) private returns (bool success) {
for (uint x = 0; x < batch.length; x++) {
Invocation memory invocation = batch[x];
address intendedSender;
address canGrant;
// If there are no delegations, this invocation comes from the signer
if (invocation.authority.length == 0) {
intendedSender = sender;
canGrant = intendedSender;
}
bytes32 authHash = 0x0;
for (uint d = 0; d < invocation.authority.length; d++) {
SignedDelegation memory signedDelegation = invocation.authority[d];
address delegationSigner = verifyDelegationSignature(signedDelegation);
// Implied sending account is the signer of the first delegation
if (d == 0) {
intendedSender = delegationSigner;
canGrant = intendedSender;
}
require(delegationSigner == canGrant, "Delegation signer does not match required signer");
Delegation memory delegation = signedDelegation.delegation;
require(delegation.authority == authHash, "Delegation authority does not match previous delegation");
// TODO: maybe delegations should have replay protection, at least a nonce (non order dependent),
// otherwise once it's revoked, you can't give the exact same permission again.
bytes32 delegationHash = GET_SIGNEDDELEGATION_PACKETHASH(signedDelegation);
// Each delegation can include any number of caveats.
// A caveat is any condition that may reject a proposed transaction.
// The caveats specify an external contract that is passed the proposed tx,
// As well as some extra terms that are used to parameterize the enforcer.
for (uint16 y = 0; y < delegation.caveats.length; y++) {
CaveatEnforcer enforcer = CaveatEnforcer(delegation.caveats[y].enforcer);
bool caveatSuccess = enforcer.enforceCaveat(delegation.caveats[y].terms, invocation.transaction, delegationHash);
require(caveatSuccess, "Caveat rejected");
}
// Store the hash of this delegation in `authHash`
// That way the next delegation can be verified against it.
authHash = delegationHash;
canGrant = delegation.delegate;
}
// Here we perform the requested invocation.
Transaction memory transaction = invocation.transaction;
require(transaction.to == address(this), "Invocation target does not match");
success = execute(
transaction.to,
transaction.data,
transaction.gasLimit,
intendedSender
);
require(success, "Delegator execution failed");
}
}
mapping(address => mapping(uint => uint)) public multiNonce;
function enforceReplayProtection (address intendedSender, ReplayProtection memory protection) private {
uint queue = protection.queue;
uint nonce = protection.nonce;
console.log("Sender %s is trying to use queue %s with nonce %s", intendedSender, queue, nonce);
require(nonce == (multiNonce[intendedSender][queue]+1), "One-at-a-time order enforced. Nonce2 is too small");
multiNonce[intendedSender][queue] = nonce;
}
function execute(
address to,
bytes memory data,
uint256 gasLimit,
address sender
) internal returns (bool success) {
bytes memory full = abi.encodePacked(data, sender);
assembly {
success := call(gasLimit, to, 0, add(full, 0x20), mload(full), 0, 0)
}
}
function verifyInvocationSignature (SignedInvocation memory signedInvocation) public view returns (address) {
bytes32 sigHash = getInvocationsTypedDataHash(signedInvocation.invocations);
address recoveredSignatureSigner = recover(sigHash, signedInvocation.signature);
return recoveredSignatureSigner;
}
function verifyDelegationSignature (SignedDelegation memory signedDelegation) public view returns (address) {
Delegation memory delegation = signedDelegation.delegation;
bytes32 sigHash = getDelegationTypedDataHash(delegation);
address recoveredSignatureSigner = recover(sigHash, signedDelegation.signature);
return recoveredSignatureSigner;
}
function getDelegationTypedDataHash(Delegation memory delegation) public view returns (bytes32) {
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
domainHash,
GET_DELEGATION_PACKETHASH(delegation)
));
return digest;
}
function getInvocationsTypedDataHash (Invocations memory invocations) public view returns (bytes32) {
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
domainHash,
GET_INVOCATIONS_PACKETHASH(invocations)
));
return digest;
}
function getEIP712DomainHash(string memory contractName, string memory version, uint256 chainId, address verifyingContract) public pure returns (bytes32) {
bytes memory encoded = abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(contractName)),
keccak256(bytes(version)),
chainId,
verifyingContract
);
return keccak256(encoded);
}
function _msgSender () internal view virtual returns (address sender) {
if(msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else {
sender = msg.sender;
}
return sender;
}
}
|
If there are no delegations, this invocation comes from the signer Implied sending account is the signer of the first delegation Each delegation can include any number of caveats. A caveat is any condition that may reject a proposed transaction. The caveats specify an external contract that is passed the proposed tx, As well as some extra terms that are used to parameterize the enforcer.
|
function _invoke (Invocation[] calldata batch, address sender) private returns (bool success) {
for (uint x = 0; x < batch.length; x++) {
Invocation memory invocation = batch[x];
address intendedSender;
address canGrant;
if (invocation.authority.length == 0) {
intendedSender = sender;
canGrant = intendedSender;
}
bytes32 authHash = 0x0;
for (uint d = 0; d < invocation.authority.length; d++) {
SignedDelegation memory signedDelegation = invocation.authority[d];
address delegationSigner = verifyDelegationSignature(signedDelegation);
if (d == 0) {
intendedSender = delegationSigner;
canGrant = intendedSender;
}
require(delegationSigner == canGrant, "Delegation signer does not match required signer");
Delegation memory delegation = signedDelegation.delegation;
require(delegation.authority == authHash, "Delegation authority does not match previous delegation");
for (uint16 y = 0; y < delegation.caveats.length; y++) {
CaveatEnforcer enforcer = CaveatEnforcer(delegation.caveats[y].enforcer);
bool caveatSuccess = enforcer.enforceCaveat(delegation.caveats[y].terms, invocation.transaction, delegationHash);
require(caveatSuccess, "Caveat rejected");
}
canGrant = delegation.delegate;
}
require(transaction.to == address(this), "Invocation target does not match");
success = execute(
transaction.to,
transaction.data,
transaction.gasLimit,
intendedSender
);
require(success, "Delegator execution failed");
}
}
mapping(address => mapping(uint => uint)) public multiNonce;
| 13,117,426 |
[
1,
2047,
1915,
854,
1158,
11158,
1012,
16,
333,
9495,
14535,
628,
326,
10363,
2221,
3110,
5431,
2236,
353,
326,
10363,
434,
326,
1122,
23595,
8315,
23595,
848,
2341,
1281,
1300,
434,
276,
836,
2323,
18,
432,
276,
836,
270,
353,
1281,
2269,
716,
2026,
4925,
279,
20084,
2492,
18,
1021,
276,
836,
2323,
4800,
392,
3903,
6835,
716,
353,
2275,
326,
20084,
2229,
16,
2970,
5492,
487,
2690,
2870,
6548,
716,
854,
1399,
358,
1569,
554,
326,
570,
14896,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
225,
445,
389,
14407,
261,
9267,
8526,
745,
892,
2581,
16,
1758,
5793,
13,
3238,
1135,
261,
6430,
2216,
13,
288,
203,
565,
364,
261,
11890,
619,
273,
374,
31,
619,
411,
2581,
18,
2469,
31,
619,
27245,
288,
203,
1377,
11298,
3778,
9495,
273,
2581,
63,
92,
15533,
203,
1377,
1758,
12613,
12021,
31,
203,
1377,
1758,
848,
9021,
31,
203,
203,
1377,
309,
261,
5768,
4431,
18,
24763,
18,
2469,
422,
374,
13,
288,
203,
3639,
12613,
12021,
273,
5793,
31,
203,
3639,
848,
9021,
273,
12613,
12021,
31,
203,
1377,
289,
203,
203,
1377,
1731,
1578,
1357,
2310,
273,
374,
92,
20,
31,
203,
203,
1377,
364,
261,
11890,
302,
273,
374,
31,
302,
411,
9495,
18,
24763,
18,
2469,
31,
302,
27245,
288,
203,
3639,
16724,
26945,
3778,
6726,
26945,
273,
9495,
18,
24763,
63,
72,
15533,
203,
3639,
1758,
23595,
15647,
273,
3929,
26945,
5374,
12,
5679,
26945,
1769,
203,
203,
3639,
309,
261,
72,
422,
374,
13,
288,
203,
1850,
12613,
12021,
273,
23595,
15647,
31,
203,
1850,
848,
9021,
273,
12613,
12021,
31,
203,
3639,
289,
203,
203,
3639,
2583,
12,
3771,
1332,
367,
15647,
422,
848,
9021,
16,
315,
26945,
10363,
1552,
486,
845,
1931,
10363,
8863,
203,
203,
3639,
24117,
367,
3778,
23595,
273,
6726,
26945,
18,
3771,
1332,
367,
31,
203,
3639,
2583,
12,
3771,
1332,
367,
18,
24763,
422,
1357,
2310,
16,
315,
26945,
11675,
1552,
486,
845,
2416,
23595,
8863,
203,
203,
203,
3639,
364,
261,
11890,
2313,
677,
273,
374,
31,
2
] |
./partial_match/97/0xccE5693469A0542AAE3c0ecbafB07006a43718a7/sources/Sota1155General.sol
|
Contract name Contract symbol
|
{
using Strings for string;
address proxyRegistryAddress;
uint256 public _currentTokenID = 0;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public loyaltyFee;
mapping(uint256 => uint256) public tokenSupply;
mapping(uint256 => uint256) public tokenMaxSupply;
string public name;
string public symbol;
event Create(
address indexed _creator,
uint256 indexed _id,
uint256 indexed _loyaltyFee,
uint256 _maxSupply,
uint256 _initSupply
);
constructor(string memory _name, string memory _symbol) public {
name = _name;
symbol = _symbol;
}
function removeWhitelistAdmin(address account) public onlyOwner {
_removeWhitelistAdmin(account);
}
function removeMinter(address account) public onlyOwner {
_removeMinter(account);
}
function uri(uint256 _id) public view returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return Strings.strConcat(baseMetadataURI, Strings.uint2str(_id));
}
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
function maxSupply(uint256 _id) public view returns (uint256) {
return tokenMaxSupply[_id];
}
function setBaseMetadataURI(string memory _newBaseMetadataURI)
public
onlyWhitelistAdmin
{
_setBaseMetadataURI(_newBaseMetadataURI);
}
function create(
uint256 _maxSupply,
uint256 _initialSupply,
uint256 _loyaltyFee,
string memory _uri,
bytes memory _data
) public returns (uint256 tokenId) {
require(
_initialSupply <= _maxSupply,
"Initial supply cannot be more than max supply"
);
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
loyaltyFee[_id] = _loyaltyFee;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
tokenMaxSupply[_id] = _maxSupply;
emit Create(msg.sender, _id, _loyaltyFee, _maxSupply, _initialSupply);
return _id;
}
function create(
uint256 _maxSupply,
uint256 _initialSupply,
uint256 _loyaltyFee,
string memory _uri,
bytes memory _data
) public returns (uint256 tokenId) {
require(
_initialSupply <= _maxSupply,
"Initial supply cannot be more than max supply"
);
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
loyaltyFee[_id] = _loyaltyFee;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
if (_initialSupply != 0) _mint(msg.sender, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
tokenMaxSupply[_id] = _maxSupply;
emit Create(msg.sender, _id, _loyaltyFee, _maxSupply, _initialSupply);
return _id;
}
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public {
uint256 tokenId = _id;
require(creators[tokenId] == msg.sender, "Only-creator-can-mint");
require(
tokenSupply[tokenId] < tokenMaxSupply[tokenId],
"Max supply reached"
);
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
function setProxyAddress(address _proxyRegistryAddress)
public
onlyOwner
returns (bool)
{
proxyRegistryAddress = _proxyRegistryAddress;
return true;
}
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool isOperator)
{
if (proxyRegistryAddress != address(0)) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool isOperator)
{
if (proxyRegistryAddress != address(0)) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
function isApprovedForAll(address _owner, address _operator)
public
view
returns (bool isOperator)
{
if (proxyRegistryAddress != address(0)) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
function _getNextTokenID() private view returns (uint256) {
return _currentTokenID.add(1);
}
function _incrementTokenTypeId() private {
_currentTokenID++;
}
function getCreator(uint256 _id) public view returns (address) {
return creators[_id];
}
function getLoyaltyFee(uint256 _id) public view returns (uint256) {
return loyaltyFee[_id];
}
}
| 11,477,791 |
[
1,
8924,
508,
13456,
3273,
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,
95,
203,
565,
1450,
8139,
364,
533,
31,
203,
203,
565,
1758,
2889,
4243,
1887,
31,
203,
565,
2254,
5034,
1071,
389,
2972,
1345,
734,
273,
374,
31,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
1071,
1519,
3062,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
1071,
437,
93,
15006,
14667,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
1071,
1147,
3088,
1283,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
1071,
1147,
2747,
3088,
1283,
31,
203,
565,
533,
1071,
508,
31,
203,
565,
533,
1071,
3273,
31,
203,
203,
565,
871,
1788,
12,
203,
3639,
1758,
8808,
389,
20394,
16,
203,
3639,
2254,
5034,
8808,
389,
350,
16,
203,
3639,
2254,
5034,
8808,
389,
2466,
15006,
14667,
16,
203,
3639,
2254,
5034,
389,
1896,
3088,
1283,
16,
203,
3639,
2254,
5034,
389,
2738,
3088,
1283,
203,
565,
11272,
203,
203,
203,
565,
3885,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
13,
1071,
288,
203,
3639,
508,
273,
389,
529,
31,
203,
3639,
3273,
273,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
1206,
18927,
4446,
12,
2867,
2236,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
4479,
18927,
4446,
12,
4631,
1769,
203,
565,
289,
203,
203,
565,
445,
1206,
49,
2761,
12,
2867,
2236,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
4479,
49,
2761,
12,
4631,
1769,
203,
565,
289,
203,
203,
565,
445,
2003,
12,
11890,
5034,
389,
350,
13,
1071,
1476,
1135,
2
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-14
*/
//Gorgonzola - GORGO
//Liquidity Fee: 4%
//Marketing Fee: 8%
//Telegram: https://t.me/GorgonzolaETH
pragma solidity ^0.8.1;
// SPDX-License-Identifier: Unlicensed
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
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 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);
}
}
}
}
/**
* @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;
address private _previousOwner;
uint256 private _lockTime;
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;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function 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;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// 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;
}
contract Gorgonzola is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
address deadAddress = 0x000000000000000000000000000000000000dEaD;
string private _name = "Gorgonzola";
string private _symbol = "GORGO";
uint8 private _decimals = 9;
uint256 private initialsupply = 1_000_000_000;
uint256 private _tTotal = initialsupply * 10 ** _decimals;
address payable private _marketingWallet;
address payable private _liquidity;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping(address => uint256) private buycooldown;
mapping(address => uint256) private sellcooldown;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
mapping (address => bool) private _isBlacklisted;
address[] private _excluded;
bool private cooldownEnabled = true;
uint256 public cooldown = 30 seconds;
uint256 private constant MAX = ~uint256(0);
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
uint256 public _taxFee = 0;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 4;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 public _marketingFee = 8;
uint256 private _previousMarketingFee = _marketingFee;
uint256 private maxBuyPercent = 10;
uint256 private maxBuyDivisor = 1000;
uint256 private _maxBuyAmount = (_tTotal * maxBuyPercent) / maxBuyDivisor;
IUniswapV2Router02 public immutable uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 private numTokensSellToAddToLiquidity = _tTotal / 100; // 1%
event ToMarketing(uint256 bnbSent);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor (address marketingWallet) {
_rOwned[_msgSender()] = _rTotal;
_marketingWallet = payable(marketingWallet);
// Pancake Swap V2 address
// IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E);
// uniswap address
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_liquidity = payable(uniswapV2Pair);
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[uniswapV2Pair] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromFee[_marketingWallet] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
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 _tTotal;}
function allowance(address owner, address spender) public view override returns (uint256) {return _allowances[owner][spender];}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function airdrop(address[] memory airdropWallets, uint256[] memory amounts) external onlyOwner returns (bool){
require(airdropWallets.length < 100);
for(uint256 i = 0; i < airdropWallets.length; i++){
address wallet = airdropWallets[i];
uint256 amount = amounts[i];
_transfer(msg.sender, wallet, amount);
}
return true;
}
function setNumTokensSellToAddToLiquidity(uint256 percent, uint256 divisor) external onlyOwner() {
uint256 swapAmount = _tTotal.mul(percent).div(divisor);
numTokensSellToAddToLiquidity = swapAmount;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
_liquidityFee = liquidityFee;
}
function setMarketingFeePercent(uint256 marketingFee) external onlyOwner() {
_marketingFee = marketingFee;
}
function setCooldown(uint256 _cooldown) external onlyOwner() {
cooldown = _cooldown;
}
function setLiquidityAddress(address _liq) public onlyOwner {
require(_liq != address(0));
_liquidity = payable(_liq);
_isExcludedFromFee[_liquidity] = true;
}
function setMaxBuyPercent(uint256 percent, uint divisor) external onlyOwner {
require(percent >= 1 && divisor <= 1000); // cannot set lower than .1%
uint256 new_tx = _tTotal.mul(percent).div(divisor);
require(new_tx >= (_tTotal / 1000), "Max tx must be above 0.1% of total supply.");
_maxBuyAmount = new_tx;
}
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 setBlacklistStatus(address account, bool Blacklisted) external onlyOwner {
if (Blacklisted = true) {
_isBlacklisted[account] = true;
} else if(Blacklisted = false) {
_isBlacklisted[account] = false;
}
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function excludeFromReward(address account) public onlyOwner() {
require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
// require(account != 0x10ED43C718714eb63d5aA57B78B54704E256024E, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to receive ETH from uniswapV2Router when swapping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, tMarketing, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity, tMarketing);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tMarketing = calculateMarketingFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity).sub(tMarketing);
return (tTransferAmount, tFee, tMarketing, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rMarketing = tMarketing.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity).sub(rMarketing);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function _takeMarketing(uint256 tMarketing) private {
uint256 currentRate = _getRate();
uint256 rMarketing = tMarketing.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tMarketing);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateMarketingFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_marketingFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0 && _marketingFee == 0) return;
_previousTaxFee = _taxFee;
_previousMarketingFee = _marketingFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_marketingFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_marketingFee = _previousMarketingFee;
_liquidityFee = _previousLiquidityFee;
}
function _approve(address owner, address spender, uint256 amount) private {
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);
}
// swapAndLiquify takes the balance to be liquified and make sure it is equally distributed
// in BNB and Harold
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// 1/2 balance is sent to the marketing wallet, 1/2 is added to the liquidity pool
uint256 marketingTokenBalance = contractTokenBalance.div(2);
uint256 liquidityTokenBalance = contractTokenBalance.sub(marketingTokenBalance);
uint256 tokenBalanceToLiquifyAsBNB = liquidityTokenBalance.div(2);
uint256 tokenBalanceToLiquify = liquidityTokenBalance.sub(tokenBalanceToLiquifyAsBNB);
uint256 initialBalance = address(this).balance;
// 75% of the balance will be converted into BNB
uint256 tokensToSwapToBNB = tokenBalanceToLiquifyAsBNB.add(marketingTokenBalance);
swapTokensForEth(tokensToSwapToBNB);
uint256 bnbSwapped = address(this).balance.sub(initialBalance);
uint256 bnbToLiquify = bnbSwapped.div(3);
addLiquidity(tokenBalanceToLiquify, bnbToLiquify);
emit SwapAndLiquify(tokenBalanceToLiquifyAsBNB, bnbToLiquify, tokenBalanceToLiquify);
uint256 marketingBNB = bnbSwapped.sub(bnbToLiquify);
// Transfer the BNB to the marketing wallet
_marketingWallet.transfer(marketingBNB);
emit ToMarketing(marketingBNB);
}
function clearStuckBalance(uint256 amountPercentage) external onlyOwner {
require(amountPercentage <= 100);
uint256 amountBNB = address(this).balance;
payable(_marketingWallet).transfer(amountBNB.mul(amountPercentage).div(100));
}
function transferToken(address _token, address _to) external onlyOwner returns (bool _sent){
require(_token != address(0));
uint256 _contractBalance = IERC20(_token).balanceOf(address(this));
_sent = IERC20(_token).transfer(_to, _contractBalance);
}
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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
_liquidity,
block.timestamp
);
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(_isBlacklisted[from] == false, "Hehe");
require(_isBlacklisted[to] == false, "Hehe");
if (from == uniswapV2Pair && to != address(uniswapV2Router) && !_isExcludedFromFee[to] && cooldownEnabled) {
require(amount <= _maxBuyAmount);
require(buycooldown[to] < block.timestamp);
buycooldown[to] = block.timestamp.add(cooldown);
} else if(from == uniswapV2Pair && cooldownEnabled && !_isExcludedFromFee[to]) {
require(sellcooldown[from] <= block.timestamp);
sellcooldown[from] = block.timestamp.add(cooldown);
}
uint256 contractTokenBalance = balanceOf(address(this));
if(contractTokenBalance >= numTokensSellToAddToLiquidity)
{
contractTokenBalance = numTokensSellToAddToLiquidity;
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount,takeFee);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private {
if(!takeFee)
removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if(!takeFee)
restoreAllFee();
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 tMarketing) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeMarketing(tMarketing);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function cooldownStatus() public view returns (bool) {
return cooldownEnabled;
}
function setCooldownEnabled(bool onoff) external onlyOwner() {
cooldownEnabled = onoff;
}
}
|
approve token transfer to cover all possible scenarios add the liquidity
|
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
_liquidity,
block.timestamp
);
}
| 2,339,884 |
[
1,
12908,
537,
1147,
7412,
358,
5590,
777,
3323,
22456,
527,
326,
4501,
372,
24237,
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,
527,
48,
18988,
24237,
12,
11890,
5034,
1147,
6275,
16,
2254,
5034,
13750,
6275,
13,
3238,
288,
203,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
3631,
1147,
6275,
1769,
203,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
1147,
6275,
16,
203,
5411,
389,
549,
372,
24237,
16,
203,
5411,
1203,
18,
5508,
203,
3639,
11272,
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
] |
pragma solidity 0.6.6;
import "./EglToken.sol";
import "./interfaces/IEglGenesis.sol";
import "./libraries/Math.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SignedSafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
/**
* @title EGL Voting Smart Contract
* @author Shane van Coller
*/
contract EglContract is Initializable, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable {
using Math for *;
using SafeMathUpgradeable for *;
using SignedSafeMathUpgradeable for int;
uint8 constant WEEKS_IN_YEAR = 52;
uint constant DECIMAL_PRECISION = 10**18;
/* PUBLIC STATE VARIABLES */
int public desiredEgl;
int public baselineEgl;
int public initialEgl;
int public tallyVotesGasLimit;
uint public creatorEglsTotal;
uint public liquidityEglMatchingTotal;
uint16 public currentEpoch;
uint public currentEpochStartDate;
uint public tokensInCirculation;
uint[52] public voterRewardSums;
uint[8] public votesTotal;
uint[8] public voteWeightsSum;
uint[8] public gasTargetSum;
mapping(address => Voter) public voters;
mapping(address => Supporter) public supporters;
mapping(address => uint) public seeders;
struct Voter {
uint8 lockupDuration;
uint16 voteEpoch;
uint releaseDate;
uint tokensLocked;
uint gasTarget;
}
struct Supporter {
uint32 claimed;
uint poolTokens;
uint firstEgl;
uint lastEgl;
}
/* PRIVATE STATE VARIABLES */
EglToken private eglToken;
IERC20Upgradeable private balancerPoolToken;
IEglGenesis private eglGenesis;
address private creatorRewardsAddress;
int private epochGasLimitSum;
int private epochVoteCount;
int private desiredEglThreshold;
uint24 private votingPauseSeconds;
uint32 private epochLength;
uint private firstEpochStartDate;
uint private latestRewardSwept;
uint private minLiquidityTokensLockup;
uint private creatorRewardFirstEpoch;
uint private remainingPoolReward;
uint private remainingCreatorReward;
uint private remainingDaoBalance;
uint private remainingSeederBalance;
uint private remainingSupporterBalance;
uint private remainingBptBalance;
uint private remainingVoterReward;
uint private lastSerializedEgl;
uint private ethEglRatio;
uint private ethBptRatio;
uint private voterRewardMultiplier;
uint private gasTargetTolerance;
uint16 private voteThresholdGracePeriod;
/* EVENTS */
event Initialized(
address deployer,
address eglContract,
address eglToken,
address genesisContract,
address balancerToken,
uint totalGenesisEth,
uint ethEglRatio,
uint ethBptRatio,
uint minLiquidityTokensLockup,
uint firstEpochStartDate,
uint votingPauseSeconds,
uint epochLength,
uint date
);
event Vote(
address caller,
uint16 currentEpoch,
uint gasTarget,
uint eglAmount,
uint8 lockupDuration,
uint releaseDate,
uint epochVoteWeightSum,
uint epochGasTargetSum,
uint epochVoterRewardSum,
uint epochTotalVotes,
uint date
);
event ReVote(
address caller,
uint gasTarget,
uint eglAmount,
uint date
);
event Withdraw(
address caller,
uint16 currentEpoch,
uint tokensLocked,
uint rewardTokens,
uint gasTarget,
uint epochVoterRewardSum,
uint epochTotalVotes,
uint epochVoteWeightSum,
uint epochGasTargetSum,
uint date
);
event VotesTallied(
address caller,
uint16 currentEpoch,
int desiredEgl,
int averageGasTarget,
uint votingThreshold,
uint actualVotePercentage,
int baselineEgl,
uint tokensInCirculation,
uint date
);
event CreatorRewardsClaimed(
address caller,
address creatorRewardAddress,
uint amountClaimed,
uint lastSerializedEgl,
uint remainingCreatorReward,
uint16 currentEpoch,
uint date
);
event VoteThresholdMet(
address caller,
uint16 currentEpoch,
int desiredEgl,
uint voteThreshold,
uint actualVotePercentage,
int gasLimitSum,
int voteCount,
int baselineEgl,
uint date
);
event VoteThresholdFailed(
address caller,
uint16 currentEpoch,
int desiredEgl,
uint voteThreshold,
uint actualVotePercentage,
int baselineEgl,
int initialEgl,
uint timeSinceFirstEpoch,
uint gracePeriodSeconds,
uint date
);
event PoolRewardsSwept(
address caller,
address coinbaseAddress,
uint blockNumber,
int blockGasLimit,
uint blockReward,
uint date
);
event BlockRewardCalculated(
uint blockNumber,
uint16 currentEpoch,
uint remainingPoolReward,
int blockGasLimit,
int desiredEgl,
int tallyVotesGasLimit,
uint proximityRewardPercent,
uint totalRewardPercent,
uint blockReward,
uint date
);
event SeedAccountClaimed(
address seedAddress,
uint individualSeedAmount,
uint releaseDate,
uint date
);
event VoterRewardCalculated(
address voter,
uint16 currentEpoch,
uint voterReward,
uint epochVoterReward,
uint voteWeight,
uint rewardMultiplier,
uint weeksDiv,
uint epochVoterRewardSum,
uint remainingVoterRewards,
uint date
);
event SupporterTokensClaimed(
address caller,
uint amountContributed,
uint gasTarget,
uint lockDuration,
uint ethEglRatio,
uint ethBptRatio,
uint bonusEglsReceived,
uint poolTokensReceived,
uint remainingSupporterBalance,
uint remainingBptBalance,
uint date
);
event PoolTokensWithdrawn(
address caller,
uint currentSerializedEgl,
uint poolTokensDue,
uint poolTokens,
uint firstEgl,
uint lastEgl,
uint eglReleaseDate,
uint date
);
event SerializedEglCalculated(
uint currentEpoch,
uint secondsSinceEglStart,
uint timePassedPercentage,
uint serializedEgl,
uint maxSupply,
uint date
);
event SeedAccountAdded(
address seedAccount,
uint seedAmount,
uint remainingSeederBalance,
uint date
);
/**
* @notice Revert any transactions that attempts to send ETH to the contract directly
*/
receive() external payable {
revert("EGL:NO_PAYMENTS");
}
/* EXTERNAL FUNCTIONS */
/**
* @notice Initialized contract variables and sets up token bucket sizes
*
* @param _token Address of the EGL token
* @param _poolToken Address of the Balance Pool Token (BPT)
* @param _genesis Address of the EGL Genesis contract
* @param _currentEpochStartDate Start date for the first epoch
* @param _votingPauseSeconds Number of seconds to pause voting before votes are tallied
* @param _epochLength The length of each epoch in seconds
* @param _seedAccounts List of accounts to seed with EGL's
* @param _seedAmounts Amount of EGLS's to seed accounts with
* @param _creatorRewardsAccount Address that creator rewards get sent to
*/
function initialize(
address _token,
address _poolToken,
address _genesis,
uint _currentEpochStartDate,
uint24 _votingPauseSeconds,
uint32 _epochLength,
address[] memory _seedAccounts,
uint[] memory _seedAmounts,
address _creatorRewardsAccount
)
public
initializer
{
require(_token != address(0), "EGL:INVALID_EGL_TOKEN_ADDR");
require(_poolToken != address(0), "EGL:INVALID_BP_TOKEN_ADDR");
require(_genesis != address(0), "EGL:INVALID_GENESIS_ADDR");
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
eglToken = EglToken(_token);
balancerPoolToken = IERC20Upgradeable(_poolToken);
eglGenesis = IEglGenesis(_genesis);
creatorEglsTotal = 750000000 ether;
remainingCreatorReward = creatorEglsTotal;
liquidityEglMatchingTotal = 750000000 ether;
remainingPoolReward = 1250000000 ether;
remainingDaoBalance = 250000000 ether;
remainingSeederBalance = 50000000 ether;
remainingSupporterBalance = 500000000 ether;
remainingVoterReward = 500000000 ether;
voterRewardMultiplier = 362844.70 ether;
uint totalGenesisEth = eglGenesis.cumulativeBalance();
require(totalGenesisEth > 0, "EGL:NO_GENESIS_BALANCE");
remainingBptBalance = balancerPoolToken.balanceOf(eglGenesis.owner());
require(remainingBptBalance > 0, "EGL:NO_BPT_BALANCE");
ethEglRatio = liquidityEglMatchingTotal.mul(DECIMAL_PRECISION)
.div(totalGenesisEth);
ethBptRatio = remainingBptBalance.mul(DECIMAL_PRECISION)
.div(totalGenesisEth);
creatorRewardFirstEpoch = 10;
minLiquidityTokensLockup = _epochLength.mul(10);
firstEpochStartDate = _currentEpochStartDate;
currentEpochStartDate = _currentEpochStartDate;
votingPauseSeconds = _votingPauseSeconds;
epochLength = _epochLength;
creatorRewardsAddress = _creatorRewardsAccount;
tokensInCirculation = liquidityEglMatchingTotal;
tallyVotesGasLimit = int(block.gaslimit);
baselineEgl = int(block.gaslimit);
initialEgl = baselineEgl;
desiredEgl = baselineEgl;
gasTargetTolerance = 4000000;
desiredEglThreshold = 1000000;
voteThresholdGracePeriod = 7;
if (_seedAccounts.length > 0) {
for (uint8 i = 0; i < _seedAccounts.length; i++) {
addSeedAccount(_seedAccounts[i], _seedAmounts[i]);
}
}
emit Initialized(
msg.sender,
address(this),
address(eglToken),
address(eglGenesis),
address(balancerPoolToken),
totalGenesisEth,
ethEglRatio,
ethBptRatio,
minLiquidityTokensLockup,
firstEpochStartDate,
votingPauseSeconds,
epochLength,
block.timestamp
);
}
/**
* @notice Allows EGL Genesis contributors to claim their "bonus" EGL's from contributing in Genesis. Bonus EGL's
* get locked up in a vote right away and can only be withdrawn once all BPT's are available
*
* @param _gasTarget desired gas target for initial vote
* @param _lockupDuration duration to lock tokens for - determines vote multiplier
*/
function claimSupporterEgls(uint _gasTarget, uint8 _lockupDuration) external whenNotPaused {
require(remainingSupporterBalance > 0, "EGL:SUPPORTER_EGLS_DEPLETED");
require(remainingBptBalance > 0, "EGL:BPT_BALANCE_DEPLETED");
require(
eglGenesis.canContribute() == false && eglGenesis.canWithdraw() == false,
"EGL:GENESIS_LOCKED"
);
require(supporters[msg.sender].claimed == 0, "EGL:ALREADY_CLAIMED");
(uint contributionAmount, uint cumulativeBalance, ,) = eglGenesis.contributors(msg.sender);
require(contributionAmount > 0, "EGL:NOT_CONTRIBUTED");
if (block.timestamp > currentEpochStartDate.add(epochLength))
tallyVotes();
uint serializedEgls = contributionAmount.mul(ethEglRatio).div(DECIMAL_PRECISION);
uint firstEgl = cumulativeBalance.sub(contributionAmount)
.mul(ethEglRatio)
.div(DECIMAL_PRECISION);
uint lastEgl = firstEgl.add(serializedEgls);
uint bonusEglsDue = Math.umin(
_calculateBonusEglsDue(firstEgl, lastEgl),
remainingSupporterBalance
);
uint poolTokensDue = Math.umin(
contributionAmount.mul(ethBptRatio).div(DECIMAL_PRECISION),
remainingBptBalance
);
remainingSupporterBalance = remainingSupporterBalance.sub(bonusEglsDue);
remainingBptBalance = remainingBptBalance.sub(poolTokensDue);
tokensInCirculation = tokensInCirculation.add(bonusEglsDue);
Supporter storage _supporter = supporters[msg.sender];
_supporter.claimed = 1;
_supporter.poolTokens = poolTokensDue;
_supporter.firstEgl = firstEgl;
_supporter.lastEgl = lastEgl;
emit SupporterTokensClaimed(
msg.sender,
contributionAmount,
_gasTarget,
_lockupDuration,
ethEglRatio,
ethBptRatio,
bonusEglsDue,
poolTokensDue,
remainingSupporterBalance,
remainingBptBalance,
block.timestamp
);
_internalVote(
msg.sender,
_gasTarget,
bonusEglsDue,
_lockupDuration,
firstEpochStartDate.add(epochLength.mul(WEEKS_IN_YEAR))
);
}
/**
* @notice Function for seed/signal accounts to claim their EGL's. EGL's get locked up in a vote right away and can
* only be withdrawn after the seeder/signal lockup period
*
* @param _gasTarget desired gas target for initial vote
* @param _lockupDuration duration to lock tokens for - determines vote multiplier
*/
function claimSeederEgls(uint _gasTarget, uint8 _lockupDuration) external whenNotPaused {
require(seeders[msg.sender] > 0, "EGL:NOT_SEEDER");
if (block.timestamp > currentEpochStartDate.add(epochLength))
tallyVotes();
uint seedAmount = seeders[msg.sender];
delete seeders[msg.sender];
tokensInCirculation = tokensInCirculation.add(seedAmount);
uint releaseDate = firstEpochStartDate.add(epochLength.mul(WEEKS_IN_YEAR));
emit SeedAccountClaimed(msg.sender, seedAmount, releaseDate, block.timestamp);
_internalVote(
msg.sender,
_gasTarget,
seedAmount,
_lockupDuration,
releaseDate
);
}
/**
* @notice Submit vote to either increase or decrease the desired gas limit
*
* @param _gasTarget The votes target gas limit
* @param _eglAmount Amount of EGL's to vote with
* @param _lockupDuration Duration to lock the EGL's
*/
function vote(
uint _gasTarget,
uint _eglAmount,
uint8 _lockupDuration
)
external
whenNotPaused
nonReentrant
{
require(_eglAmount >= 1 ether, "EGL:AMNT_TOO_LOW");
require(_eglAmount <= eglToken.balanceOf(msg.sender), "EGL:INSUFFICIENT_EGL_BALANCE");
require(eglToken.allowance(msg.sender, address(this)) >= _eglAmount, "EGL:INSUFFICIENT_ALLOWANCE");
if (block.timestamp > currentEpochStartDate.add(epochLength))
tallyVotes();
bool success = eglToken.transferFrom(msg.sender, address(this), _eglAmount);
require(success, "EGL:TOKEN_TRANSFER_FAILED");
_internalVote(
msg.sender,
_gasTarget,
_eglAmount,
_lockupDuration,
0
);
}
/**
* @notice Re-Vote to change parameters of an existing vote. Will not shorten the time the tokens are
* locked up from the original vote
*
* @param _gasTarget The votes target gas limit
* @param _eglAmount Amount of EGL's to vote with
* @param _lockupDuration Duration to lock the EGL's
*/
function reVote(
uint _gasTarget,
uint _eglAmount,
uint8 _lockupDuration
)
external
whenNotPaused
nonReentrant
{
require(voters[msg.sender].tokensLocked > 0, "EGL:NOT_VOTED");
if (_eglAmount > 0) {
require(_eglAmount >= 1 ether, "EGL:AMNT_TOO_LOW");
require(_eglAmount <= eglToken.balanceOf(msg.sender), "EGL:INSUFFICIENT_EGL_BALANCE");
require(eglToken.allowance(msg.sender, address(this)) >= _eglAmount, "EGL:INSUFFICIENT_ALLOWANCE");
bool success = eglToken.transferFrom(msg.sender, address(this), _eglAmount);
require(success, "EGL:TOKEN_TRANSFER_FAILED");
}
if (block.timestamp > currentEpochStartDate.add(epochLength))
tallyVotes();
uint originalReleaseDate = voters[msg.sender].releaseDate;
_eglAmount = _eglAmount.add(_internalWithdraw(msg.sender));
_internalVote(
msg.sender,
_gasTarget,
_eglAmount,
_lockupDuration,
originalReleaseDate
);
emit ReVote(msg.sender, _gasTarget, _eglAmount, block.timestamp);
}
/**
* @notice Withdraw EGL's once they have matured
*/
function withdraw() external whenNotPaused {
require(voters[msg.sender].tokensLocked > 0, "EGL:NOT_VOTED");
require(block.timestamp > voters[msg.sender].releaseDate, "EGL:NOT_RELEASE_DATE");
bool success = eglToken.transfer(msg.sender, _internalWithdraw(msg.sender));
require(success, "EGL:TOKEN_TRANSFER_FAILED");
}
/**
* @notice Send EGL reward to miner of the block. Reward caclulated based on how close the block gas limit
* is to the desired EGL. The closer it is, the higher the reward
*/
function sweepPoolRewards() external whenNotPaused {
require(block.number > latestRewardSwept, "EGL:ALREADY_SWEPT");
latestRewardSwept = block.number;
int blockGasLimit = int(block.gaslimit);
uint blockReward = _calculateBlockReward(blockGasLimit, desiredEgl, tallyVotesGasLimit);
if (blockReward > 0) {
remainingPoolReward = remainingPoolReward.sub(blockReward);
tokensInCirculation = tokensInCirculation.add(blockReward);
bool success = eglToken.transfer(block.coinbase, Math.umin(eglToken.balanceOf(address(this)), blockReward));
require(success, "EGL:TOKEN_TRANSFER_FAILED");
}
emit PoolRewardsSwept(
msg.sender,
block.coinbase,
latestRewardSwept,
blockGasLimit,
blockReward,
block.timestamp
);
}
/**
* @notice Allows for the withdrawal of liquidity pool tokens once they have matured
*/
function withdrawPoolTokens() external whenNotPaused {
require(supporters[msg.sender].poolTokens > 0, "EGL:NO_POOL_TOKENS");
require(block.timestamp.sub(firstEpochStartDate) > minLiquidityTokensLockup, "EGL:ALL_TOKENS_LOCKED");
uint currentSerializedEgl = _calculateSerializedEgl(
block.timestamp.sub(firstEpochStartDate),
liquidityEglMatchingTotal,
minLiquidityTokensLockup
);
Voter storage _voter = voters[msg.sender];
Supporter storage _supporter = supporters[msg.sender];
require(_supporter.firstEgl <= currentSerializedEgl, "EGL:ADDR_TOKENS_LOCKED");
uint poolTokensDue;
if (currentSerializedEgl >= _supporter.lastEgl) {
poolTokensDue = _supporter.poolTokens;
_supporter.poolTokens = 0;
uint releaseEpoch = _voter.voteEpoch.add(_voter.lockupDuration);
_voter.releaseDate = releaseEpoch > currentEpoch
? block.timestamp.add(releaseEpoch.sub(currentEpoch).mul(epochLength))
: block.timestamp;
emit PoolTokensWithdrawn(
msg.sender,
currentSerializedEgl,
poolTokensDue,
_supporter.poolTokens,
_supporter.firstEgl,
_supporter.lastEgl,
_voter.releaseDate,
block.timestamp
);
} else {
poolTokensDue = _calculateCurrentPoolTokensDue(
currentSerializedEgl,
_supporter.firstEgl,
_supporter.lastEgl,
_supporter.poolTokens
);
_supporter.poolTokens = _supporter.poolTokens.sub(poolTokensDue);
emit PoolTokensWithdrawn(
msg.sender,
currentSerializedEgl,
poolTokensDue,
_supporter.poolTokens,
_supporter.firstEgl,
_supporter.lastEgl,
_voter.releaseDate,
block.timestamp
);
_supporter.firstEgl = currentSerializedEgl;
}
bool success = balancerPoolToken.transfer(
msg.sender,
Math.umin(balancerPoolToken.balanceOf(address(this)), poolTokensDue)
);
require(success, "EGL:TOKEN_TRANSFER_FAILED");
}
/**
* @notice Ower only funciton to pause contract
*/
function pauseEgl() external onlyOwner whenNotPaused {
_pause();
}
/**
* @notice Owner only function to unpause contract
*/
function unpauseEgl() external onlyOwner whenPaused {
_unpause();
}
/* PUBLIC FUNCTIONS */
/**
* @notice Tally Votes for the most recent epoch and calculate the new desired EGL amount
*/
function tallyVotes() public whenNotPaused {
require(block.timestamp > currentEpochStartDate.add(epochLength), "EGL:VOTE_NOT_ENDED");
tallyVotesGasLimit = int(block.gaslimit);
uint votingThreshold = currentEpoch <= voteThresholdGracePeriod
? DECIMAL_PRECISION.mul(10)
: DECIMAL_PRECISION.mul(30);
if (currentEpoch >= WEEKS_IN_YEAR) {
uint actualThreshold = votingThreshold.add(
(DECIMAL_PRECISION.mul(20).div(WEEKS_IN_YEAR.mul(2)))
.mul(currentEpoch.sub(WEEKS_IN_YEAR.sub(1)))
);
votingThreshold = Math.umin(actualThreshold, 50 * DECIMAL_PRECISION);
}
int averageGasTarget = voteWeightsSum[0] > 0
? int(gasTargetSum[0].div(voteWeightsSum[0]))
: 0;
uint votePercentage = _calculatePercentageOfTokensInCirculation(votesTotal[0]);
if (votePercentage >= votingThreshold) {
epochGasLimitSum = epochGasLimitSum.add(int(tallyVotesGasLimit));
epochVoteCount = epochVoteCount.add(1);
baselineEgl = epochGasLimitSum.div(epochVoteCount);
desiredEgl = baselineEgl > averageGasTarget
? baselineEgl.sub(baselineEgl.sub(averageGasTarget).min(desiredEglThreshold))
: baselineEgl.add(averageGasTarget.sub(baselineEgl).min(desiredEglThreshold));
if (
desiredEgl >= tallyVotesGasLimit.sub(10000) &&
desiredEgl <= tallyVotesGasLimit.add(10000)
)
desiredEgl = tallyVotesGasLimit;
emit VoteThresholdMet(
msg.sender,
currentEpoch,
desiredEgl,
votingThreshold,
votePercentage,
epochGasLimitSum,
epochVoteCount,
baselineEgl,
block.timestamp
);
} else {
if (block.timestamp.sub(firstEpochStartDate) >= epochLength.mul(voteThresholdGracePeriod))
desiredEgl = tallyVotesGasLimit.mul(95).div(100);
emit VoteThresholdFailed(
msg.sender,
currentEpoch,
desiredEgl,
votingThreshold,
votePercentage,
baselineEgl,
initialEgl,
block.timestamp.sub(firstEpochStartDate),
epochLength.mul(6),
block.timestamp
);
}
// move values 1 slot earlier and put a '0' at the last slot
for (uint8 i = 0; i < 7; i++) {
voteWeightsSum[i] = voteWeightsSum[i + 1];
gasTargetSum[i] = gasTargetSum[i + 1];
votesTotal[i] = votesTotal[i + 1];
}
voteWeightsSum[7] = 0;
gasTargetSum[7] = 0;
votesTotal[7] = 0;
epochGasLimitSum = 0;
epochVoteCount = 0;
if (currentEpoch >= creatorRewardFirstEpoch && remainingCreatorReward > 0)
_issueCreatorRewards(currentEpoch);
currentEpoch += 1;
currentEpochStartDate = currentEpochStartDate.add(epochLength);
emit VotesTallied(
msg.sender,
currentEpoch - 1,
desiredEgl,
averageGasTarget,
votingThreshold,
votePercentage,
baselineEgl,
tokensInCirculation,
block.timestamp
);
}
/**
* @notice Owner only function to add a seeder account with specified number of EGL's. Amount cannot
* exceed balance allocated for seed/signal accounts
*
* @param _seedAccount Wallet address of seeder
* @param _seedAmount Amount of EGL's to seed
*/
function addSeedAccount(address _seedAccount, uint _seedAmount) public onlyOwner {
require(_seedAmount <= remainingSeederBalance, "EGL:INSUFFICIENT_SEED_BALANCE");
require(seeders[_seedAccount] == 0, "EGL:ALREADY_SEEDER");
require(voters[_seedAccount].tokensLocked == 0, "EGL:ALREADY_HAS_VOTE");
require(eglToken.balanceOf(_seedAccount) == 0, "EGL:ALREADY_HAS_EGLS");
require(block.timestamp < firstEpochStartDate.add(minLiquidityTokensLockup), "EGL:SEED_PERIOD_PASSED");
(uint contributorAmount,,,) = eglGenesis.contributors(_seedAccount);
require(contributorAmount == 0, "EGL:IS_CONTRIBUTOR");
remainingSeederBalance = remainingSeederBalance.sub(_seedAmount);
remainingDaoBalance = remainingDaoBalance.sub(_seedAmount);
seeders[_seedAccount] = _seedAmount;
emit SeedAccountAdded(
_seedAccount,
_seedAmount,
remainingSeederBalance,
block.timestamp
);
}
/**
* @notice Do not allow owner to renounce ownership, only transferOwnership
*/
function renounceOwnership() public override onlyOwner {
revert("EGL:NO_RENOUNCE_OWNERSHIP");
}
/* INTERNAL FUNCTIONS */
/**
* @notice Internal function that adds the vote
*
* @param _voter Address the vote should to assigned to
* @param _gasTarget The target gas limit amount
* @param _eglAmount Amount of EGL's to vote with
* @param _lockupDuration Duration to lock the EGL's
* @param _releaseTime Date the EGL's are available to withdraw
*/
function _internalVote(
address _voter,
uint _gasTarget,
uint _eglAmount,
uint8 _lockupDuration,
uint _releaseTime
) internal {
require(_voter != address(0), "EGL:VOTER_ADDRESS_0");
require(block.timestamp >= firstEpochStartDate, "EGL:VOTING_NOT_STARTED");
require(voters[_voter].tokensLocked == 0, "EGL:ALREADY_VOTED");
require(
Math.udelta(_gasTarget, block.gaslimit) < gasTargetTolerance,
"EGL:INVALID_GAS_TARGET"
);
require(_lockupDuration >= 1 && _lockupDuration <= 8, "EGL:INVALID_LOCKUP");
require(block.timestamp < currentEpochStartDate.add(epochLength), "EGL:VOTE_TOO_FAR");
require(block.timestamp < currentEpochStartDate.add(epochLength).sub(votingPauseSeconds), "EGL:VOTE_TOO_CLOSE");
epochGasLimitSum = epochGasLimitSum.add(int(block.gaslimit));
epochVoteCount = epochVoteCount.add(1);
uint updatedReleaseDate = block.timestamp.add(_lockupDuration.mul(epochLength)).umax(_releaseTime);
Voter storage voter = voters[_voter];
voter.voteEpoch = currentEpoch;
voter.lockupDuration = _lockupDuration;
voter.releaseDate = updatedReleaseDate;
voter.tokensLocked = _eglAmount;
voter.gasTarget = _gasTarget;
// Add the vote
uint voteWeight = _eglAmount.mul(_lockupDuration);
for (uint8 i = 0; i < _lockupDuration; i++) {
voteWeightsSum[i] = voteWeightsSum[i].add(voteWeight);
gasTargetSum[i] = gasTargetSum[i].add(_gasTarget.mul(voteWeight));
if (currentEpoch.add(i) < WEEKS_IN_YEAR)
voterRewardSums[currentEpoch.add(i)] = voterRewardSums[currentEpoch.add(i)].add(voteWeight);
votesTotal[i] = votesTotal[i].add(_eglAmount);
}
emit Vote(
_voter,
currentEpoch,
_gasTarget,
_eglAmount,
_lockupDuration,
updatedReleaseDate,
voteWeightsSum[0],
gasTargetSum[0],
currentEpoch < WEEKS_IN_YEAR ? voterRewardSums[currentEpoch]: 0,
votesTotal[0],
block.timestamp
);
}
/**
* @notice Internal function that removes the vote from current and future epochs as well as
* calculates the rewards due for the time the tokens were locked
*
* @param _voter Address the voter for be withdrawn for
* @return totalWithdrawn - The original vote amount + the total reward tokens due
*/
function _internalWithdraw(address _voter) internal returns (uint totalWithdrawn) {
require(_voter != address(0), "EGL:VOTER_ADDRESS_0");
Voter storage voter = voters[_voter];
uint16 voterEpoch = voter.voteEpoch;
uint originalEglAmount = voter.tokensLocked;
uint8 lockupDuration = voter.lockupDuration;
uint gasTarget = voter.gasTarget;
delete voters[_voter];
uint voteWeight = originalEglAmount.mul(lockupDuration);
uint voterReward = _calculateVoterReward(_voter, currentEpoch, voterEpoch, lockupDuration, voteWeight);
// Remove the gas target vote
uint voterInterval = voterEpoch.add(lockupDuration);
uint affectedEpochs = currentEpoch < voterInterval ? voterInterval.sub(currentEpoch) : 0;
for (uint8 i = 0; i < affectedEpochs; i++) {
voteWeightsSum[i] = voteWeightsSum[i].sub(voteWeight);
gasTargetSum[i] = gasTargetSum[i].sub(voteWeight.mul(gasTarget));
if (currentEpoch.add(i) < WEEKS_IN_YEAR) {
voterRewardSums[currentEpoch.add(i)] = voterRewardSums[currentEpoch.add(i)].sub(voteWeight);
}
votesTotal[i] = votesTotal[i].sub(originalEglAmount);
}
tokensInCirculation = tokensInCirculation.add(voterReward);
emit Withdraw(
_voter,
currentEpoch,
originalEglAmount,
voterReward,
gasTarget,
currentEpoch < WEEKS_IN_YEAR ? voterRewardSums[currentEpoch]: 0,
votesTotal[0],
voteWeightsSum[0],
gasTargetSum[0],
block.timestamp
);
totalWithdrawn = originalEglAmount.add(voterReward);
}
/**
* @notice Calculates and issues creator reward EGLs' based on the release schedule
*
* @param _rewardEpoch The epoch number to calcualte the rewards for
*/
function _issueCreatorRewards(uint _rewardEpoch) internal {
uint serializedEgl = _calculateSerializedEgl(
_rewardEpoch.mul(epochLength),
creatorEglsTotal,
creatorRewardFirstEpoch.mul(epochLength)
);
uint creatorRewardForEpoch = serializedEgl > 0
? serializedEgl.sub(lastSerializedEgl).umin(remainingCreatorReward)
: 0;
bool success = eglToken.transfer(creatorRewardsAddress, creatorRewardForEpoch);
require(success, "EGL:TOKEN_TRANSFER_FAILED");
remainingCreatorReward = remainingCreatorReward.sub(creatorRewardForEpoch);
tokensInCirculation = tokensInCirculation.add(creatorRewardForEpoch);
emit CreatorRewardsClaimed(
msg.sender,
creatorRewardsAddress,
creatorRewardForEpoch,
lastSerializedEgl,
remainingCreatorReward,
currentEpoch,
block.timestamp
);
lastSerializedEgl = serializedEgl;
}
/**
* @notice Calulates the block reward depending on the current blocks gas limit
*
* @param _blockGasLimit Gas limit of the currently mined block
* @param _desiredEgl Current desired EGL value
* @param _tallyVotesGasLimit Gas limit of the block that contained the tally votes tx
* @return blockReward The calculated block reward
*/
function _calculateBlockReward(
int _blockGasLimit,
int _desiredEgl,
int _tallyVotesGasLimit
)
internal
returns (uint blockReward)
{
uint totalRewardPercent;
uint proximityRewardPercent;
int eglDelta = Math.delta(_tallyVotesGasLimit, _desiredEgl);
int actualDelta = Math.delta(_tallyVotesGasLimit, _blockGasLimit);
int ceiling = _desiredEgl.add(10000);
int floor = _desiredEgl.sub(10000);
if (_blockGasLimit >= floor && _blockGasLimit <= ceiling) {
totalRewardPercent = DECIMAL_PRECISION.mul(100);
} else if (eglDelta > 0 && (
(
_desiredEgl > _tallyVotesGasLimit
&& _blockGasLimit > _tallyVotesGasLimit
&& _blockGasLimit <= ceiling
) || (
_desiredEgl < _tallyVotesGasLimit
&& _blockGasLimit < _tallyVotesGasLimit
&& _blockGasLimit >= floor
)
)
) {
proximityRewardPercent = uint(actualDelta.mul(int(DECIMAL_PRECISION))
.div(eglDelta))
.mul(75);
totalRewardPercent = proximityRewardPercent.add(DECIMAL_PRECISION.mul(25));
}
blockReward = totalRewardPercent.mul(remainingPoolReward.div(2500000))
.div(DECIMAL_PRECISION)
.div(100);
emit BlockRewardCalculated(
block.number,
currentEpoch,
remainingPoolReward,
_blockGasLimit,
_desiredEgl,
_tallyVotesGasLimit,
proximityRewardPercent,
totalRewardPercent,
blockReward,
block.timestamp
);
}
/**
* @notice Calculates the current serialized EGL given a time input
*
* @param _timeSinceOrigin Seconds passed since the first epoch started
* @param _maxEglSupply The maximum supply of EGL's for the thing we're calculating for
* @param _timeLocked The minimum lockup period for the thing we're calculating for
* @return serializedEgl The serialized EGL for the exact second the function was called
*/
function _calculateSerializedEgl(uint _timeSinceOrigin, uint _maxEglSupply, uint _timeLocked)
internal
returns (uint serializedEgl)
{
if (_timeSinceOrigin >= epochLength.mul(WEEKS_IN_YEAR))
return _maxEglSupply;
uint timePassedPercentage = _timeSinceOrigin
.sub(_timeLocked)
.mul(DECIMAL_PRECISION)
.div(
epochLength.mul(WEEKS_IN_YEAR).sub(_timeLocked)
);
// Reduced precision so that we don't overflow the uint256 when we raise to 4th power
serializedEgl = ((timePassedPercentage.div(10**8))**4)
.mul(_maxEglSupply.div(DECIMAL_PRECISION))
.mul(10**8)
.div((10**10)**3);
emit SerializedEglCalculated(
currentEpoch,
_timeSinceOrigin,
timePassedPercentage.mul(100),
serializedEgl,
_maxEglSupply,
block.timestamp
);
}
/**
* @notice Calculates the pool tokens due at time of calling
*
* @param _currentEgl The current serialized EGL
* @param _firstEgl The first serialized EGL of the participant
* @param _lastEgl The last serialized EGL of the participant
* @param _totalPoolTokens The total number of pool tokens due to the participant
* @return poolTokensDue The number of pool tokens due based on the serialized EGL
*/
function _calculateCurrentPoolTokensDue(
uint _currentEgl,
uint _firstEgl,
uint _lastEgl,
uint _totalPoolTokens
)
internal
pure
returns (uint poolTokensDue)
{
require(_firstEgl < _lastEgl, "EGL:INVALID_SERIALIZED_EGLS");
if (_currentEgl < _firstEgl)
return 0;
uint eglsReleased = (_currentEgl.umin(_lastEgl)).sub(_firstEgl);
poolTokensDue = _totalPoolTokens
.mul(eglsReleased)
.div(
_lastEgl.sub(_firstEgl)
);
}
/**
* @notice Calculates bonus EGLs due
*
* @param _firstEgl The first serialized EGL of the participant
* @param _lastEgl The last serialized EGL of the participant
* @return bonusEglsDue The number of bonus EGL's due as a result of participating in Genesis
*/
function _calculateBonusEglsDue(
uint _firstEgl,
uint _lastEgl
)
internal
pure
returns (uint bonusEglsDue)
{
require(_firstEgl < _lastEgl, "EGL:INVALID_SERIALIZED_EGLS");
bonusEglsDue = (_lastEgl.div(DECIMAL_PRECISION)**4)
.sub(_firstEgl.div(DECIMAL_PRECISION)**4)
.mul(DECIMAL_PRECISION)
.div(
(81/128)*(10**27)
);
}
/**
* @notice Calculates voter reward at time of withdrawal
*
* @param _voter The voter to calculate rewards for
* @param _currentEpoch The current epoch to calculate rewards for
* @param _voterEpoch The epoch the vote was originally entered
* @param _lockupDuration The number of epochs the vote is locked up for
* @param _voteWeight The vote weight for this vote (vote amount * lockup duration)
* @return rewardsDue The total rewards due for all relevant epochs
*/
function _calculateVoterReward(
address _voter,
uint16 _currentEpoch,
uint16 _voterEpoch,
uint8 _lockupDuration,
uint _voteWeight
)
internal
returns(uint rewardsDue)
{
require(_voter != address(0), "EGL:VOTER_ADDRESS_0");
uint rewardEpochs = _voterEpoch.add(_lockupDuration).umin(_currentEpoch).umin(WEEKS_IN_YEAR);
for (uint16 i = _voterEpoch; i < rewardEpochs; i++) {
uint epochReward = voterRewardSums[i] > 0
? Math.umin(
_voteWeight.mul(voterRewardMultiplier)
.mul(WEEKS_IN_YEAR.sub(i))
.div(voterRewardSums[i]),
remainingVoterReward
)
: 0;
rewardsDue = rewardsDue.add(epochReward);
remainingVoterReward = remainingVoterReward.sub(epochReward);
emit VoterRewardCalculated(
_voter,
_currentEpoch,
rewardsDue,
epochReward,
_voteWeight,
voterRewardMultiplier,
WEEKS_IN_YEAR.sub(i),
voterRewardSums[i],
remainingVoterReward,
block.timestamp
);
}
}
/**
* @notice Calculates the percentage of tokens in circulation for a given total
*
* @param _total The total to calculate the percentage of
* @return votePercentage The percentage of the total
*/
function _calculatePercentageOfTokensInCirculation(uint _total)
internal
view
returns (uint votePercentage)
{
votePercentage = tokensInCirculation > 0
? _total.mul(DECIMAL_PRECISION).mul(100).div(tokensInCirculation)
: 0;
}
}
pragma solidity 0.6.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20CappedUpgradeable.sol";
contract EglToken is Initializable, ContextUpgradeable, ERC20CappedUpgradeable {
function initialize(
address initialRecipient,
string memory name,
string memory symbol,
uint256 initialSupply
)
public
initializer
{
require(initialRecipient != address(0), "EGLTOKEN:INVALID_RECIPIENT");
__ERC20_init(name, symbol);
__ERC20Capped_init_unchained(initialSupply);
_mint(initialRecipient, initialSupply);
}
}
pragma solidity 0.6.6;
interface IEglGenesis {
function owner() external view returns(address);
function cumulativeBalance() external view returns(uint);
function canContribute() external view returns(bool);
function canWithdraw() external view returns(bool);
function contributors(address contributor) external view returns(uint, uint, uint, uint);
}
pragma solidity ^0.6.0;
library Math {
/**
* @dev Returns max value of 2 unsigned ints
*/
function umax(uint a, uint b) internal pure returns (uint) {
return a >= b ? a : b;
}
/**
* @dev Returns min value of 2 unsigned ints
*/
function umin(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
/**
* @dev Returns max value of 2 signed ints
*/
function max(int a, int b) internal pure returns (int) {
return a >= b ? a : b;
}
/**
* @dev Returns min value of 2 signed ints
*/
function min(int a, int b) internal pure returns (int) {
return a < b ? a : b;
}
/**
* @dev Returns the positive delta between 2 unsigned ints
*/
function udelta(uint a, uint b) internal pure returns (uint) {
return a > b ? a - b : b - a;
}
/**
* @dev Returns the positive delta between 2 signed ints
*/
function delta(int a, int b) internal pure returns (int) {
return a > b ? a - b : b - a;
}
}
// 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
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMathUpgradeable {
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;
}
}
// 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.6.0 <0.8.0;
import "./ERC20Upgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable {
using SafeMathUpgradeable for uint256;
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
function __ERC20Capped_init(uint256 cap_) internal initializer {
__Context_init_unchained();
__ERC20Capped_init_unchained(cap_);
}
function __ERC20Capped_init_unchained(uint256 cap_) internal initializer {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable 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.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_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 { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
|
* @notice Calculates voter reward at time of withdrawal @param _voter The voter to calculate rewards for @param _currentEpoch The current epoch to calculate rewards for @param _voterEpoch The epoch the vote was originally entered @param _lockupDuration The number of epochs the vote is locked up for @param _voteWeight The vote weight for this vote (vote amount lockup duration) @return rewardsDue The total rewards due for all relevant epochs/
|
function _calculateVoterReward(
address _voter,
uint16 _currentEpoch,
uint16 _voterEpoch,
uint8 _lockupDuration,
uint _voteWeight
)
internal
returns(uint rewardsDue)
{
require(_voter != address(0), "EGL:VOTER_ADDRESS_0");
uint rewardEpochs = _voterEpoch.add(_lockupDuration).umin(_currentEpoch).umin(WEEKS_IN_YEAR);
for (uint16 i = _voterEpoch; i < rewardEpochs; i++) {
uint epochReward = voterRewardSums[i] > 0
? Math.umin(
_voteWeight.mul(voterRewardMultiplier)
.mul(WEEKS_IN_YEAR.sub(i))
.div(voterRewardSums[i]),
remainingVoterReward
)
: 0;
rewardsDue = rewardsDue.add(epochReward);
remainingVoterReward = remainingVoterReward.sub(epochReward);
emit VoterRewardCalculated(
_voter,
_currentEpoch,
rewardsDue,
epochReward,
_voteWeight,
voterRewardMultiplier,
WEEKS_IN_YEAR.sub(i),
voterRewardSums[i],
remainingVoterReward,
block.timestamp
);
}
}
| 1,734,571 |
[
1,
10587,
331,
20005,
19890,
622,
813,
434,
598,
9446,
287,
225,
389,
90,
20005,
1021,
331,
20005,
358,
4604,
283,
6397,
364,
225,
389,
2972,
14638,
1021,
783,
7632,
358,
4604,
283,
6397,
364,
225,
389,
90,
20005,
14638,
1021,
7632,
326,
12501,
1703,
24000,
16219,
225,
389,
739,
416,
5326,
1021,
1300,
434,
25480,
326,
12501,
353,
8586,
731,
364,
225,
389,
25911,
6544,
1021,
12501,
3119,
364,
333,
12501,
261,
25911,
3844,
225,
2176,
416,
3734,
13,
327,
283,
6397,
30023,
1021,
2078,
283,
6397,
6541,
364,
777,
9368,
25480,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
389,
11162,
58,
20005,
17631,
1060,
12,
203,
3639,
1758,
389,
90,
20005,
16,
203,
3639,
2254,
2313,
389,
2972,
14638,
16,
203,
3639,
2254,
2313,
389,
90,
20005,
14638,
16,
203,
3639,
2254,
28,
389,
739,
416,
5326,
16,
203,
3639,
2254,
389,
25911,
6544,
203,
565,
262,
7010,
3639,
2713,
1850,
203,
3639,
1135,
12,
11890,
283,
6397,
30023,
13,
7010,
565,
288,
203,
3639,
2583,
24899,
90,
20005,
480,
1758,
12,
20,
3631,
315,
41,
11261,
30,
58,
1974,
654,
67,
15140,
67,
20,
8863,
203,
203,
3639,
2254,
19890,
14638,
87,
273,
389,
90,
20005,
14638,
18,
1289,
24899,
739,
416,
5326,
2934,
20668,
24899,
2972,
14638,
2934,
20668,
12,
20274,
55,
67,
706,
67,
15137,
1769,
203,
3639,
364,
261,
11890,
2313,
277,
273,
389,
90,
20005,
14638,
31,
277,
411,
19890,
14638,
87,
31,
277,
27245,
288,
203,
5411,
2254,
7632,
17631,
1060,
273,
331,
20005,
17631,
1060,
3495,
87,
63,
77,
65,
405,
374,
7010,
7734,
692,
2361,
18,
20668,
12,
203,
10792,
389,
25911,
6544,
18,
16411,
12,
90,
20005,
17631,
1060,
23365,
13,
203,
13491,
263,
16411,
12,
20274,
55,
67,
706,
67,
15137,
18,
1717,
12,
77,
3719,
203,
13491,
263,
2892,
12,
90,
20005,
17631,
1060,
3495,
87,
63,
77,
65,
3631,
203,
10792,
4463,
58,
20005,
17631,
1060,
203,
7734,
262,
203,
7734,
294,
374,
31,
203,
5411,
283,
6397,
30023,
273,
283,
6397,
30023,
18,
1289,
12,
12015,
17631,
1060,
1769,
203,
5411,
4463,
58,
20005,
17631,
1060,
273,
2
] |
{{
"language": "Solidity",
"settings": {
"remappings": [
"main=./src"
],
"optimizer": {
"enabled": true,
"runs": 200
},
"evmVersion": "istanbul",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"abi"
]
}
}
},
"sources": {
"./src/dependencies/DSAuth.sol": {
"content": "/// @notice Modified from DappHub (https://git.io/fpwrq)\n\npragma solidity 0.6.1;\n\nabstract contract DSAuthority {\n function canCall(\n address src, address dst, bytes4 sig\n ) public view virtual returns (bool);\n}\n\ncontract DSAuthEvents {\n event LogSetAuthority (address indexed authority);\n event LogSetOwner (address indexed owner);\n}\n\ncontract DSAuth is DSAuthEvents {\n DSAuthority public authority;\n address public owner;\n\n constructor() public {\n owner = msg.sender;\n emit LogSetOwner(msg.sender);\n }\n\n function setOwner(address owner_)\n public\n auth\n {\n owner = owner_;\n emit LogSetOwner(owner);\n }\n\n function setAuthority(DSAuthority authority_)\n public\n auth\n {\n authority = authority_;\n emit LogSetAuthority(address(authority));\n }\n\n modifier auth {\n require(isAuthorized(msg.sender, msg.sig), \"ds-auth-unauthorized\");\n _;\n }\n\n function isAuthorized(address src, bytes4 sig) internal view returns (bool) {\n if (src == address(this)) {\n return true;\n } else if (src == owner) {\n return true;\n } else if (authority == DSAuthority(0)) {\n return false;\n } else {\n return authority.canCall(src, address(this), sig);\n }\n }\n}\n"
},
"./src/dependencies/DSGuard.sol": {
"content": "/// @notice Retrieved from DappHub (https://git.io/fpwMi)\n\npragma solidity 0.6.1;\n\nimport \"./DSAuth.sol\";\n\ncontract DSGuardEvents {\n event LogPermit(\n bytes32 indexed src,\n bytes32 indexed dst,\n bytes32 indexed sig\n );\n\n event LogForbid(\n bytes32 indexed src,\n bytes32 indexed dst,\n bytes32 indexed sig\n );\n}\n\ncontract DSGuard is DSAuth, DSAuthority, DSGuardEvents {\n bytes32 constant public ANY = bytes32(uint(-1));\n\n mapping (bytes32 => mapping (bytes32 => mapping (bytes32 => bool))) acl;\n\n function canCall(\n address src_, address dst_, bytes4 sig\n ) public view override returns (bool) {\n bytes32 src = bytes32(bytes20(src_));\n bytes32 dst = bytes32(bytes20(dst_));\n\n return acl[src][dst][sig]\n || acl[src][dst][ANY]\n || acl[src][ANY][sig]\n || acl[src][ANY][ANY]\n || acl[ANY][dst][sig]\n || acl[ANY][dst][ANY]\n || acl[ANY][ANY][sig]\n || acl[ANY][ANY][ANY];\n }\n\n function permit(bytes32 src, bytes32 dst, bytes32 sig) public auth {\n acl[src][dst][sig] = true;\n emit LogPermit(src, dst, sig);\n }\n\n function forbid(bytes32 src, bytes32 dst, bytes32 sig) public auth {\n acl[src][dst][sig] = false;\n emit LogForbid(src, dst, sig);\n }\n\n function permit(address src, address dst, bytes32 sig) public {\n permit(bytes32(bytes20(src)), bytes32(bytes20(dst)), sig);\n }\n function forbid(address src, address dst, bytes32 sig) public {\n forbid(bytes32(bytes20(src)), bytes32(bytes20(dst)), sig);\n }\n\n}\n\ncontract DSGuardFactory {\n mapping (address => bool) public isGuard;\n\n function newGuard() public returns (DSGuard guard) {\n guard = new DSGuard();\n guard.setOwner(msg.sender);\n isGuard[address(guard)] = true;\n }\n}\n"
},
"./src/dependencies/DSMath.sol": {
"content": "/// DSMath.sol -- mixin for inline numerical wizardry\n\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU General Public License for more details.\n\n// You should have received a copy of the GNU General Public License\n// along with this program. If not, see <http://www.gnu.org/licenses/>.\n\npragma solidity >0.4.13;\n\ncontract DSMath {\n function add(uint x, uint y) internal pure returns (uint z) {\n require((z = x + y) >= x, \"ds-math-add-overflow\");\n }\n function sub(uint x, uint y) internal pure returns (uint z) {\n require((z = x - y) <= x, \"ds-math-sub-underflow\");\n }\n function mul(uint x, uint y) internal pure returns (uint z) {\n require(y == 0 || (z = x * y) / y == x, \"ds-math-mul-overflow\");\n }\n\n function min(uint x, uint y) internal pure returns (uint z) {\n return x <= y ? x : y;\n }\n function max(uint x, uint y) internal pure returns (uint z) {\n return x >= y ? x : y;\n }\n function imin(int x, int y) internal pure returns (int z) {\n return x <= y ? x : y;\n }\n function imax(int x, int y) internal pure returns (int z) {\n return x >= y ? x : y;\n }\n\n uint constant WAD = 10 ** 18;\n uint constant RAY = 10 ** 27;\n\n function wmul(uint x, uint y) internal pure returns (uint z) {\n z = add(mul(x, y), WAD / 2) / WAD;\n }\n function rmul(uint x, uint y) internal pure returns (uint z) {\n z = add(mul(x, y), RAY / 2) / RAY;\n }\n function wdiv(uint x, uint y) internal pure returns (uint z) {\n z = add(mul(x, WAD), y / 2) / y;\n }\n function rdiv(uint x, uint y) internal pure returns (uint z) {\n z = add(mul(x, RAY), y / 2) / y;\n }\n\n // This famous algorithm is called \"exponentiation by squaring\"\n // and calculates x^n with x as fixed-point and n as regular unsigned.\n //\n // It's O(log n), instead of O(n) for naive repeated multiplication.\n //\n // These facts are why it works:\n //\n // If n is even, then x^n = (x^2)^(n/2).\n // If n is odd, then x^n = x * x^(n-1),\n // and applying the equation for even x gives\n // x^n = x * (x^2)^((n-1) / 2).\n //\n // Also, EVM division is flooring and\n // floor[(n-1) / 2] = floor[n / 2].\n //\n function rpow(uint x, uint n) internal pure returns (uint z) {\n z = n % 2 != 0 ? x : RAY;\n\n for (n /= 2; n != 0; n /= 2) {\n x = rmul(x, x);\n\n if (n % 2 != 0) {\n z = rmul(z, x);\n }\n }\n }\n}\n"
},
"./src/dependencies/SafeMath.sol": {
"content": "pragma solidity 0.6.1;\n\n\n/**\n * @title SafeMath\n * @dev Math operations with safety checks that revert on error\n */\nlibrary SafeMath {\n\n /**\n * @dev Multiplies two numbers, reverts on overflow.\n */\n function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522\n if (_a == 0) {\n return 0;\n }\n\n uint256 c = _a * _b;\n require(c / _a == _b);\n\n return c;\n }\n\n /**\n * @dev Integer division of two numbers truncating the quotient, reverts on division by zero.\n */\n function div(uint256 _a, uint256 _b) internal pure returns (uint256) {\n require(_b > 0); // Solidity only automatically asserts when dividing by 0\n uint256 c = _a / _b;\n // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).\n */\n function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {\n require(_b <= _a);\n uint256 c = _a - _b;\n\n return c;\n }\n\n /**\n * @dev Adds two numbers, reverts on overflow.\n */\n function add(uint256 _a, uint256 _b) internal pure returns (uint256) {\n uint256 c = _a + _b;\n require(c >= _a);\n\n return c;\n }\n\n /**\n * @dev Divides two numbers and returns the remainder (unsigned integer modulo),\n * reverts when dividing by zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n require(b != 0);\n return a % b;\n }\n}\n"
},
"./src/dependencies/token/BurnableToken.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"./PreminedToken.sol\";\n\n/// @dev Just a wrapper for premined tokens which can actually be burnt\ncontract BurnableToken is PreminedToken {\n constructor(string memory _symbol, uint8 _decimals, string memory _name)\n public\n PreminedToken(_symbol, _decimals, _name)\n {}\n\n function burn(uint _amount) public {\n _burn(msg.sender, _amount);\n }\n\n function burnFrom(address from, uint256 value) public {\n _burnFrom(from, value);\n }\n}\n\n"
},
"./src/dependencies/token/IERC20.sol": {
"content": "pragma solidity 0.6.1;\n\n/**\n * @title ERC20 interface\n * @dev see https://github.com/ethereum/EIPs/issues/20\n * Altered from https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a466e76d26c394b1faa6e2797aefe34668566392/contracts/token/ERC20/ERC20.sol\n */\ninterface IERC20 {\n function totalSupply() external view returns (uint256);\n\n function balanceOf(address _who) external view returns (uint256);\n\n function allowance(address _owner, address _spender)\n external view returns (uint256);\n\n function transfer(address _to, uint256 _value) external returns (bool);\n\n function approve(address _spender, uint256 _value) external returns (bool);\n\n function transferFrom(address _from, address _to, uint256 _value) external returns (bool);\n\n event Transfer(\n address indexed from,\n address indexed to,\n uint256 value\n );\n\n event Approval(\n address indexed owner,\n address indexed spender,\n uint256 value\n );\n}\n\n/// @dev Just adds extra functions that we use elsewhere\nabstract contract ERC20WithFields is IERC20 {\n string public symbol;\n string public name;\n uint8 public decimals;\n}\n"
},
"./src/dependencies/token/PreminedToken.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"./StandardToken.sol\";\n\ncontract PreminedToken is StandardToken {\n string public symbol;\n string public name;\n uint8 public decimals;\n\n constructor(string memory _symbol, uint8 _decimals, string memory _name) public {\n symbol = _symbol;\n decimals = _decimals;\n name = _name;\n totalSupply_ = 1000000 * 10**uint(decimals);\n balances[msg.sender] = totalSupply_;\n emit Transfer(address(0), msg.sender, totalSupply_);\n }\n}\n\n"
},
"./src/dependencies/token/StandardToken.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"./IERC20.sol\";\nimport \"../SafeMath.sol\";\n\n/**\n * @title Standard ERC20 token\n *\n * @dev Implementation of the basic standard token.\n * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md\n * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol\n * Modified from https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a466e76d26c394b1faa6e2797aefe34668566392/contracts/token/ERC20/StandardToken.sol\n */\ncontract StandardToken is IERC20 {\n using SafeMath for uint256;\n\n mapping (address => uint256) balances;\n\n mapping (address => mapping (address => uint256)) allowed;\n\n uint256 totalSupply_;\n\n /**\n * @dev Total number of tokens in existence\n */\n function totalSupply() public view override returns (uint256) {\n return totalSupply_;\n }\n\n /**\n * @dev Gets the balance of the specified address.\n * @param _owner The address to query the the balance of.\n * @return An uint256 representing the amount owned by the passed address.\n */\n function balanceOf(address _owner) public view override returns (uint256) {\n return balances[_owner];\n }\n\n /**\n * @dev Function to check the amount of tokens that an owner allowed to a spender.\n * @param _owner address The address which owns the funds.\n * @param _spender address The address which will spend the funds.\n * @return A uint256 specifying the amount of tokens still available for the spender.\n */\n function allowance(\n address _owner,\n address _spender\n )\n public\n view\n override\n returns (uint256)\n {\n return allowed[_owner][_spender];\n }\n\n /**\n * @dev Transfer token for a specified address\n * @param _to The address to transfer to.\n * @param _value The amount to be transferred.\n */\n function transfer(address _to, uint256 _value) public virtual override returns (bool) {\n require(_value <= balances[msg.sender]);\n require(_to != address(0));\n\n balances[msg.sender] = balances[msg.sender].sub(_value);\n balances[_to] = balances[_to].add(_value);\n emit Transfer(msg.sender, _to, _value);\n return true;\n }\n\n /**\n * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.\n * Beware that changing an allowance with this method brings the risk that someone may use both the old\n * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this\n * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n * @param _spender The address which will spend the funds.\n * @param _value The amount of tokens to be spent.\n */\n function approve(address _spender, uint256 _value) public virtual override returns (bool) {\n allowed[msg.sender][_spender] = _value;\n emit Approval(msg.sender, _spender, _value);\n return true;\n }\n\n /**\n * @dev Transfer tokens from one address to another\n * @param _from address The address which you want to send tokens from\n * @param _to address The address which you want to transfer to\n * @param _value uint256 the amount of tokens to be transferred\n */\n function transferFrom(\n address _from,\n address _to,\n uint256 _value\n )\n public\n virtual\n override\n returns (bool)\n {\n require(_value <= balances[_from]);\n require(_value <= allowed[_from][msg.sender]);\n require(_to != address(0));\n\n balances[_from] = balances[_from].sub(_value);\n balances[_to] = balances[_to].add(_value);\n allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);\n emit Approval(_from, msg.sender, allowed[_from][msg.sender]);\n emit Transfer(_from, _to, _value);\n return true;\n }\n\n /**\n * @dev Increase the amount of tokens that an owner allowed to a spender.\n * approve should be called when allowed[_spender] == 0. To increment\n * allowed value is better to use this function to avoid 2 calls (and wait until\n * the first transaction is mined)\n * From MonolithDAO Token.sol\n * @param _spender The address which will spend the funds.\n * @param _addedValue The amount of tokens to increase the allowance by.\n */\n function increaseApproval(\n address _spender,\n uint256 _addedValue\n )\n public\n virtual\n returns (bool)\n {\n allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));\n emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);\n return true;\n }\n\n /**\n * @dev Decrease the amount of tokens that an owner allowed to a spender.\n * approve should be called when allowed[_spender] == 0. To decrement\n * allowed value is better to use this function to avoid 2 calls (and wait until\n * the first transaction is mined)\n * From MonolithDAO Token.sol\n * @param _spender The address which will spend the funds.\n * @param _subtractedValue The amount of tokens to decrease the allowance by.\n */\n function decreaseApproval(\n address _spender,\n uint256 _subtractedValue\n )\n public\n virtual\n returns (bool)\n {\n uint256 oldValue = allowed[msg.sender][_spender];\n if (_subtractedValue >= oldValue) {\n allowed[msg.sender][_spender] = 0;\n } else {\n allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);\n }\n emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);\n return true;\n }\n\n /**\n * @dev Internal function that mints an amount of the token and assigns it to\n * an account. This encapsulates the modification of balances such that the\n * proper events are emitted.\n * @param _account The account that will receive the created tokens.\n * @param _amount The amount that will be created.\n */\n function _mint(address _account, uint256 _amount) internal {\n require(_account != address(0));\n totalSupply_ = totalSupply_.add(_amount);\n balances[_account] = balances[_account].add(_amount);\n emit Transfer(address(0), _account, _amount);\n }\n\n /**\n * @dev Internal function that burns an amount of the token of a given\n * account.\n * @param _account The account whose tokens will be burnt.\n * @param _amount The amount that will be burnt.\n */\n function _burn(address _account, uint256 _amount) internal {\n require(_account != address(0));\n require(_amount <= balances[_account]);\n\n totalSupply_ = totalSupply_.sub(_amount);\n balances[_account] = balances[_account].sub(_amount);\n emit Transfer(_account, address(0), _amount);\n }\n\n /**\n * @dev Internal function that burns an amount of the token of a given\n * account, deducting from the sender's allowance for said account. Uses the\n * internal _burn function.\n * @param _account The account whose tokens will be burnt.\n * @param _amount The amount that will be burnt.\n */\n function _burnFrom(address _account, uint256 _amount) internal {\n require(_amount <= allowed[_account][msg.sender]);\n allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount);\n emit Approval(_account, msg.sender, allowed[_account][msg.sender]);\n _burn(_account, _amount);\n }\n}\n"
},
"./src/dependencies/TokenUser.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"./token/IERC20.sol\";\nimport \"./DSMath.sol\";\n\n/// @notice Wrapper to ensure tokens are received\ncontract TokenUser is DSMath {\n function safeTransfer(\n address _token,\n address _to,\n uint _value\n ) internal {\n uint receiverPreBalance = IERC20(_token).balanceOf(_to);\n IERC20(_token).transfer(_to, _value);\n uint receiverPostBalance = IERC20(_token).balanceOf(_to);\n require(\n add(receiverPreBalance, _value) == receiverPostBalance,\n \"Receiver did not receive tokens in transfer\"\n );\n }\n\n function safeTransferFrom(\n address _token,\n address _from,\n address _to,\n uint _value\n ) internal {\n uint receiverPreBalance = IERC20(_token).balanceOf(_to);\n IERC20(_token).transferFrom(_from, _to, _value);\n uint receiverPostBalance = IERC20(_token).balanceOf(_to);\n require(\n add(receiverPreBalance, _value) == receiverPostBalance,\n \"Receiver did not receive tokens in transferFrom\"\n );\n }\n}\n"
},
"./src/dependencies/WETH.sol": {
"content": "pragma solidity 0.6.1;\n\ncontract WETH {\n string public name = \"Wrapped Ether\";\n string public symbol = \"WETH\";\n uint8 public decimals = 18;\n\n event Approval(address indexed src, address indexed guy, uint wad);\n event Transfer(address indexed src, address indexed dst, uint wad);\n event Deposit(address indexed dst, uint wad);\n event Withdrawal(address indexed src, uint wad);\n\n mapping (address => uint) public balanceOf;\n mapping (address => mapping (address => uint)) public allowance;\n\n receive() external payable {\n deposit();\n }\n function deposit() public payable {\n balanceOf[msg.sender] += msg.value;\n emit Deposit(msg.sender, msg.value);\n }\n function withdraw(uint wad) public {\n require(balanceOf[msg.sender] >= wad);\n balanceOf[msg.sender] -= wad;\n msg.sender.transfer(wad);\n emit Withdrawal(msg.sender, wad);\n }\n\n function totalSupply() public view returns (uint) {\n return address(this).balance;\n }\n\n function approve(address guy, uint wad) public returns (bool) {\n allowance[msg.sender][guy] = wad;\n emit Approval(msg.sender, guy, wad);\n return true;\n }\n\n function transfer(address dst, uint wad) public returns (bool) {\n return transferFrom(msg.sender, dst, wad);\n }\n\n function transferFrom(address src, address dst, uint wad)\n public\n returns (bool)\n {\n require(balanceOf[src] >= wad);\n\n if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {\n require(allowance[src][msg.sender] >= wad);\n allowance[src][msg.sender] -= wad;\n }\n\n balanceOf[src] -= wad;\n balanceOf[dst] += wad;\n\n emit Transfer(src, dst, wad);\n\n return true;\n }\n}\n\n"
},
"./src/engine/AmguConsumer.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../dependencies/DSMath.sol\";\nimport \"../dependencies/token/IERC20.sol\";\nimport \"../prices/IPriceSource.sol\";\nimport \"../version/IVersion.sol\";\nimport \"./IEngine.sol\";\nimport \"../version/Registry.sol\";\n\n/// @notice Abstract contracts\n/// @notice inherit this to pay AMGU on a function call\nabstract contract AmguConsumer is DSMath {\n\n /// @dev each of these must be implemented by the inheriting contract\n function engine() public view virtual returns (address);\n function mlnToken() public view virtual returns (address);\n function priceSource() public view virtual returns (address);\n function registry() public view virtual returns (address);\n event AmguPaid(address indexed payer, uint256 totalAmguPaidInEth, uint256 amguChargableGas, uint256 incentivePaid);\n\n /// bool deductIncentive is used when sending extra eth beyond amgu\n modifier amguPayable(bool deductIncentive) {\n uint preGas = gasleft();\n _;\n uint postGas = gasleft();\n\n uint mlnPerAmgu = IEngine(engine()).getAmguPrice();\n uint mlnQuantity = mul(\n mlnPerAmgu,\n sub(preGas, postGas)\n );\n address nativeAsset = Registry(registry()).nativeAsset();\n uint ethToPay = IPriceSource(priceSource()).convertQuantity(\n mlnQuantity,\n mlnToken(),\n nativeAsset\n );\n uint incentiveAmount;\n if (deductIncentive) {\n incentiveAmount = Registry(registry()).incentive();\n } else {\n incentiveAmount = 0;\n }\n require(\n msg.value >= add(ethToPay, incentiveAmount),\n \"Insufficent AMGU and/or incentive\"\n );\n IEngine(engine()).payAmguInEther.value(ethToPay)();\n\n require(\n msg.sender.send(\n sub(\n sub(msg.value, ethToPay),\n incentiveAmount\n )\n ),\n \"Refund failed\"\n );\n emit AmguPaid(msg.sender, ethToPay, sub(preGas, postGas), incentiveAmount);\n }\n}\n"
},
"./src/engine/Engine.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../dependencies/DSMath.sol\";\nimport \"../dependencies/token/BurnableToken.sol\";\nimport \"../prices/IPriceSource.sol\";\nimport \"../version/Registry.sol\";\n\n/// @notice Liquidity contract and token sink\ncontract Engine is DSMath {\n\n event RegistryChange(address registry);\n event SetAmguPrice(uint amguPrice);\n event AmguPaid(uint amount);\n event Thaw(uint amount);\n event Burn(uint amount);\n\n uint public constant MLN_DECIMALS = 18;\n\n Registry public registry;\n uint public amguPrice;\n uint public frozenEther;\n uint public liquidEther;\n uint public lastThaw;\n uint public thawingDelay;\n uint public totalEtherConsumed;\n uint public totalAmguConsumed;\n uint public totalMlnBurned;\n\n constructor(uint _delay, address _registry) public {\n lastThaw = block.timestamp;\n thawingDelay = _delay;\n _setRegistry(_registry);\n }\n\n modifier onlyMGM() {\n require(\n msg.sender == registry.MGM(),\n \"Only MGM can call this\"\n );\n _;\n }\n\n /// @dev Registry owner is MTC\n modifier onlyMTC() {\n require(\n msg.sender == registry.owner(),\n \"Only MTC can call this\"\n );\n _;\n }\n\n function _setRegistry(address _registry) internal {\n registry = Registry(_registry);\n emit RegistryChange(address(registry));\n }\n\n /// @dev only callable by MTC\n function setRegistry(address _registry)\n external\n onlyMTC\n {\n _setRegistry(_registry);\n }\n\n /// @dev set price of AMGU in MLN (base units)\n /// @dev only callable by MGM\n function setAmguPrice(uint _price)\n external\n onlyMGM\n {\n amguPrice = _price;\n emit SetAmguPrice(_price);\n }\n\n function getAmguPrice() public view returns (uint) { return amguPrice; }\n\n function premiumPercent() public view returns (uint) {\n if (liquidEther < 1 ether) {\n return 0;\n } else if (liquidEther >= 1 ether && liquidEther < 5 ether) {\n return 5;\n } else if (liquidEther >= 5 ether && liquidEther < 10 ether) {\n return 10;\n } else if (liquidEther >= 10 ether) {\n return 15;\n }\n }\n\n function payAmguInEther() external payable {\n require(\n registry.isFundFactory(msg.sender) ||\n registry.isFund(msg.sender),\n \"Sender must be a fund or the factory\"\n );\n uint mlnPerAmgu = getAmguPrice();\n uint ethPerMln;\n (ethPerMln,) = priceSource().getPrice(address(mlnToken()));\n uint amguConsumed;\n if (mlnPerAmgu > 0 && ethPerMln > 0) {\n amguConsumed = (mul(msg.value, 10 ** uint(MLN_DECIMALS))) / (mul(ethPerMln, mlnPerAmgu));\n } else {\n amguConsumed = 0;\n }\n totalEtherConsumed = add(totalEtherConsumed, msg.value);\n totalAmguConsumed = add(totalAmguConsumed, amguConsumed);\n frozenEther = add(frozenEther, msg.value);\n emit AmguPaid(amguConsumed);\n }\n\n /// @notice Move frozen ether to liquid pool after delay\n /// @dev Delay only restarts when this function is called\n function thaw() external {\n require(\n block.timestamp >= add(lastThaw, thawingDelay),\n \"Thawing delay has not passed\"\n );\n require(frozenEther > 0, \"No frozen ether to thaw\");\n lastThaw = block.timestamp;\n liquidEther = add(liquidEther, frozenEther);\n emit Thaw(frozenEther);\n frozenEther = 0;\n }\n\n /// @return ETH per MLN including premium\n function enginePrice() public view returns (uint) {\n uint ethPerMln;\n (ethPerMln, ) = priceSource().getPrice(address(mlnToken()));\n uint premium = (mul(ethPerMln, premiumPercent()) / 100);\n return add(ethPerMln, premium);\n }\n\n function ethPayoutForMlnAmount(uint mlnAmount) public view returns (uint) {\n return mul(mlnAmount, enginePrice()) / 10 ** uint(MLN_DECIMALS);\n }\n\n /// @notice MLN must be approved first\n function sellAndBurnMln(uint mlnAmount) external {\n require(registry.isFund(msg.sender), \"Only funds can use the engine\");\n require(\n mlnToken().transferFrom(msg.sender, address(this), mlnAmount),\n \"MLN transferFrom failed\"\n );\n uint ethToSend = ethPayoutForMlnAmount(mlnAmount);\n require(ethToSend > 0, \"No ether to pay out\");\n require(liquidEther >= ethToSend, \"Not enough liquid ether to send\");\n liquidEther = sub(liquidEther, ethToSend);\n totalMlnBurned = add(totalMlnBurned, mlnAmount);\n msg.sender.transfer(ethToSend);\n mlnToken().burn(mlnAmount);\n emit Burn(mlnAmount);\n }\n\n /// @dev Get MLN from the registry\n function mlnToken()\n public\n view\n returns (BurnableToken)\n {\n return BurnableToken(registry.mlnToken());\n }\n\n /// @dev Get PriceSource from the registry\n function priceSource()\n public\n view\n returns (IPriceSource)\n {\n return IPriceSource(registry.priceSource());\n }\n}\n\n"
},
"./src/engine/IEngine.sol": {
"content": "pragma solidity 0.6.1;\n\n\ninterface IEngine {\n function payAmguInEther() external payable;\n function getAmguPrice() external view returns (uint256);\n}\n"
},
"./src/exchanges/EngineAdapter.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../engine/Engine.sol\";\nimport \"../fund/hub/Hub.sol\";\nimport \"../fund/trading/Trading.sol\";\nimport \"../fund/vault/Vault.sol\";\nimport \"../dependencies/DSMath.sol\";\nimport \"../dependencies/WETH.sol\";\nimport \"../dependencies/token/IERC20.sol\";\nimport \"./ExchangeAdapter.sol\";\nimport \"../dependencies/TokenUser.sol\";\n\n/// @notice Trading adapter to Melon Engine\ncontract EngineAdapter is DSMath, TokenUser, ExchangeAdapter {\n\n /// @notice Buys Ether from the engine, selling MLN\n /// @param targetExchange Address of the engine\n /// @param orderValues [0] Min Eth to receive from the engine\n /// @param orderValues [1] MLN quantity\n /// @param orderValues [6] Same as orderValues[1]\n /// @param orderAddresses [2] WETH token\n /// @param orderAddresses [3] MLN token\n function takeOrder (\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public override onlyManager notShutDown {\n Hub hub = getHub();\n\n address wethAddress = orderAddresses[2];\n address mlnAddress = orderAddresses[3];\n uint minEthToReceive = orderValues[0];\n uint mlnQuantity = orderValues[1];\n\n require(\n wethAddress == Registry(hub.registry()).nativeAsset(),\n \"maker asset doesnt match nativeAsset on registry\"\n );\n require(\n orderValues[1] == orderValues[6],\n \"fillTakerQuantity must equal takerAssetQuantity\"\n );\n\n withdrawAndApproveAsset(mlnAddress, targetExchange, mlnQuantity, \"takerAsset\");\n\n uint ethToReceive = Engine(targetExchange).ethPayoutForMlnAmount(mlnQuantity);\n\n require(\n ethToReceive >= minEthToReceive,\n \"Expected ETH to receive is less than takerQuantity (minEthToReceive)\"\n );\n\n Engine(targetExchange).sellAndBurnMln(mlnQuantity);\n WETH(payable(wethAddress)).deposit.value(ethToReceive)();\n safeTransfer(wethAddress, address(Vault(hub.vault())), ethToReceive);\n\n getAccounting().addAssetToOwnedAssets(wethAddress);\n getAccounting().updateOwnedAssets();\n getTrading().orderUpdateHook(\n targetExchange,\n bytes32(0),\n Trading.UpdateType.take,\n [payable(wethAddress), payable(mlnAddress)],\n [ethToReceive, mlnQuantity, mlnQuantity]\n );\n }\n}\n"
},
"./src/exchanges/EthfinexAdapter.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../dependencies/token/IERC20.sol\";\nimport \"../fund/trading/Trading.sol\";\nimport \"../fund/hub/Hub.sol\";\nimport \"../fund/vault/Vault.sol\";\nimport \"../fund/accounting/Accounting.sol\";\nimport \"../version/Registry.sol\";\nimport \"../dependencies/WETH.sol\";\nimport \"../dependencies/DSMath.sol\";\nimport \"./interfaces/IZeroExV2.sol\";\nimport \"./interfaces/IEthfinex.sol\";\nimport \"./ExchangeAdapter.sol\";\n\n/// @title EthfinexAdapter Contract\n/// @author Melonport AG <[email protected]>\n/// @notice Adapter to EthFinex exchange\ncontract EthfinexAdapter is DSMath, ExchangeAdapter {\n /// @param _orderAddresses [2] Order maker asset\n /// @param _orderAddresses [3] Order taker asset\n /// @param _orderData [0] Encoded data specific to maker asset\n /// @param _orderData [1] Encoded data specific to taker asset\n modifier orderAddressesMatchOrderData(\n address[8] memory _orderAddresses,\n bytes[4] memory _orderData\n )\n {\n require(\n getAssetAddress(_orderData[0]) == getWrapperToken(_orderAddresses[2]),\n \"Maker asset data does not match order address in array\"\n );\n require(\n getAssetAddress(_orderData[1]) == _orderAddresses[3],\n \"Taker asset data does not match order address in array\"\n );\n _;\n }\n\n // METHODS\n\n // PUBLIC METHODS\n\n /// @notice Make order by pre-approving signatures\n function makeOrder(\n address _targetExchange,\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData,\n bytes32 _identifier,\n bytes memory _signature\n )\n public\n override\n onlyManager\n notShutDown\n orderAddressesMatchOrderData(_orderAddresses, _orderData)\n {\n ensureCanMakeOrder(_orderAddresses[2]);\n\n IZeroExV2.Order memory order = constructOrderStruct(_orderAddresses, _orderValues, _orderData);\n bytes memory wrappedMakerAssetData = _orderData[0];\n bytes memory takerAssetData = _orderData[1];\n address makerAsset = _orderAddresses[2];\n address takerAsset = getAssetAddress(takerAssetData);\n\n // Order parameter checks\n getTrading().updateAndGetQuantityBeingTraded(makerAsset);\n ensureNotInOpenMakeOrder(makerAsset);\n\n wrapMakerAsset(_targetExchange, makerAsset, wrappedMakerAssetData, order.makerAssetAmount, order.expirationTimeSeconds);\n\n IZeroExV2.OrderInfo memory orderInfo = IZeroExV2(_targetExchange).getOrderInfo(order);\n IZeroExV2(_targetExchange).preSign(orderInfo.orderHash, address(this), _signature);\n\n require(\n IZeroExV2(_targetExchange).isValidSignature(\n orderInfo.orderHash,\n address(this),\n _signature\n ),\n \"INVALID_ORDER_SIGNATURE\"\n );\n\n updateStateMakeOrder(_targetExchange, order);\n }\n\n /// @notice Cancel the 0x make order\n function cancelOrder(\n address _targetExchange,\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData,\n bytes32 _identifier,\n bytes memory _signature\n )\n public\n override\n orderAddressesMatchOrderData(_orderAddresses, _orderData)\n {\n IZeroExV2.Order memory order = getTrading().getZeroExV2OrderDetails(_identifier);\n ensureCancelPermitted(_targetExchange, getAssetAddress(order.makerAssetData));\n IZeroExV2(_targetExchange).cancelOrder(order);\n\n updateStateCancelOrder(_targetExchange, order);\n }\n\n /// @notice Unwrap (withdraw) tokens, uses _orderAddresses for input list of tokens to be unwrapped\n /// @dev Call to \"withdraw\" fails if timestamp < `Wrapper.depositLock(tradingComponent)`\n function withdrawTokens(\n address _targetExchange,\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData,\n bytes32 _identifier,\n bytes memory _signature\n )\n public\n {\n Hub hub = getHub();\n address nativeAsset = Accounting(hub.accounting()).NATIVE_ASSET();\n\n for (uint i = 0; i < _orderAddresses.length; i++) {\n if (_orderAddresses[i] == address(0)) continue;\n address wrappedToken = getWrapperToken(_orderAddresses[i]);\n uint balance = IWrapperLock(wrappedToken).balanceOf(address(this));\n require(balance > 0, \"Insufficient balance\");\n IWrapperLock(wrappedToken).withdraw(balance, 0, bytes32(0), bytes32(0), 0);\n if (_orderAddresses[i] == nativeAsset) {\n WETH(payable(nativeAsset)).deposit.value(balance)();\n }\n getTrading().removeOpenMakeOrder(_targetExchange, _orderAddresses[i]);\n getTrading().returnAssetToVault(_orderAddresses[i]);\n }\n }\n\n /// @notice Minor: Wrapped tokens directly sent to the fund are not accounted. To be called by Trading spoke\n function getOrder(address _targetExchange, uint256 _id, address _makerAsset)\n public\n view\n override\n returns (address, address, uint256, uint256)\n {\n uint orderId;\n uint orderIndex;\n address takerAsset;\n uint makerQuantity;\n uint takerQuantity;\n (orderId, , orderIndex) = Trading(msg.sender).getOpenOrderInfo(_targetExchange, _makerAsset);\n (, takerAsset, makerQuantity, takerQuantity) = Trading(msg.sender).getOrderDetails(orderIndex);\n\n // Check if order has been completely filled\n uint takerAssetFilledAmount = IZeroExV2(_targetExchange).filled(bytes32(orderId));\n if (sub(takerQuantity, takerAssetFilledAmount) == 0) {\n return (_makerAsset, takerAsset, 0, 0);\n }\n\n // Check if tokens have been withdrawn (cancelled order may still need to be accounted if there is balance)\n uint balance = IWrapperLock(getWrapperTokenFromAdapterContext(_makerAsset)).balanceOf(msg.sender);\n if (balance == 0) {\n return (_makerAsset, takerAsset, 0, 0);\n }\n return (_makerAsset, takerAsset, makerQuantity, sub(takerQuantity, takerAssetFilledAmount));\n }\n\n // INTERNAL METHODS\n\n /// @notice needed to avoid stack too deep error\n /// @dev deposit time should be greater than 1 hour\n function wrapMakerAsset(\n address _targetExchange,\n address _makerAsset,\n bytes memory _wrappedMakerAssetData,\n uint _makerQuantity,\n uint _orderExpirationTime\n )\n internal\n {\n Hub hub = getHub();\n\n // Deposit to rounded up value of time difference of expiration time and current time (in hours)\n uint depositTime = (\n sub(_orderExpirationTime, block.timestamp) / 1 hours\n ) + 1;\n\n address nativeAsset = Accounting(hub.accounting()).NATIVE_ASSET();\n address wrappedToken = getWrapperToken(_makerAsset);\n // Handle case for WETH vs ERC20\n if (_makerAsset == nativeAsset) {\n Vault vault = Vault(hub.vault());\n vault.withdraw(_makerAsset, _makerQuantity);\n WETH(payable(nativeAsset)).withdraw(_makerQuantity);\n IWrapperLockEth(wrappedToken).deposit.value(_makerQuantity)(_makerQuantity, depositTime);\n } else {\n withdrawAndApproveAsset(\n _makerAsset,\n wrappedToken,\n _makerQuantity,\n \"makerAsset\"\n );\n IWrapperLock(wrappedToken).deposit(_makerQuantity, depositTime);\n }\n }\n\n // @dev avoids stack too deep error\n function updateStateCancelOrder(address _targetExchange, IZeroExV2.Order memory _order)\n internal\n {\n // Order is not removed from OpenMakeOrder mapping as it's needed for accounting (wrapped tokens)\n getAccounting().updateOwnedAssets();\n getTrading().orderUpdateHook(\n _targetExchange,\n IZeroExV2(_targetExchange).getOrderInfo(_order).orderHash,\n Trading.UpdateType.cancel,\n [address(0), address(0)],\n [uint(0), uint(0), uint(0)]\n );\n }\n\n // @dev avoids stack too deep error\n function updateStateMakeOrder(address _targetExchange, IZeroExV2.Order memory _order)\n internal\n {\n address wrapperRegistry = Registry(getTrading().registry()).ethfinexWrapperRegistry();\n address wrappedMakerAsset = getAssetAddress(_order.makerAssetData);\n address makerAsset = IWrapperRegistryEFX(\n wrapperRegistry\n ).wrapper2TokenLookup(wrappedMakerAsset);\n address takerAsset = getAssetAddress(_order.takerAssetData);\n IZeroExV2.OrderInfo memory orderInfo = IZeroExV2(_targetExchange).getOrderInfo(_order);\n\n getAccounting().addAssetToOwnedAssets(takerAsset);\n getTrading().orderUpdateHook(\n _targetExchange,\n orderInfo.orderHash,\n Trading.UpdateType.make,\n [payable(makerAsset), payable(takerAsset)],\n [_order.makerAssetAmount, _order.takerAssetAmount, uint(0)]\n );\n getTrading().addOpenMakeOrder(\n _targetExchange,\n makerAsset,\n takerAsset,\n uint256(orderInfo.orderHash),\n _order.expirationTimeSeconds\n );\n getTrading().addZeroExV2OrderData(orderInfo.orderHash, _order);\n }\n\n // VIEW METHODS\n\n function constructOrderStruct(\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData\n )\n internal\n view\n returns (IZeroExV2.Order memory _order)\n {\n _order = IZeroExV2.Order({\n makerAddress: _orderAddresses[0],\n takerAddress: _orderAddresses[1],\n feeRecipientAddress: _orderAddresses[4],\n senderAddress: _orderAddresses[5],\n makerAssetAmount: _orderValues[0],\n takerAssetAmount: _orderValues[1],\n makerFee: _orderValues[2],\n takerFee: _orderValues[3],\n expirationTimeSeconds: _orderValues[4],\n salt: _orderValues[5],\n makerAssetData: _orderData[0],\n takerAssetData: _orderData[1]\n });\n }\n\n function getAssetProxy(address _targetExchange, bytes memory _assetData)\n internal\n view\n returns (address assetProxy_)\n {\n bytes4 assetProxyId;\n assembly {\n assetProxyId := and(mload(\n add(_assetData, 32)),\n 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000\n )\n }\n assetProxy_ = IZeroExV2(_targetExchange).getAssetProxy(assetProxyId);\n }\n\n function getAssetAddress(bytes memory _assetData)\n internal\n view\n returns (address assetAddress_)\n {\n assembly {\n assetAddress_ := mload(add(_assetData, 36))\n }\n }\n\n /// @dev Function to be called from Trading spoke context (Delegate call)\n function getWrapperToken(address _token)\n internal\n view\n returns (address)\n {\n address wrapperRegistry = Registry(getTrading().registry()).ethfinexWrapperRegistry();\n return IWrapperRegistryEFX(wrapperRegistry).token2WrapperLookup(_token);\n }\n\n /// @dev Function to be called by Trading spoke without change of context (Non delegate call)\n function getWrapperTokenFromAdapterContext(address _token)\n internal\n view\n returns (address)\n {\n address wrapperRegistry = Registry(Trading(msg.sender).registry()).ethfinexWrapperRegistry();\n return IWrapperRegistryEFX(wrapperRegistry).token2WrapperLookup(_token);\n }\n}\n"
},
"./src/exchanges/ExchangeAdapter.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../dependencies/DSMath.sol\";\nimport \"../dependencies/token/IERC20.sol\";\nimport \"../fund/accounting/Accounting.sol\";\nimport \"../fund/hub/Hub.sol\";\nimport \"../fund/trading/Trading.sol\";\nimport \"../fund/vault/Vault.sol\";\n\n/// @title Exchange Adapter base contract\n/// @author Melonport AG <[email protected]>\n/// @notice Override the public methods to implement an adapter\ncontract ExchangeAdapter is DSMath {\n\n modifier onlyManager() {\n require(\n getManager() == msg.sender,\n \"Manager must be sender\"\n );\n _;\n }\n\n modifier notShutDown() {\n require(\n !hubShutDown(),\n \"Hub must not be shut down\"\n );\n _;\n }\n\n /// @dev Either manager sends, fund shut down, or order expired\n function ensureCancelPermitted(address exchange, address asset) internal {\n require(\n getManager() == msg.sender ||\n hubShutDown() ||\n getTrading().isOrderExpired(exchange, asset),\n \"No cancellation condition met\"\n );\n }\n\n function getTrading() internal view returns (Trading) {\n return Trading(payable(address(this)));\n }\n\n function getHub() internal view returns (Hub) {\n return Hub(getTrading().hub());\n }\n\n function getAccounting() internal view returns (Accounting) {\n return Accounting(getHub().accounting());\n }\n\n function hubShutDown() internal view returns (bool) {\n return getHub().isShutDown();\n }\n\n function getManager() internal view returns (address) {\n return getHub().manager();\n }\n\n function ensureNotInOpenMakeOrder(address _asset) internal view {\n require(\n !getTrading().isInOpenMakeOrder(_asset),\n \"This asset is already in an open make order\"\n );\n }\n\n function ensureCanMakeOrder(address _asset) internal view {\n require(\n block.timestamp >= getTrading().makerAssetCooldown(_asset),\n \"Cooldown for the maker asset not reached\"\n );\n }\n\n /// @notice Increment allowance of an asset for some target\n function withdrawAndApproveAsset(\n address _asset,\n address _target,\n uint256 _amount,\n string memory _assetType\n )\n internal\n {\n Hub hub = getHub();\n Vault vault = Vault(hub.vault());\n\n require(\n IERC20(_asset).balanceOf(address(vault)) >= _amount,\n string(abi.encodePacked(\"Insufficient balance: \", _assetType))\n );\n\n vault.withdraw(_asset, _amount);\n uint256 allowance = IERC20(_asset).allowance(address(this), _target);\n require(\n IERC20(_asset).approve(_target, add(allowance, _amount)),\n string(abi.encodePacked(\"Approval failed: \", _assetType))\n );\n }\n\n /// @notice Reduce allowance of an asset for some target\n function revokeApproveAsset(\n address _asset,\n address _target,\n uint256 _amount,\n string memory _assetType\n )\n internal\n {\n uint256 allowance = IERC20(_asset).allowance(address(this), _target);\n require(\n IERC20(_asset).approve(_target, sub(allowance, _amount)),\n string(abi.encodePacked(\"Revoke approval failed: \", _assetType))\n );\n }\n\n /// @param orderAddresses [0] Order maker\n /// @param orderAddresses [1] Order taker\n /// @param orderAddresses [2] Order maker asset\n /// @param orderAddresses [3] Order taker asset\n /// @param orderAddresses [4] feeRecipientAddress\n /// @param orderAddresses [5] senderAddress\n /// @param orderAddresses [6] maker fee asset\n /// @param orderAddresses [7] taker fee asset\n /// @param orderValues [0] makerAssetAmount\n /// @param orderValues [1] takerAssetAmount\n /// @param orderValues [2] Maker fee\n /// @param orderValues [3] Taker fee\n /// @param orderValues [4] expirationTimeSeconds\n /// @param orderValues [5] Salt/nonce\n /// @param orderValues [6] Fill amount: amount of taker token to be traded\n /// @param orderValues [7] Dexy signature mode\n /// @param orderData [0] Encoded data specific to maker asset\n /// @param orderData [1] Encoded data specific to taker asset\n /// @param orderData [2] Encoded data specific to maker asset fee\n /// @param orderData [3] Encoded data specific to taker asset fee\n /// @param identifier Order identifier\n /// @param signature Signature of order maker\n\n // Responsibilities of makeOrder are:\n // - check sender\n // - check fund not shut down\n // - check price recent\n // - check risk management passes\n // - approve funds to be traded (if necessary)\n // - make order on the exchange\n // - check order was made (if possible)\n // - place asset in ownedAssets if not already tracked\n function makeOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public virtual { revert(\"Unimplemented\"); }\n\n // Responsibilities of takeOrder are:\n // - check sender\n // - check fund not shut down\n // - check not buying own fund tokens\n // - check price exists for asset pair\n // - check price is recent\n // - check price passes risk management\n // - approve funds to be traded (if necessary)\n // - take order from the exchange\n // - check order was taken (if possible)\n // - place asset in ownedAssets if not already tracked\n function takeOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public virtual { revert(\"Unimplemented\"); }\n\n // responsibilities of cancelOrder are:\n // - check sender is owner, or that order expired, or that fund shut down\n // - remove order from tracking array\n // - cancel order on exchange\n function cancelOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public virtual { revert(\"Unimplemented\"); }\n\n // PUBLIC METHODS\n // PUBLIC VIEW METHODS\n /*\n @return {\n \"makerAsset\": \"Maker asset\",\n \"takerAsset\": \"Taker asset\",\n \"makerQuantity\": \"Amount of maker asset\"\n \"takerQuantity\": \"Amount of taker asset\"\n }\n */\n function getOrder(\n address onExchange,\n uint id,\n address makerAsset\n ) public view virtual returns (\n address,\n address,\n uint,\n uint\n ) { revert(\"Unimplemented\"); }\n}\n"
},
"./src/exchanges/interfaces/IEthfinex.sol": {
"content": "pragma solidity 0.6.1;\n// pragma experimental ABIEncoderV2;\n\n/// @dev Minimal interface for our interactions with EthFinex WrapperLock\ninterface IWrapperLock {\n function balanceOf(address) external view returns (uint256);\n function withdraw(uint256, uint8, bytes32, bytes32, uint256) external returns (bool);\n function deposit(uint256, uint256) external returns (bool);\n}\n\n/// @dev Minimal interface for our interactions with EthFinex WrapperLockEth\ninterface IWrapperLockEth {\n function balanceOf(address) external view returns (uint256);\n function deposit(uint256, uint256) external payable returns (bool);\n}\n\n/// @dev Minimal interface for our interactions with EthFinex WrapperRegistryEFX\ninterface IWrapperRegistryEFX {\n function token2WrapperLookup(address) external view returns (address);\n function wrapper2TokenLookup(address) external view returns (address);\n}\n"
},
"./src/exchanges/interfaces/IKyberNetworkProxy.sol": {
"content": "pragma solidity 0.6.1;\n\n\n/// @title Kyber Network interface\ninterface IKyberNetworkProxy {\n function maxGasPrice() external view returns(uint256);\n function getUserCapInWei(address) external view returns(uint256);\n function getUserCapInTokenWei(address, address) external view returns(uint256);\n function enabled() external view returns(bool);\n function info(bytes32) external view returns(uint256);\n function swapEtherToToken(address, uint256) external payable returns(uint256);\n function swapTokenToEther(address, uint256, uint256) external returns(uint256);\n function swapTokenToToken(address, uint256, address, uint256) external returns(uint);\n function getExpectedRate(address, address, uint256) external view returns (uint256, uint256);\n function tradeWithHint(\n address, uint256, address, address, uint256, uint256, address, bytes calldata\n ) external payable returns(uint256);\n}\n"
},
"./src/exchanges/interfaces/IOasisDex.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @dev Minimal interface for our interactions with OasisDex MatchingMarket\ninterface IOasisDex {\n function getFirstUnsortedOffer() external view returns(uint256);\n function getNextUnsortedOffer(uint256) external view returns(uint256);\n function getBestOffer(address, address) external view returns(uint256);\n function getOffer(uint256) external view returns (uint256, address, uint256, address);\n function getWorseOffer(uint256) external view returns(uint256);\n function isActive(uint256) external view returns (bool);\n function buy(uint256, uint256) external returns (bool);\n function cancel(uint256) external returns (bool);\n function offer(uint256, address, uint256, address) external returns (uint256);\n}\n"
},
"./src/exchanges/interfaces/IUniswapExchange.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @dev Minimal interface for our interactions with UniswapExchange\ninterface IUniswapExchange {\n // Trade ETH to ERC20\n function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient)\n external\n payable\n returns (uint256 tokens_bought);\n // Trade ERC20 to ETH\n function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline)\n external\n returns (uint256 eth_bought);\n // Trade ERC20 to ERC20\n function tokenToTokenTransferInput(\n uint256 tokens_sold,\n uint256 min_tokens_bought,\n uint256 min_eth_bought,\n uint256 deadline,\n address recipient,\n address token_addr\n )\n external\n returns (uint256 tokens_bought);\n\n /// @dev The following functions are only used in tests\n // Provide Liquidity\n function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline)\n external\n payable\n returns (uint256);\n // Get Prices\n function getEthToTokenInputPrice(uint256 eth_sold)\n external\n view\n returns (uint256 tokens_bought);\n function getTokenToEthInputPrice(uint256 tokens_sold)\n external\n view\n returns (uint256 eth_bought);\n}\n"
},
"./src/exchanges/interfaces/IUniswapFactory.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @dev Minimal interface for our interactions with UniswapFactory\ninterface IUniswapFactory {\n function getExchange(address token) external view returns (address exchange);\n}\n"
},
"./src/exchanges/interfaces/IZeroExV2.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\n/// @dev Minimal interface for our interactions with the ZeroEx Exchange contract\ninterface IZeroExV2 {\n struct Order {\n address makerAddress;\n address takerAddress;\n address feeRecipientAddress;\n address senderAddress;\n uint256 makerAssetAmount;\n uint256 takerAssetAmount;\n uint256 makerFee;\n uint256 takerFee;\n uint256 expirationTimeSeconds;\n uint256 salt;\n bytes makerAssetData;\n bytes takerAssetData;\n }\n\n struct OrderInfo {\n uint8 orderStatus;\n bytes32 orderHash;\n uint256 orderTakerAssetFilledAmount;\n }\n\n struct FillResults {\n uint256 makerAssetFilledAmount;\n uint256 takerAssetFilledAmount;\n uint256 makerFeePaid;\n uint256 takerFeePaid;\n }\n\n function ZRX_ASSET_DATA() external view returns (bytes memory);\n function filled(bytes32) external view returns (uint256);\n function cancelled(bytes32) external view returns (bool);\n function getOrderInfo(Order calldata) external view returns (OrderInfo memory);\n function getAssetProxy(bytes4) external view returns (address);\n function isValidSignature(bytes32, address, bytes calldata) external view returns (bool);\n function preSign(bytes32, address, bytes calldata) external;\n function cancelOrder(Order calldata) external;\n function fillOrder(Order calldata, uint256, bytes calldata) external returns (FillResults memory);\n}\n"
},
"./src/exchanges/interfaces/IZeroExV3.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\n/// @dev Minimal interface for our interactions with the ZeroEx Exchange contract\ninterface IZeroExV3 {\n struct Order {\n address makerAddress;\n address takerAddress;\n address feeRecipientAddress;\n address senderAddress;\n uint256 makerAssetAmount;\n uint256 takerAssetAmount;\n uint256 makerFee;\n uint256 takerFee;\n uint256 expirationTimeSeconds;\n uint256 salt;\n bytes makerAssetData;\n bytes takerAssetData;\n bytes makerFeeAssetData;\n bytes takerFeeAssetData;\n }\n\n struct OrderInfo {\n uint8 orderStatus;\n bytes32 orderHash;\n uint256 orderTakerAssetFilledAmount;\n }\n\n struct FillResults {\n uint256 makerAssetFilledAmount;\n uint256 takerAssetFilledAmount;\n uint256 makerFeePaid;\n uint256 takerFeePaid;\n uint256 protocolFeePaid;\n }\n\n function cancelled(bytes32) external view returns (bool);\n function cancelOrder(Order calldata) external;\n function filled(bytes32) external view returns (uint256);\n function fillOrder(Order calldata, uint256, bytes calldata) external payable returns (FillResults memory);\n function getAssetProxy(bytes4) external view returns (address);\n function getOrderInfo(Order calldata) external view returns (OrderInfo memory);\n function isValidOrderSignature(Order calldata, bytes calldata) external view returns (bool);\n function preSign(bytes32) external;\n function protocolFeeCollector() external view returns (address);\n function protocolFeeMultiplier() external view returns (uint256);\n}\n"
},
"./src/exchanges/KyberAdapter.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../dependencies/WETH.sol\";\nimport \"../dependencies/token/IERC20.sol\";\nimport \"../fund/trading/Trading.sol\";\nimport \"../fund/hub/Hub.sol\";\nimport \"../fund/vault/Vault.sol\";\nimport \"../fund/accounting/Accounting.sol\";\nimport \"../prices/IPriceSource.sol\";\nimport \"./interfaces/IKyberNetworkProxy.sol\";\nimport \"./ExchangeAdapter.sol\";\n\ncontract KyberAdapter is DSMath, ExchangeAdapter {\n address public constant ETH_TOKEN_ADDRESS = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);\n\n // NON-CONSTANT METHODS\n\n // Responsibilities of takeOrder (Kybers swapToken) are:\n // - check price recent\n // - check risk management passes\n // - approve funds to be traded (if necessary)\n // - perform swap order on the exchange\n // - place asset in ownedAssets if not already tracked\n /// @notice Swaps srcAmount of srcToken for destAmount of destToken\n /// @dev Variable naming to be close to Kyber's naming\n /// @dev For the purpose of PriceTolerance, fillTakerQuantity == takerAssetQuantity = Dest token amount\n /// @param targetExchange Address of the exchange\n /// @param orderAddresses [2] Maker asset (Dest token)\n /// @param orderAddresses [3] Taker asset (Src token)\n /// @param orderValues [0] Maker asset quantity (Dest token amount)\n /// @param orderValues [1] Taker asset quantity (Src token amount)\n function takeOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public override onlyManager notShutDown {\n Hub hub = getHub();\n\n require(\n orderValues[1] == orderValues[6],\n \"fillTakerQuantity must equal takerAssetQuantity\"\n );\n\n address makerAsset = orderAddresses[2];\n address takerAsset = orderAddresses[3];\n uint makerAssetAmount = orderValues[0];\n uint takerAssetAmount = orderValues[1];\n\n uint minRate = calcMinRate(\n takerAsset,\n makerAsset,\n takerAssetAmount,\n makerAssetAmount\n );\n\n uint actualReceiveAmount = dispatchSwap(\n targetExchange, takerAsset, takerAssetAmount, makerAsset, minRate\n );\n require(\n actualReceiveAmount >= makerAssetAmount,\n \"Received less than expected from Kyber swap\"\n );\n\n getAccounting().addAssetToOwnedAssets(makerAsset);\n getAccounting().updateOwnedAssets();\n getTrading().returnAssetToVault(makerAsset);\n getTrading().orderUpdateHook(\n targetExchange,\n bytes32(0),\n Trading.UpdateType.take,\n [payable(makerAsset), payable(takerAsset)],\n [actualReceiveAmount, takerAssetAmount, takerAssetAmount]\n );\n }\n\n // INTERNAL FUNCTIONS\n\n /// @notice Call different functions based on type of assets supplied\n function dispatchSwap(\n address targetExchange,\n address srcToken,\n uint srcAmount,\n address destToken,\n uint minRate\n )\n internal\n returns (uint actualReceiveAmount)\n {\n\n Hub hub = getHub();\n address nativeAsset = Accounting(hub.accounting()).NATIVE_ASSET();\n\n if (srcToken == nativeAsset) {\n actualReceiveAmount = swapNativeAssetToToken(targetExchange, nativeAsset, srcAmount, destToken, minRate);\n }\n else if (destToken == nativeAsset) {\n actualReceiveAmount = swapTokenToNativeAsset(targetExchange, srcToken, srcAmount, nativeAsset, minRate);\n }\n else {\n actualReceiveAmount = swapTokenToToken(targetExchange, srcToken, srcAmount, destToken, minRate);\n }\n }\n\n /// @dev If minRate is not defined, uses expected rate from the network\n /// @param targetExchange Address of Kyber proxy contract\n /// @param nativeAsset Native asset address as src token\n /// @param srcAmount Amount of native asset supplied\n /// @param destToken Address of dest token\n /// @param minRate Minimum rate supplied to the Kyber proxy\n /// @return receivedAmount Actual amount of destToken received from the exchange\n function swapNativeAssetToToken(\n address targetExchange,\n address nativeAsset,\n uint srcAmount,\n address destToken,\n uint minRate\n )\n internal\n returns (uint receivedAmount)\n {\n // Convert WETH to ETH\n Hub hub = getHub();\n Vault vault = Vault(hub.vault());\n vault.withdraw(nativeAsset, srcAmount);\n WETH(payable(nativeAsset)).withdraw(srcAmount);\n receivedAmount = IKyberNetworkProxy(targetExchange).swapEtherToToken.value(srcAmount)(destToken, minRate);\n }\n\n /// @dev If minRate is not defined, uses expected rate from the network\n /// @param targetExchange Address of Kyber proxy contract\n /// @param srcToken Address of src token\n /// @param srcAmount Amount of src token supplied\n /// @param nativeAsset Native asset address as src token\n /// @param minRate Minimum rate supplied to the Kyber proxy\n /// @return receivedAmount Actual amount of destToken received from the exchange\n function swapTokenToNativeAsset(\n address targetExchange,\n address srcToken,\n uint srcAmount,\n address nativeAsset,\n uint minRate\n )\n internal\n returns (uint receivedAmount)\n {\n withdrawAndApproveAsset(srcToken, targetExchange, srcAmount, \"takerAsset\");\n receivedAmount = IKyberNetworkProxy(targetExchange).swapTokenToEther(srcToken, srcAmount, minRate);\n\n // Convert ETH to WETH\n WETH(payable(nativeAsset)).deposit.value(receivedAmount)();\n }\n\n /// @dev If minRate is not defined, uses expected rate from the network\n /// @param targetExchange Address of Kyber proxy contract\n /// @param srcToken Address of src token\n /// @param srcAmount Amount of src token supplied\n /// @param destToken Address of dest token\n /// @param minRate Minimum rate supplied to the Kyber proxy\n /// @return receivedAmount Actual amount of destToken received from the exchange\n function swapTokenToToken(\n address targetExchange,\n address srcToken,\n uint srcAmount,\n address destToken,\n uint minRate\n )\n internal\n returns (uint receivedAmount)\n {\n withdrawAndApproveAsset(srcToken, targetExchange, srcAmount, \"takerAsset\");\n\n receivedAmount = IKyberNetworkProxy(targetExchange).swapTokenToToken(srcToken, srcAmount, destToken, minRate);\n }\n\n /// @param srcToken Address of src token\n /// @param destToken Address of dest token\n /// @param srcAmount Amount of src token\n /// @return minRate Minimum rate to be supplied to the network for some order params\n function calcMinRate(\n address srcToken,\n address destToken,\n uint srcAmount,\n uint destAmount\n )\n internal\n view\n returns (uint minRate)\n {\n IPriceSource pricefeed = IPriceSource(getHub().priceSource());\n minRate = pricefeed.getOrderPriceInfo(\n srcToken,\n destToken,\n srcAmount,\n destAmount\n );\n }\n}\n"
},
"./src/exchanges/OasisDexAccessor.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"./interfaces/IOasisDex.sol\";\n\ncontract OasisDexAccessor {\n function getUnsortedOfferIds(\n address targetExchange,\n address sellAsset,\n address buyAsset\n )\n public\n view\n returns (uint[] memory)\n {\n IOasisDex market = IOasisDex(targetExchange);\n uint[] memory ids = new uint[](1000);\n uint count = 0;\n\n // Iterate over all unsorted offers up to 1000 iterations.\n uint id = market.getFirstUnsortedOffer();\n for (uint i = 0; i < 1000; i++) {\n if (id == 0) {\n break;\n }\n\n if (market.isActive(id)) {\n address sellGem;\n address buyGem;\n (, sellGem, , buyGem) = market.getOffer(id);\n\n if (sellGem == sellAsset && buyGem == buyAsset) {\n ids[count++] = id;\n }\n }\n\n // Get the next offer and repeat.\n id = market.getNextUnsortedOffer(id);\n }\n\n // Create a new array of offers with the correct size.\n uint[] memory copy = new uint[](count);\n for (uint i = 0; i < count; i++) {\n copy[i] = ids[i];\n }\n\n return copy;\n }\n\n function getSortedOfferIds(\n address targetExchange,\n address sellAsset,\n address buyAsset\n )\n public\n view\n returns(uint[] memory)\n {\n IOasisDex market = IOasisDex(targetExchange);\n uint[] memory ids = new uint[](1000);\n uint count = 0;\n\n // Iterate over all sorted offers.\n uint id = market.getBestOffer(sellAsset, buyAsset);\n for (uint i = 0; i < 1000 ; i++ ) {\n if (id == 0) {\n break;\n }\n\n if (market.isActive(id)) {\n ids[count++] = id;\n }\n\n // Get the next offer and repeat.\n id = market.getWorseOffer(id);\n }\n\n // Create a new array of offers with the correct size.\n uint[] memory copy = new uint[](count);\n for (uint i = 0; i < count; i++) {\n copy[i] = ids[i];\n }\n\n return copy;\n }\n\n function getOrders(\n address targetExchange,\n address sellAsset,\n address buyAsset\n )\n public\n view\n returns (uint[] memory, uint[] memory, uint[] memory) {\n IOasisDex market = IOasisDex(targetExchange);\n uint[] memory sIds = getSortedOfferIds(targetExchange, sellAsset, buyAsset);\n uint[] memory uIds = getUnsortedOfferIds(targetExchange, sellAsset, buyAsset);\n uint[] memory ids = new uint[](uIds.length + sIds.length);\n uint[] memory sellQtys = new uint[](ids.length);\n uint[] memory buyQtys = new uint[](ids.length);\n\n for (uint i = 0; i < sIds.length; i++) {\n ids[i] = sIds[i];\n }\n\n for (uint i = 0; i < uIds.length; i++) {\n ids[i + sIds.length] = uIds[i];\n }\n\n for (uint i = 0; i < ids.length; i++) {\n uint sellQty;\n uint buyQty;\n (sellQty, , buyQty,) = market.getOffer(ids[i]);\n sellQtys[i] = sellQty;\n buyQtys[i] = buyQty;\n }\n\n return (ids, sellQtys, buyQtys);\n }\n}\n"
},
"./src/exchanges/OasisDexAdapter.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../fund/hub/Hub.sol\";\nimport \"../fund/trading/Trading.sol\";\nimport \"../fund/vault/Vault.sol\";\nimport \"../fund/accounting/Accounting.sol\";\nimport \"../dependencies/DSMath.sol\";\nimport \"./interfaces/IOasisDex.sol\";\nimport \"./ExchangeAdapter.sol\";\n\n/// @title OasisDexAdapter Contract\n/// @author Melonport AG <[email protected]>\n/// @notice Adapter between Melon and OasisDex Matching Market\ncontract OasisDexAdapter is DSMath, ExchangeAdapter {\n\n event OrderCreated(uint256 id);\n\n // METHODS\n\n // PUBLIC METHODS\n\n // Responsibilities of makeOrder are:\n // - check sender\n // - check fund not shut down\n // - check price recent\n // - check risk management passes\n // - approve funds to be traded (if necessary)\n // - make order on the exchange\n // - check order was made (if possible)\n // - place asset in ownedAssets if not already tracked\n /// @notice Makes an order on the selected exchange\n /// @dev These orders are not expected to settle immediately\n /// @param targetExchange Address of the exchange\n /// @param orderAddresses [2] Order maker asset\n /// @param orderAddresses [3] Order taker asset\n /// @param orderValues [0] Maker token quantity\n /// @param orderValues [1] Taker token quantity\n function makeOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public override onlyManager notShutDown {\n ensureCanMakeOrder(orderAddresses[2]);\n address makerAsset = orderAddresses[2];\n address takerAsset = orderAddresses[3];\n uint256 makerQuantity = orderValues[0];\n uint256 takerQuantity = orderValues[1];\n\n // Order parameter checks\n getTrading().updateAndGetQuantityBeingTraded(makerAsset);\n ensureNotInOpenMakeOrder(makerAsset);\n\n withdrawAndApproveAsset(makerAsset, targetExchange, makerQuantity, \"makerAsset\");\n\n uint256 orderId = IOasisDex(targetExchange).offer(makerQuantity, makerAsset, takerQuantity, takerAsset);\n\n // defines success in MatchingMarket\n require(orderId != 0, \"Order ID should not be zero\");\n\n getAccounting().addAssetToOwnedAssets(takerAsset);\n getTrading().orderUpdateHook(\n targetExchange,\n bytes32(orderId),\n Trading.UpdateType.make,\n [payable(makerAsset), payable(takerAsset)],\n [makerQuantity, takerQuantity, uint256(0)]\n );\n getTrading().addOpenMakeOrder(targetExchange, makerAsset, takerAsset, orderId, orderValues[4]);\n emit OrderCreated(orderId);\n }\n\n // Responsibilities of takeOrder are:\n // - check sender\n // - check fund not shut down\n // - check not buying own fund tokens\n // - check price exists for asset pair\n // - check price is recent\n // - check price passes risk management\n // - approve funds to be traded (if necessary)\n // - take order from the exchange\n // - check order was taken (if possible)\n // - place asset in ownedAssets if not already tracked\n /// @notice Takes an active order on the selected exchange\n /// @dev These orders are expected to settle immediately\n /// @param targetExchange Address of the exchange\n /// @param orderValues [6] Fill amount : amount of taker token to fill\n /// @param identifier Active order id\n function takeOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public override onlyManager notShutDown {\n Hub hub = getHub();\n uint256 fillTakerQuantity = orderValues[6];\n uint256 maxMakerQuantity;\n address makerAsset;\n uint256 maxTakerQuantity;\n address takerAsset;\n (\n maxMakerQuantity,\n makerAsset,\n maxTakerQuantity,\n takerAsset\n ) = IOasisDex(targetExchange).getOffer(uint256(identifier));\n uint256 fillMakerQuantity = mul(fillTakerQuantity, maxMakerQuantity) / maxTakerQuantity;\n\n require(\n makerAsset == orderAddresses[2] && takerAsset == orderAddresses[3],\n \"Maker and taker assets do not match the order addresses\"\n );\n require(\n makerAsset != takerAsset,\n \"Maker and taker assets cannot be the same\"\n );\n require(fillMakerQuantity <= maxMakerQuantity, \"Maker amount to fill above max\");\n require(fillTakerQuantity <= maxTakerQuantity, \"Taker amount to fill above max\");\n\n withdrawAndApproveAsset(takerAsset, targetExchange, fillTakerQuantity, \"takerAsset\");\n\n require(\n IOasisDex(targetExchange).buy(uint256(identifier), fillMakerQuantity),\n \"Buy on matching market failed\"\n );\n\n getAccounting().addAssetToOwnedAssets(makerAsset);\n getAccounting().updateOwnedAssets();\n getTrading().returnAssetToVault(makerAsset);\n getTrading().orderUpdateHook(\n targetExchange,\n bytes32(identifier),\n Trading.UpdateType.take,\n [payable(makerAsset), payable(takerAsset)],\n [maxMakerQuantity, maxTakerQuantity, fillTakerQuantity]\n );\n }\n\n // responsibilities of cancelOrder are:\n // - check sender is owner, or that order expired, or that fund shut down\n // - remove order from tracking array\n // - cancel order on exchange\n /// @notice Cancels orders that were not expected to settle immediately\n /// @param targetExchange Address of the exchange\n /// @param orderAddresses [2] Order maker asset\n /// @param identifier Order ID on the exchange\n function cancelOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public override {\n require(uint256(identifier) != 0, \"ID cannot be zero\");\n\n address makerAsset;\n (, makerAsset, ,) = IOasisDex(targetExchange).getOffer(uint256(identifier));\n ensureCancelPermitted(targetExchange, makerAsset);\n\n require(\n address(makerAsset) == orderAddresses[2],\n \"Retrieved and passed assets do not match\"\n );\n\n getTrading().removeOpenMakeOrder(targetExchange, makerAsset);\n IOasisDex(targetExchange).cancel(\n uint256(identifier)\n );\n getTrading().returnAssetToVault(makerAsset);\n getAccounting().updateOwnedAssets();\n getTrading().orderUpdateHook(\n targetExchange,\n bytes32(identifier),\n Trading.UpdateType.cancel,\n [address(0), address(0)],\n [uint256(0), uint256(0), uint256(0)]\n );\n }\n\n // VIEW METHODS\n\n function getOrder(address targetExchange, uint256 id, address makerAsset)\n public\n view\n override\n returns (address, address, uint256, uint256)\n {\n uint256 sellQuantity;\n address sellAsset;\n uint256 buyQuantity;\n address buyAsset;\n (\n sellQuantity,\n sellAsset,\n buyQuantity,\n buyAsset\n ) = IOasisDex(targetExchange).getOffer(id);\n return (\n sellAsset,\n buyAsset,\n sellQuantity,\n buyQuantity\n );\n }\n}\n"
},
"./src/exchanges/UniswapAdapter.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../dependencies/token/IERC20.sol\";\nimport \"../dependencies/WETH.sol\";\nimport \"../fund/accounting/Accounting.sol\";\nimport \"../fund/hub/Hub.sol\";\nimport \"../fund/trading/Trading.sol\";\nimport \"../fund/vault/Vault.sol\";\nimport \"./interfaces/IUniswapFactory.sol\";\nimport \"./interfaces/IUniswapExchange.sol\";\nimport \"./ExchangeAdapter.sol\";\n\ncontract UniswapAdapter is DSMath, ExchangeAdapter {\n /// @notice Take order that uses a user-defined src token amount to trade for a dest token amount\n /// @dev For the purpose of PriceTolerance, _orderValues [1] == _orderValues [6] = Dest token amount\n /// @param _targetExchange Address of Uniswap factory contract\n /// @param _orderAddresses [2] Maker asset (Dest token)\n /// @param _orderAddresses [3] Taker asset (Src token)\n /// @param _orderValues [0] Maker asset quantity (Dest token amount)\n /// @param _orderValues [1] Taker asset quantity (Src token amount)\n /// @param _orderValues [6] Taker asset fill amount\n function takeOrder(\n address _targetExchange,\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData,\n bytes32 _identifier,\n bytes memory _signature\n )\n public\n override\n onlyManager\n notShutDown\n {\n require(\n _orderValues[1] == _orderValues[6],\n \"Taker asset amount must equal taker asset fill amount\"\n );\n\n address makerAsset = _orderAddresses[2];\n address takerAsset = _orderAddresses[3];\n uint makerAssetAmount = _orderValues[0];\n uint takerAssetAmount = _orderValues[1];\n\n uint actualReceiveAmount = dispatchSwap(\n _targetExchange, takerAsset, takerAssetAmount, makerAsset, makerAssetAmount\n );\n require(\n actualReceiveAmount >= makerAssetAmount,\n \"Received less than expected from Uniswap exchange\"\n );\n\n updateStateTakeOrder(\n _targetExchange,\n makerAsset,\n takerAsset,\n takerAssetAmount,\n actualReceiveAmount\n );\n }\n\n // INTERNAL FUNCTIONS\n\n /// @notice Call different functions based on type of assets supplied\n /// @param _targetExchange Address of Uniswap factory contract\n /// @param _srcToken Address of src token\n /// @param _srcAmount Amount of src token supplied\n /// @param _destToken Address of dest token\n /// @param _minDestAmount Minimum amount of dest token to receive\n /// @return actualReceiveAmount_ Actual amount of _destToken received\n function dispatchSwap(\n address _targetExchange,\n address _srcToken,\n uint _srcAmount,\n address _destToken,\n uint _minDestAmount\n )\n internal\n returns (uint actualReceiveAmount_)\n {\n require(\n _srcToken != _destToken,\n \"Src token cannot be the same as dest token\"\n );\n\n Hub hub = getHub();\n address nativeAsset = Accounting(hub.accounting()).NATIVE_ASSET();\n\n if (_srcToken == nativeAsset) {\n actualReceiveAmount_ = swapNativeAssetToToken(\n _targetExchange,\n nativeAsset,\n _srcAmount,\n _destToken,\n _minDestAmount\n );\n } else if (_destToken == nativeAsset) {\n actualReceiveAmount_ = swapTokenToNativeAsset(\n _targetExchange,\n _srcToken,\n _srcAmount,\n nativeAsset,\n _minDestAmount\n );\n } else {\n actualReceiveAmount_ = swapTokenToToken(\n _targetExchange,\n _srcToken,\n _srcAmount,\n _destToken,\n _minDestAmount\n );\n }\n }\n\n /// @param _targetExchange Address of Uniswap factory contract\n /// @param _nativeAsset Native asset address as src token\n /// @param _srcAmount Amount of native asset supplied\n /// @param _destToken Address of dest token\n /// @param _minDestAmount Minimum amount of dest token to get back\n /// @return actualReceiveAmount_ Actual amount of _destToken received\n function swapNativeAssetToToken(\n address _targetExchange,\n address _nativeAsset,\n uint _srcAmount,\n address _destToken,\n uint _minDestAmount\n )\n internal\n returns (uint actualReceiveAmount_)\n {\n // Convert WETH to ETH\n Hub hub = getHub();\n Vault vault = Vault(hub.vault());\n vault.withdraw(_nativeAsset, _srcAmount);\n WETH(payable(_nativeAsset)).withdraw(_srcAmount);\n\n address tokenExchange = IUniswapFactory(_targetExchange).getExchange(_destToken);\n actualReceiveAmount_ = IUniswapExchange(tokenExchange).ethToTokenTransferInput.value(\n _srcAmount\n )\n (\n _minDestAmount,\n add(block.timestamp, 1),\n address(vault)\n );\n }\n\n /// @param _targetExchange Address of Uniswap factory contract\n /// @param _srcToken Address of src token\n /// @param _srcAmount Amount of src token supplied\n /// @param _nativeAsset Native asset address as dest token\n /// @param _minDestAmount Minimum amount of dest token to get back\n /// @return actualReceiveAmount_ Actual amount of _destToken received\n function swapTokenToNativeAsset(\n address _targetExchange,\n address _srcToken,\n uint _srcAmount,\n address _nativeAsset,\n uint _minDestAmount\n )\n internal\n returns (uint actualReceiveAmount_)\n {\n address tokenExchange = IUniswapFactory(_targetExchange).getExchange(_srcToken);\n withdrawAndApproveAsset(_srcToken, tokenExchange, _srcAmount, \"takerAsset\");\n actualReceiveAmount_ = IUniswapExchange(tokenExchange).tokenToEthSwapInput(\n _srcAmount,\n _minDestAmount,\n add(block.timestamp, 1)\n );\n\n // Convert ETH to WETH and move to Vault\n WETH(payable(_nativeAsset)).deposit.value(actualReceiveAmount_)();\n getTrading().returnAssetToVault(_nativeAsset);\n }\n\n /// @param _targetExchange Address of Uniswap factory contract\n /// @param _srcToken Address of src token\n /// @param _srcAmount Amount of src token supplied\n /// @param _destToken Address of dest token\n /// @param _minDestAmount Minimum amount of dest token to get back\n /// @return actualReceiveAmount_ Actual amount of _destToken received\n function swapTokenToToken(\n address _targetExchange,\n address _srcToken,\n uint _srcAmount,\n address _destToken,\n uint _minDestAmount\n )\n internal\n returns (uint actualReceiveAmount_)\n {\n Hub hub = getHub();\n address tokenExchange = IUniswapFactory(_targetExchange).getExchange(_srcToken);\n withdrawAndApproveAsset(_srcToken, tokenExchange, _srcAmount, \"takerAsset\");\n actualReceiveAmount_ = IUniswapExchange(tokenExchange).tokenToTokenTransferInput(\n _srcAmount,\n _minDestAmount,\n 1,\n add(block.timestamp, 1),\n address(Vault(hub.vault())),\n _destToken\n );\n }\n\n function updateStateTakeOrder(\n address _targetExchange,\n address _makerAsset,\n address _takerAsset,\n uint256 _takerAssetAmount,\n uint256 _actualReceiveAmount\n )\n internal\n {\n getAccounting().addAssetToOwnedAssets(_makerAsset);\n getAccounting().updateOwnedAssets();\n getTrading().orderUpdateHook(\n _targetExchange,\n bytes32(0),\n Trading.UpdateType.take,\n [payable(_makerAsset), payable(_takerAsset)],\n [_actualReceiveAmount, _takerAssetAmount, _takerAssetAmount]\n );\n }\n}\n"
},
"./src/exchanges/ZeroExV2Adapter.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../dependencies/token/IERC20.sol\";\nimport \"../fund/trading/Trading.sol\";\nimport \"../fund/hub/Hub.sol\";\nimport \"../fund/vault/Vault.sol\";\nimport \"../fund/accounting/Accounting.sol\";\nimport \"../dependencies/DSMath.sol\";\nimport \"./interfaces/IZeroExV2.sol\";\nimport \"./ExchangeAdapter.sol\";\n\n/// @title ZeroExV2Adapter Contract\n/// @author Melonport AG <[email protected]>\n/// @notice Adapter to 0xV2 Exchange Contract\ncontract ZeroExV2Adapter is DSMath, ExchangeAdapter {\n /// @param orderAddresses [2] Order maker asset\n /// @param orderAddresses [3] Order taker asset\n /// @param orderData [0] Order maker asset data\n /// @param orderData [1] Order taker asset data\n modifier orderAddressesMatchOrderData(\n address[8] memory orderAddresses,\n bytes[4] memory orderData\n )\n {\n require(\n getAssetAddress(orderData[0]) == orderAddresses[2],\n \"Maker asset data does not match order address in array\"\n );\n require(\n getAssetAddress(orderData[1]) == orderAddresses[3],\n \"Taker asset data does not match order address in array\"\n );\n _;\n }\n\n // METHODS\n\n // PUBLIC METHODS\n\n /// @notice Make order by pre-approving signatures\n function makeOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n )\n public\n override\n onlyManager\n notShutDown\n orderAddressesMatchOrderData(orderAddresses, orderData)\n {\n ensureCanMakeOrder(orderAddresses[2]);\n\n IZeroExV2.Order memory order = constructOrderStruct(orderAddresses, orderValues, orderData);\n address makerAsset = getAssetAddress(orderData[0]);\n address takerAsset = getAssetAddress(orderData[1]);\n\n // Order parameter checks\n getTrading().updateAndGetQuantityBeingTraded(makerAsset);\n ensureNotInOpenMakeOrder(makerAsset);\n\n approveAssetsMakeOrder(targetExchange, order);\n\n IZeroExV2.OrderInfo memory orderInfo = IZeroExV2(targetExchange).getOrderInfo(order);\n IZeroExV2(targetExchange).preSign(orderInfo.orderHash, address(this), signature);\n\n require(\n IZeroExV2(targetExchange).isValidSignature(\n orderInfo.orderHash,\n address(this),\n signature\n ),\n \"INVALID_ORDER_SIGNATURE\"\n );\n\n updateStateMakeOrder(targetExchange, order);\n }\n\n // Responsibilities of takeOrder are:\n // - check sender\n // - check fund not shut down\n // - check not buying own fund tokens\n // - check price exists for asset pair\n // - check price is recent\n // - check price passes risk management\n // - approve funds to be traded (if necessary)\n // - take order from the exchange\n // - check order was taken (if possible)\n // - place asset in ownedAssets if not already tracked\n /// @notice Takes an active order on the selected exchange\n /// @dev These orders are expected to settle immediately\n /// @param targetExchange Address of the exchange\n /// @param orderAddresses [0] Order maker\n /// @param orderAddresses [1] Order taker\n /// @param orderAddresses [2] Order maker asset\n /// @param orderAddresses [3] Order taker asset\n /// @param orderAddresses [4] feeRecipientAddress\n /// @param orderAddresses [5] senderAddress\n /// @param orderValues [0] makerAssetAmount\n /// @param orderValues [1] takerAssetAmount\n /// @param orderValues [2] Maker fee\n /// @param orderValues [3] Taker fee\n /// @param orderValues [4] expirationTimeSeconds\n /// @param orderValues [5] Salt/nonce\n /// @param orderValues [6] Fill amount: amount of taker token to be traded\n /// @param orderValues [7] Dexy signature mode\n /// @param orderData [0] Encoded data specific to maker asset\n /// @param orderData [1] Encoded data specific to taker asset\n /// @param orderData [2] Encoded data specific to maker asset fee\n /// @param orderData [3] Encoded data specific to taker asset fee\n /// @param identifier Order identifier\n /// @param signature Signature of the order.\n function takeOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n )\n public\n override\n onlyManager\n notShutDown\n orderAddressesMatchOrderData(orderAddresses, orderData)\n {\n IZeroExV2.Order memory order = constructOrderStruct(orderAddresses, orderValues, orderData);\n\n uint fillTakerQuantity = orderValues[6];\n\n approveAssetsTakeOrder(targetExchange, order);\n\n uint takerAssetFilledAmount = executeFill(targetExchange, order, fillTakerQuantity, signature);\n require(\n takerAssetFilledAmount == fillTakerQuantity,\n \"Filled amount does not match desired fill amount\"\n );\n\n updateStateTakeOrder(targetExchange, order, fillTakerQuantity);\n }\n\n /// @notice Cancel the 0x make order\n function cancelOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n )\n public\n override\n orderAddressesMatchOrderData(orderAddresses, orderData)\n {\n IZeroExV2.Order memory order = getTrading().getZeroExV2OrderDetails(identifier);\n ensureCancelPermitted(targetExchange, getAssetAddress(order.makerAssetData));\n\n if (order.expirationTimeSeconds > block.timestamp) {\n IZeroExV2(targetExchange).cancelOrder(order);\n }\n\n revokeApproveAssetsCancelOrder(targetExchange, order);\n\n updateStateCancelOrder(targetExchange, order);\n }\n\n /// @dev Get order details\n function getOrder(address targetExchange, uint256 id, address makerAsset)\n public\n view\n override\n returns (address, address, uint256, uint256)\n {\n uint orderId;\n uint orderIndex;\n address takerAsset;\n uint makerQuantity;\n uint takerQuantity;\n (orderId, , orderIndex) = Trading(msg.sender).getOpenOrderInfo(targetExchange, makerAsset);\n (, takerAsset, makerQuantity, takerQuantity) = Trading(msg.sender).getOrderDetails(orderIndex);\n uint takerAssetFilledAmount = IZeroExV2(targetExchange).filled(bytes32(orderId));\n uint makerAssetFilledAmount = mul(takerAssetFilledAmount, makerQuantity) / takerQuantity;\n if (IZeroExV2(targetExchange).cancelled(bytes32(orderId)) || sub(takerQuantity, takerAssetFilledAmount) == 0) {\n return (makerAsset, takerAsset, 0, 0);\n }\n return (\n makerAsset,\n takerAsset,\n sub(makerQuantity, makerAssetFilledAmount),\n sub(takerQuantity, takerAssetFilledAmount)\n );\n }\n\n // INTERNAL METHODS\n\n /// @notice Approves makerAsset, makerFee\n function approveAssetsMakeOrder(address _targetExchange, IZeroExV2.Order memory _order)\n internal\n {\n withdrawAndApproveAsset(\n getAssetAddress(_order.makerAssetData),\n getAssetProxy(_targetExchange, _order.makerAssetData),\n _order.makerAssetAmount,\n \"makerAsset\"\n );\n if (_order.makerFee > 0) {\n bytes memory zrxAssetData = IZeroExV2(_targetExchange).ZRX_ASSET_DATA();\n withdrawAndApproveAsset(\n getAssetAddress(zrxAssetData),\n getAssetProxy(_targetExchange, zrxAssetData),\n _order.makerFee,\n \"makerFeeAsset\"\n );\n }\n }\n\n /// @notice Approves takerAsset, takerFee\n function approveAssetsTakeOrder(address _targetExchange, IZeroExV2.Order memory _order)\n internal\n {\n withdrawAndApproveAsset(\n getAssetAddress(_order.takerAssetData),\n getAssetProxy(_targetExchange, _order.takerAssetData),\n _order.takerAssetAmount,\n \"takerAsset\"\n );\n if (_order.takerFee > 0) {\n bytes memory zrxAssetData = IZeroExV2(_targetExchange).ZRX_ASSET_DATA();\n withdrawAndApproveAsset(\n getAssetAddress(zrxAssetData),\n getAssetProxy(_targetExchange, zrxAssetData),\n _order.takerFee,\n \"takerFeeAsset\"\n );\n }\n }\n\n /// @dev Needed to avoid stack too deep error\n function executeFill(\n address targetExchange,\n IZeroExV2.Order memory order,\n uint256 takerAssetFillAmount,\n bytes memory signature\n )\n internal\n returns (uint256)\n {\n address makerAsset = getAssetAddress(order.makerAssetData);\n uint preMakerAssetBalance = IERC20(makerAsset).balanceOf(address(this));\n\n IZeroExV2.FillResults memory fillResults = IZeroExV2(targetExchange).fillOrder(\n order,\n takerAssetFillAmount,\n signature\n );\n\n uint256 postMakerAssetBalance = IERC20(makerAsset).balanceOf(address(this));\n\n // Account for case where makerAsset is ZRX (same as takerFee)\n uint256 makerAssetFeesTotal;\n if (makerAsset == getAssetAddress(IZeroExV2(targetExchange).ZRX_ASSET_DATA())) {\n makerAssetFeesTotal = add(makerAssetFeesTotal, order.takerFee);\n }\n\n require(\n postMakerAssetBalance == sub(\n add(preMakerAssetBalance, fillResults.makerAssetFilledAmount),\n makerAssetFeesTotal\n ),\n \"Maker asset balance different than expected\"\n );\n\n return fillResults.takerAssetFilledAmount;\n }\n\n /// @notice Revoke asset approvals and return assets to vault\n function revokeApproveAssetsCancelOrder(\n address _targetExchange,\n IZeroExV2.Order memory _order\n )\n internal\n {\n address makerAsset = getAssetAddress(_order.makerAssetData);\n bytes memory makerFeeAssetData = IZeroExV2(_targetExchange).ZRX_ASSET_DATA();\n address makerFeeAsset = getAssetAddress(makerFeeAssetData);\n\n revokeApproveAsset(\n makerAsset,\n getAssetProxy(_targetExchange, _order.makerAssetData),\n _order.makerAssetAmount,\n \"makerAsset\"\n );\n getTrading().returnAssetToVault(makerAsset);\n\n if (_order.makerFee > 0) {\n revokeApproveAsset(\n makerFeeAsset,\n getAssetProxy(_targetExchange, makerFeeAssetData),\n _order.makerFee,\n \"makerFeeAsset\"\n );\n if (makerFeeAsset != makerAsset) getTrading().returnAssetToVault(makerFeeAsset);\n }\n }\n\n /// @dev Avoids stack too deep error\n function updateStateCancelOrder(address targetExchange, IZeroExV2.Order memory order)\n internal\n {\n address makerAsset = getAssetAddress(order.makerAssetData);\n\n getTrading().removeOpenMakeOrder(targetExchange, makerAsset);\n getAccounting().updateOwnedAssets();\n getTrading().orderUpdateHook(\n targetExchange,\n IZeroExV2(targetExchange).getOrderInfo(order).orderHash,\n Trading.UpdateType.cancel,\n [address(0), address(0)],\n [uint(0), uint(0), uint(0)]\n );\n }\n\n /// @dev Avoids stack too deep error\n function updateStateMakeOrder(address targetExchange, IZeroExV2.Order memory order)\n internal\n {\n address makerAsset = getAssetAddress(order.makerAssetData);\n address takerAsset = getAssetAddress(order.takerAssetData);\n IZeroExV2.OrderInfo memory orderInfo = IZeroExV2(targetExchange).getOrderInfo(order);\n\n getAccounting().addAssetToOwnedAssets(takerAsset);\n getTrading().orderUpdateHook(\n targetExchange,\n orderInfo.orderHash,\n Trading.UpdateType.make,\n [payable(makerAsset), payable(takerAsset)],\n [order.makerAssetAmount, order.takerAssetAmount, uint(0)]\n );\n getTrading().addOpenMakeOrder(\n targetExchange,\n makerAsset,\n takerAsset,\n uint256(orderInfo.orderHash),\n order.expirationTimeSeconds\n );\n getTrading().addZeroExV2OrderData(orderInfo.orderHash, order);\n }\n\n /// @dev avoids stack too deep error\n function updateStateTakeOrder(\n address targetExchange,\n IZeroExV2.Order memory order,\n uint256 fillTakerQuantity\n )\n internal\n {\n address makerAsset = getAssetAddress(order.makerAssetData);\n address takerAsset = getAssetAddress(order.takerAssetData);\n\n getAccounting().addAssetToOwnedAssets(makerAsset);\n getAccounting().updateOwnedAssets();\n getTrading().returnAssetToVault(makerAsset);\n getTrading().orderUpdateHook(\n targetExchange,\n IZeroExV2(targetExchange).getOrderInfo(order).orderHash,\n Trading.UpdateType.take,\n [payable(makerAsset), payable(takerAsset)],\n [order.makerAssetAmount, order.takerAssetAmount, fillTakerQuantity]\n );\n }\n\n // VIEW METHODS\n\n function constructOrderStruct(\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData\n )\n internal\n view\n returns (IZeroExV2.Order memory order)\n {\n order = IZeroExV2.Order({\n makerAddress: orderAddresses[0],\n takerAddress: orderAddresses[1],\n feeRecipientAddress: orderAddresses[4],\n senderAddress: orderAddresses[5],\n makerAssetAmount: orderValues[0],\n takerAssetAmount: orderValues[1],\n makerFee: orderValues[2],\n takerFee: orderValues[3],\n expirationTimeSeconds: orderValues[4],\n salt: orderValues[5],\n makerAssetData: orderData[0],\n takerAssetData: orderData[1]\n });\n }\n\n function getAssetProxy(address targetExchange, bytes memory assetData)\n internal\n view\n returns (address assetProxy)\n {\n bytes4 assetProxyId;\n assembly {\n assetProxyId := and(mload(\n add(assetData, 32)),\n 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000\n )\n }\n assetProxy = IZeroExV2(targetExchange).getAssetProxy(assetProxyId);\n }\n\n function getAssetAddress(bytes memory assetData)\n internal\n view\n returns (address assetAddress)\n {\n assembly {\n assetAddress := mload(add(assetData, 36))\n }\n }\n}\n"
},
"./src/exchanges/ZeroExV3Adapter.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../dependencies/token/IERC20.sol\";\nimport \"../fund/trading/Trading.sol\";\nimport \"../fund/hub/Hub.sol\";\nimport \"../fund/vault/Vault.sol\";\nimport \"../fund/accounting/Accounting.sol\";\nimport \"../dependencies/DSMath.sol\";\nimport \"./interfaces/IZeroExV3.sol\";\nimport \"./ExchangeAdapter.sol\";\n\n/// @title ZeroExV3Adapter Contract\n/// @author Melonport AG <[email protected]>\n/// @notice Adapter to 0xV3 Exchange Contract\ncontract ZeroExV3Adapter is DSMath, ExchangeAdapter {\n\n /// @param _orderAddresses [2] Order maker asset\n /// @param _orderAddresses [3] Order taker asset\n /// @param _orderAddresses [6] Order maker fee asset\n /// @param _orderAddresses [7] Order taker fee asset\n /// @param _orderValues [2] Order maker fee amount\n /// @param _orderValues [3] Order taker fee amount\n modifier orderAddressesMatchOrderData(\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData\n )\n {\n require(\n getAssetAddress(_orderData[0]) == _orderAddresses[2],\n \"Maker asset data does not match order address in array\"\n );\n require(\n getAssetAddress(_orderData[1]) == _orderAddresses[3],\n \"Taker asset data does not match order address in array\"\n );\n if (_orderValues[2] > 0) {\n require(\n getAssetAddress(_orderData[2]) == _orderAddresses[6],\n \"Maker fee asset data does not match order address in array\"\n );\n }\n if (_orderValues[3] > 0) {\n require(\n getAssetAddress(_orderData[3]) == _orderAddresses[7],\n \"Taker fee asset data does not match order address in array\"\n );\n }\n _;\n }\n\n // METHODS\n\n // PUBLIC METHODS\n\n /// @notice Make order by pre-approving signatures\n /// @param _targetExchange Address of the exchange\n /// @param _orderAddresses [2] Maker asset (Dest token)\n /// @param _orderAddresses [3] Taker asset (Src token)\n /// @param _orderData [0] Encoded data specific to maker asset\n /// @param _orderData [1] Encoded data specific to taker asset\n /// @param _signature _signature of the order.\n function makeOrder(\n address _targetExchange,\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData,\n bytes32 _identifier,\n bytes memory _signature\n )\n public\n override\n onlyManager\n notShutDown\n orderAddressesMatchOrderData(_orderAddresses, _orderValues, _orderData)\n {\n ensureCanMakeOrder(_orderAddresses[2]);\n Hub hub = getHub();\n\n IZeroExV3.Order memory order = constructOrderStruct(_orderAddresses, _orderValues, _orderData);\n address makerAsset = getAssetAddress(_orderData[0]);\n address takerAsset = getAssetAddress(_orderData[1]);\n\n // Order parameter checks\n getTrading().updateAndGetQuantityBeingTraded(makerAsset);\n ensureNotInOpenMakeOrder(makerAsset);\n\n approveAssetsMakeOrder(_targetExchange, order);\n\n IZeroExV3.OrderInfo memory orderInfo = IZeroExV3(_targetExchange).getOrderInfo(order);\n IZeroExV3(_targetExchange).preSign(orderInfo.orderHash);\n\n require(\n IZeroExV3(_targetExchange).isValidOrderSignature(order, _signature),\n \"INVALID_ORDER_SIGNATURE\"\n );\n\n updateStateMakeOrder(_targetExchange, order);\n }\n\n /// @notice Takes an active order on the selected exchange\n /// @dev These orders are expected to settle immediately\n /// @param _targetExchange Address of the exchange\n /// @param _orderAddresses [2] Order maker asset\n /// @param _orderAddresses [3] Order taker asset\n /// @param _orderValues [6] Fill amount: amount of taker token to be traded\n /// @param _signature _signature of the order.\n function takeOrder(\n address _targetExchange,\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData,\n bytes32 _identifier,\n bytes memory _signature\n )\n public\n override\n onlyManager\n notShutDown\n orderAddressesMatchOrderData(_orderAddresses, _orderValues, _orderData)\n {\n IZeroExV3.Order memory order = constructOrderStruct(_orderAddresses, _orderValues, _orderData);\n require(IZeroExV3(_targetExchange).isValidOrderSignature(order, _signature), \"Order _signature is invalid\");\n\n uint256 fillTakerQuantity = _orderValues[6];\n\n approveAssetsTakeOrder(_targetExchange, order);\n\n uint256 takerAssetFilledAmount = executeFill(_targetExchange, order, fillTakerQuantity, _signature);\n require(\n takerAssetFilledAmount == fillTakerQuantity,\n \"Filled amount does not match desired fill amount\"\n );\n\n updateStateTakeOrder(_targetExchange, order, fillTakerQuantity);\n }\n\n /// @notice Cancel the 0x make order\n /// @param _targetExchange Address of the exchange\n /// @param _orderAddresses [2] Order maker asset\n /// @param _identifier Order _identifier\n function cancelOrder(\n address _targetExchange,\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData,\n bytes32 _identifier,\n bytes memory _signature\n )\n public\n override\n orderAddressesMatchOrderData(_orderAddresses, _orderValues, _orderData)\n {\n IZeroExV3.Order memory order = getTrading().getZeroExV3OrderDetails(_identifier);\n ensureCancelPermitted(_targetExchange, getAssetAddress(order.makerAssetData));\n\n if (order.expirationTimeSeconds > block.timestamp) {\n IZeroExV3(_targetExchange).cancelOrder(order);\n }\n\n revokeApproveAssetsCancelOrder(_targetExchange, order);\n\n updateStateCancelOrder(_targetExchange, order);\n }\n\n /// @dev Get order details\n function getOrder(address _targetExchange, uint256 _id, address _makerAsset)\n public\n view\n override\n returns (address, address, uint256, uint256)\n {\n uint orderId;\n uint orderIndex;\n address takerAsset;\n uint makerQuantity;\n uint takerQuantity;\n (orderId, , orderIndex) = Trading(msg.sender).getOpenOrderInfo(_targetExchange, _makerAsset);\n (, takerAsset, makerQuantity, takerQuantity) = Trading(msg.sender).getOrderDetails(orderIndex);\n uint takerAssetFilledAmount = IZeroExV3(_targetExchange).filled(bytes32(orderId));\n uint makerAssetFilledAmount = mul(takerAssetFilledAmount, makerQuantity) / takerQuantity;\n if (IZeroExV3(_targetExchange).cancelled(bytes32(orderId)) || sub(takerQuantity, takerAssetFilledAmount) == 0) {\n return (_makerAsset, takerAsset, 0, 0);\n }\n return (\n _makerAsset,\n takerAsset,\n sub(makerQuantity, makerAssetFilledAmount),\n sub(takerQuantity, takerAssetFilledAmount)\n );\n }\n\n // INTERNAL METHODS\n\n /// @notice Approves makerAsset, makerFeeAsset\n function approveAssetsMakeOrder(address _targetExchange, IZeroExV3.Order memory _order)\n internal\n {\n withdrawAndApproveAsset(\n getAssetAddress(_order.makerAssetData),\n getAssetProxy(_targetExchange, _order.makerAssetData),\n _order.makerAssetAmount,\n \"makerAsset\"\n );\n if (_order.makerFee > 0) {\n withdrawAndApproveAsset(\n getAssetAddress(_order.makerFeeAssetData),\n getAssetProxy(_targetExchange, _order.makerFeeAssetData),\n _order.makerFee,\n \"makerFeeAsset\"\n );\n }\n }\n\n /// @notice Approves takerAsset, takerFeeAsset, protocolFee\n function approveAssetsTakeOrder(address _targetExchange, IZeroExV3.Order memory _order)\n internal\n {\n approveProtocolFeeAsset(_targetExchange);\n withdrawAndApproveAsset(\n getAssetAddress(_order.takerAssetData),\n getAssetProxy(_targetExchange, _order.takerAssetData),\n _order.takerAssetAmount,\n \"takerAsset\"\n );\n if (_order.takerFee > 0) {\n withdrawAndApproveAsset(\n getAssetAddress(_order.takerFeeAssetData),\n getAssetProxy(_targetExchange, _order.takerFeeAssetData),\n _order.takerFee,\n \"takerFeeAsset\"\n );\n }\n }\n\n function approveProtocolFeeAsset(address _targetExchange) internal {\n address protocolFeeCollector = IZeroExV3(_targetExchange).protocolFeeCollector();\n uint256 protocolFeeAmount = calcProtocolFeeAmount(_targetExchange);\n if (protocolFeeCollector == address(0) || protocolFeeAmount == 0) return;\n\n Hub hub = getHub();\n address nativeAsset = Accounting(hub.accounting()).NATIVE_ASSET();\n\n withdrawAndApproveAsset(nativeAsset, protocolFeeCollector, protocolFeeAmount, \"protocolFee\");\n }\n\n /// @dev Needed to avoid stack too deep error\n function executeFill(\n address _targetExchange,\n IZeroExV3.Order memory _order,\n uint256 _takerAssetFillAmount,\n bytes memory _signature\n )\n internal\n returns (uint256)\n {\n Hub hub = getHub();\n address makerAsset = getAssetAddress(_order.makerAssetData);\n uint preMakerAssetBalance = IERC20(makerAsset).balanceOf(address(this));\n\n IZeroExV3.FillResults memory fillResults = IZeroExV3(_targetExchange).fillOrder(\n _order,\n _takerAssetFillAmount,\n _signature\n );\n\n uint256 postMakerAssetBalance = IERC20(makerAsset).balanceOf(address(this));\n\n // Account for case where makerAsset, takerFee, protocolFee are the same\n uint256 makerAssetFeesTotal;\n if (\n makerAsset == Accounting(hub.accounting()).NATIVE_ASSET() &&\n IZeroExV3(_targetExchange).protocolFeeCollector() != address(0)\n )\n {\n makerAssetFeesTotal = calcProtocolFeeAmount(_targetExchange);\n }\n if (makerAsset == getAssetAddress(_order.takerFeeAssetData)) {\n makerAssetFeesTotal = add(makerAssetFeesTotal, _order.takerFee);\n }\n\n require(\n postMakerAssetBalance == sub(\n add(preMakerAssetBalance, fillResults.makerAssetFilledAmount),\n makerAssetFeesTotal\n ),\n \"Maker asset balance different than expected\"\n );\n\n return fillResults.takerAssetFilledAmount;\n }\n\n /// @notice Revoke asset approvals and return assets to vault\n function revokeApproveAssetsCancelOrder(\n address _targetExchange,\n IZeroExV3.Order memory _order\n )\n internal\n {\n address makerAsset = getAssetAddress(_order.makerAssetData);\n address makerFeeAsset = getAssetAddress(_order.makerFeeAssetData);\n\n revokeApproveAsset(\n makerAsset,\n getAssetProxy(_targetExchange, _order.makerAssetData),\n _order.makerAssetAmount,\n \"makerAsset\"\n );\n getTrading().returnAssetToVault(makerAsset);\n\n if (_order.makerFee > 0) {\n revokeApproveAsset(\n makerFeeAsset,\n getAssetProxy(_targetExchange, _order.makerFeeAssetData),\n _order.makerFee,\n \"makerFeeAsset\"\n );\n if (makerFeeAsset != makerAsset) getTrading().returnAssetToVault(makerFeeAsset);\n }\n }\n\n function updateStateCancelOrder(address _targetExchange, IZeroExV3.Order memory _order)\n internal\n {\n address makerAsset = getAssetAddress(_order.makerAssetData);\n\n getTrading().removeOpenMakeOrder(_targetExchange, makerAsset);\n getAccounting().updateOwnedAssets();\n getTrading().orderUpdateHook(\n _targetExchange,\n IZeroExV3(_targetExchange).getOrderInfo(_order).orderHash,\n Trading.UpdateType.cancel,\n [address(0), address(0)],\n [uint(0), uint(0), uint(0)]\n );\n }\n\n function updateStateMakeOrder(address _targetExchange, IZeroExV3.Order memory _order)\n internal\n {\n address makerAsset = getAssetAddress(_order.makerAssetData);\n address takerAsset = getAssetAddress(_order.takerAssetData);\n IZeroExV3.OrderInfo memory orderInfo = IZeroExV3(_targetExchange).getOrderInfo(_order);\n\n getAccounting().addAssetToOwnedAssets(takerAsset);\n getTrading().orderUpdateHook(\n _targetExchange,\n orderInfo.orderHash,\n Trading.UpdateType.make,\n [payable(makerAsset), payable(takerAsset)],\n [_order.makerAssetAmount, _order.takerAssetAmount, uint(0)]\n );\n getTrading().addOpenMakeOrder(\n _targetExchange,\n makerAsset,\n takerAsset,\n uint256(orderInfo.orderHash),\n _order.expirationTimeSeconds\n );\n getTrading().addZeroExV3OrderData(orderInfo.orderHash, _order);\n }\n\n /// @dev Avoids stack too deep error\n function updateStateTakeOrder(\n address _targetExchange,\n IZeroExV3.Order memory _order,\n uint256 _fillTakerQuantity\n )\n internal\n {\n address makerAsset = getAssetAddress(_order.makerAssetData);\n address takerAsset = getAssetAddress(_order.takerAssetData);\n\n getAccounting().addAssetToOwnedAssets(makerAsset);\n getAccounting().updateOwnedAssets();\n getTrading().returnAssetToVault(makerAsset);\n getTrading().orderUpdateHook(\n _targetExchange,\n IZeroExV3(_targetExchange).getOrderInfo(_order).orderHash,\n Trading.UpdateType.take,\n [payable(makerAsset), payable(takerAsset)],\n [_order.makerAssetAmount, _order.takerAssetAmount, _fillTakerQuantity]\n );\n }\n\n // VIEW METHODS\n function calcProtocolFeeAmount(address _targetExchange) internal view returns (uint256) {\n return mul(IZeroExV3(_targetExchange).protocolFeeMultiplier(), tx.gasprice);\n }\n\n function constructOrderStruct(\n address[8] memory _orderAddresses,\n uint[8] memory _orderValues,\n bytes[4] memory _orderData\n )\n internal\n view\n returns (IZeroExV3.Order memory order_)\n {\n order_ = IZeroExV3.Order({\n makerAddress: _orderAddresses[0],\n takerAddress: _orderAddresses[1],\n feeRecipientAddress: _orderAddresses[4],\n senderAddress: _orderAddresses[5],\n makerAssetAmount: _orderValues[0],\n takerAssetAmount: _orderValues[1],\n makerFee: _orderValues[2],\n takerFee: _orderValues[3],\n expirationTimeSeconds: _orderValues[4],\n salt: _orderValues[5],\n makerAssetData: _orderData[0],\n takerAssetData: _orderData[1],\n makerFeeAssetData: _orderData[2],\n takerFeeAssetData: _orderData[3]\n });\n }\n\n function getAssetProxy(address _targetExchange, bytes memory _assetData)\n internal\n view\n returns (address assetProxy_)\n {\n bytes4 assetProxyId;\n assembly {\n assetProxyId := and(mload(\n add(_assetData, 32)),\n 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000\n )\n }\n assetProxy_ = IZeroExV3(_targetExchange).getAssetProxy(assetProxyId);\n }\n\n function getAssetAddress(bytes memory _assetData)\n internal\n view\n returns (address assetAddress_)\n {\n assembly {\n assetAddress_ := mload(add(_assetData, 36))\n }\n }\n}\n"
},
"./src/factory/Factory.sol": {
"content": "pragma solidity 0.6.1;\n\n\ncontract Factory {\n mapping (address => bool) public childExists;\n\n event NewInstance(\n address indexed hub,\n address indexed instance\n );\n\n function isInstance(address _child) public view returns (bool) {\n return childExists[_child];\n }\n}\n"
},
"./src/factory/FundFactory.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../fund/accounting/IAccounting.sol\";\nimport \"../fund/fees/IFeeManager.sol\";\nimport \"../fund/hub/Hub.sol\";\nimport \"../fund/policies/IPolicyManager.sol\";\nimport \"../fund/participation/IParticipation.sol\";\nimport \"../fund/shares/IShares.sol\";\nimport \"../fund/trading/ITrading.sol\";\nimport \"../fund/vault/IVault.sol\";\nimport \"../version/IVersion.sol\";\nimport \"../engine/AmguConsumer.sol\";\nimport \"./Factory.sol\";\n\n/// @notice Creates fund routes and links them together\ncontract FundFactory is AmguConsumer, Factory {\n\n event NewFund(\n address indexed manager,\n address indexed hub,\n address[11] routes\n );\n\n IVersion public version;\n Registry public associatedRegistry;\n IAccountingFactory public accountingFactory;\n IFeeManagerFactory public feeManagerFactory;\n IParticipationFactory public participationFactory;\n IPolicyManagerFactory public policyManagerFactory;\n ISharesFactory public sharesFactory;\n ITradingFactory public tradingFactory;\n IVaultFactory public vaultFactory;\n\n address[] public funds;\n mapping (address => address) public managersToHubs;\n mapping (address => Hub.Routes) public managersToRoutes;\n mapping (address => Settings) public managersToSettings;\n\n /// @dev Parameters stored when beginning setup\n struct Settings {\n string name;\n address[] exchanges;\n address[] adapters;\n address denominationAsset;\n address[] defaultInvestmentAssets;\n address[] fees;\n uint[] feeRates;\n uint[] feePeriods;\n }\n\n constructor(\n address _accountingFactory,\n address _feeManagerFactory,\n address _participationFactory,\n address _sharesFactory,\n address _tradingFactory,\n address _vaultFactory,\n address _policyManagerFactory,\n address _version\n )\n public\n {\n accountingFactory = IAccountingFactory(_accountingFactory);\n feeManagerFactory = IFeeManagerFactory(_feeManagerFactory);\n participationFactory = IParticipationFactory(_participationFactory);\n sharesFactory = ISharesFactory(_sharesFactory);\n tradingFactory = ITradingFactory(_tradingFactory);\n vaultFactory = IVaultFactory(_vaultFactory);\n policyManagerFactory = IPolicyManagerFactory(_policyManagerFactory);\n version = IVersion(_version);\n }\n\n function componentExists(address _component) internal pure returns (bool) {\n return _component != address(0);\n }\n\n function ensureComponentNotSet(address _component) internal {\n require(\n !componentExists(_component),\n \"This step has already been run\"\n );\n }\n\n function ensureComponentSet(address _component) internal {\n require(\n componentExists(_component),\n \"Component preprequisites not met\"\n );\n }\n\n function beginSetup(\n string memory _name,\n address[] memory _fees,\n uint[] memory _feeRates,\n uint[] memory _feePeriods,\n address[] memory _exchanges,\n address[] memory _adapters,\n address _denominationAsset,\n address[] memory _defaultInvestmentAssets\n )\n public\n {\n ensureComponentNotSet(managersToHubs[msg.sender]);\n associatedRegistry.reserveFundName(\n msg.sender,\n _name\n );\n require(\n associatedRegistry.assetIsRegistered(_denominationAsset),\n \"Denomination asset must be registered\"\n );\n\n managersToHubs[msg.sender] = address(new Hub(msg.sender, _name));\n managersToSettings[msg.sender] = Settings(\n _name,\n _exchanges,\n _adapters,\n _denominationAsset,\n _defaultInvestmentAssets,\n _fees,\n _feeRates,\n _feePeriods\n );\n managersToRoutes[msg.sender].registry = address(associatedRegistry);\n managersToRoutes[msg.sender].version = address(version);\n managersToRoutes[msg.sender].engine = engine();\n managersToRoutes[msg.sender].mlnToken = mlnToken();\n }\n\n function _createAccountingFor(address _manager)\n internal\n {\n ensureComponentSet(managersToHubs[_manager]);\n ensureComponentNotSet(managersToRoutes[_manager].accounting);\n managersToRoutes[_manager].accounting = accountingFactory.createInstance(\n managersToHubs[_manager],\n managersToSettings[_manager].denominationAsset,\n associatedRegistry.nativeAsset()\n );\n }\n\n function createAccountingFor(address _manager) external amguPayable(false) payable { _createAccountingFor(_manager); }\n function createAccounting() external amguPayable(false) payable { _createAccountingFor(msg.sender); }\n\n function _createFeeManagerFor(address _manager)\n internal\n {\n ensureComponentSet(managersToHubs[_manager]);\n ensureComponentNotSet(managersToRoutes[_manager].feeManager);\n managersToRoutes[_manager].feeManager = feeManagerFactory.createInstance(\n managersToHubs[_manager],\n managersToSettings[_manager].denominationAsset,\n managersToSettings[_manager].fees,\n managersToSettings[_manager].feeRates,\n managersToSettings[_manager].feePeriods,\n managersToRoutes[_manager].registry\n );\n }\n\n function createFeeManagerFor(address _manager) external amguPayable(false) payable { _createFeeManagerFor(_manager); }\n function createFeeManager() external amguPayable(false) payable { _createFeeManagerFor(msg.sender); }\n\n function _createParticipationFor(address _manager)\n internal\n {\n ensureComponentSet(managersToHubs[_manager]);\n ensureComponentNotSet(managersToRoutes[_manager].participation);\n managersToRoutes[_manager].participation = participationFactory.createInstance(\n managersToHubs[_manager],\n managersToSettings[_manager].defaultInvestmentAssets,\n managersToRoutes[_manager].registry\n );\n }\n\n function createParticipationFor(address _manager) external amguPayable(false) payable { _createParticipationFor(_manager); }\n function createParticipation() external amguPayable(false) payable { _createParticipationFor(msg.sender); }\n\n function _createPolicyManagerFor(address _manager)\n internal\n {\n ensureComponentSet(managersToHubs[_manager]);\n ensureComponentNotSet(managersToRoutes[_manager].policyManager);\n managersToRoutes[_manager].policyManager = policyManagerFactory.createInstance(\n managersToHubs[_manager]\n );\n }\n\n function createPolicyManagerFor(address _manager) external amguPayable(false) payable { _createPolicyManagerFor(_manager); }\n function createPolicyManager() external amguPayable(false) payable { _createPolicyManagerFor(msg.sender); }\n\n function _createSharesFor(address _manager)\n internal\n {\n ensureComponentSet(managersToHubs[_manager]);\n ensureComponentNotSet(managersToRoutes[_manager].shares);\n managersToRoutes[_manager].shares = sharesFactory.createInstance(\n managersToHubs[_manager]\n );\n }\n\n function createSharesFor(address _manager) external amguPayable(false) payable { _createSharesFor(_manager); }\n function createShares() external amguPayable(false) payable { _createSharesFor(msg.sender); }\n\n function _createTradingFor(address _manager)\n internal\n {\n ensureComponentSet(managersToHubs[_manager]);\n ensureComponentNotSet(managersToRoutes[_manager].trading);\n managersToRoutes[_manager].trading = tradingFactory.createInstance(\n managersToHubs[_manager],\n managersToSettings[_manager].exchanges,\n managersToSettings[_manager].adapters,\n managersToRoutes[_manager].registry\n );\n }\n\n function createTradingFor(address _manager) external amguPayable(false) payable { _createTradingFor(_manager); }\n function createTrading() external amguPayable(false) payable { _createTradingFor(msg.sender); }\n\n function _createVaultFor(address _manager)\n internal\n {\n ensureComponentSet(managersToHubs[_manager]);\n ensureComponentNotSet(managersToRoutes[_manager].vault);\n managersToRoutes[_manager].vault = vaultFactory.createInstance(\n managersToHubs[_manager]\n );\n }\n\n function createVaultFor(address _manager) external amguPayable(false) payable { _createVaultFor(_manager); }\n function createVault() external amguPayable(false) payable { _createVaultFor(msg.sender); }\n\n function _completeSetupFor(address _manager) internal {\n Hub.Routes memory routes = managersToRoutes[_manager];\n Hub hub = Hub(managersToHubs[_manager]);\n require(!childExists[address(hub)], \"Setup already complete\");\n require(\n componentExists(address(hub)) &&\n componentExists(routes.accounting) &&\n componentExists(routes.feeManager) &&\n componentExists(routes.participation) &&\n componentExists(routes.policyManager) &&\n componentExists(routes.shares) &&\n componentExists(routes.trading) &&\n componentExists(routes.vault),\n \"Components must be set before completing setup\"\n );\n childExists[address(hub)] = true;\n hub.setSpokes([\n routes.accounting,\n routes.feeManager,\n routes.participation,\n routes.policyManager,\n routes.shares,\n routes.trading,\n routes.vault,\n routes.registry,\n routes.version,\n routes.engine,\n routes.mlnToken\n ]);\n hub.setRouting();\n hub.setPermissions();\n funds.push(address(hub));\n associatedRegistry.registerFund(\n address(hub),\n _manager,\n managersToSettings[_manager].name\n );\n\n emit NewFund(\n msg.sender,\n address(hub),\n [\n routes.accounting,\n routes.feeManager,\n routes.participation,\n routes.policyManager,\n routes.shares,\n routes.trading,\n routes.vault,\n routes.registry,\n routes.version,\n routes.engine,\n routes.mlnToken\n ]\n );\n }\n\n function completeSetupFor(address _manager) external amguPayable(false) payable { _completeSetupFor(_manager); }\n function completeSetup() external amguPayable(false) payable { _completeSetupFor(msg.sender); }\n\n function getFundById(uint withId) external view returns (address) { return funds[withId]; }\n function getLastFundId() external view returns (uint) { return funds.length - 1; }\n\n function mlnToken() public view override returns (address) {\n return address(associatedRegistry.mlnToken());\n }\n function engine() public view override returns (address) {\n return address(associatedRegistry.engine());\n }\n function priceSource() public view override returns (address) {\n return address(associatedRegistry.priceSource());\n }\n function registry() public view override returns (address) { return address(associatedRegistry); }\n function getExchangesInfo(address user) public view returns (address[] memory) {\n return (managersToSettings[user].exchanges);\n }\n}\n"
},
"./src/fund/accounting/Accounting.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../../dependencies/token/StandardToken.sol\";\nimport \"../../factory/Factory.sol\";\nimport \"../../prices/IPriceSource.sol\";\nimport \"../fees/FeeManager.sol\";\nimport \"../hub/Spoke.sol\";\nimport \"../shares/Shares.sol\";\nimport \"../trading/ITrading.sol\";\nimport \"../vault/Vault.sol\";\nimport \"../../engine/AmguConsumer.sol\";\n\ncontract Accounting is AmguConsumer, Spoke {\n\n event AssetAddition(address indexed asset);\n event AssetRemoval(address indexed asset);\n\n struct Calculations {\n uint gav;\n uint nav;\n uint allocatedFees;\n uint totalSupply;\n uint timestamp;\n }\n\n uint constant public MAX_OWNED_ASSETS = 20;\n address[] public ownedAssets;\n mapping (address => bool) public isInAssetList;\n uint public constant SHARES_DECIMALS = 18;\n address public NATIVE_ASSET;\n address public DENOMINATION_ASSET;\n uint public DENOMINATION_ASSET_DECIMALS;\n uint public DEFAULT_SHARE_PRICE;\n Calculations public atLastAllocation;\n\n constructor(address _hub, address _denominationAsset, address _nativeAsset)\n public\n Spoke(_hub)\n {\n DENOMINATION_ASSET = _denominationAsset;\n NATIVE_ASSET = _nativeAsset;\n DENOMINATION_ASSET_DECIMALS = ERC20WithFields(DENOMINATION_ASSET).decimals();\n DEFAULT_SHARE_PRICE = 10 ** uint(DENOMINATION_ASSET_DECIMALS);\n }\n\n function getOwnedAssetsLength() external view returns (uint) {\n return ownedAssets.length;\n }\n\n function assetHoldings(address _asset) public returns (uint256) {\n return add(\n uint256(ERC20WithFields(_asset).balanceOf(routes.vault)),\n ITrading(routes.trading).updateAndGetQuantityBeingTraded(_asset)\n );\n }\n\n /// @dev Returns sparse array\n function getFundHoldings() external returns (uint[] memory, address[] memory) {\n uint[] memory _quantities = new uint[](ownedAssets.length);\n address[] memory _assets = new address[](ownedAssets.length);\n for (uint i = 0; i < ownedAssets.length; i++) {\n address ofAsset = ownedAssets[i];\n // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimal)\n uint quantityHeld = assetHoldings(ofAsset);\n _assets[i] = ofAsset;\n _quantities[i] = quantityHeld;\n }\n return (_quantities, _assets);\n }\n\n function calcAssetGAV(address _queryAsset) external returns (uint) {\n uint queryAssetQuantityHeld = assetHoldings(_queryAsset);\n return IPriceSource(priceSource()).convertQuantity(\n queryAssetQuantityHeld, _queryAsset, DENOMINATION_ASSET\n );\n }\n\n // prices are quoted in DENOMINATION_ASSET so they use denominationDecimals\n function calcGav() public returns (uint gav) {\n for (uint i = 0; i < ownedAssets.length; ++i) {\n address asset = ownedAssets[i];\n // assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimals)\n uint quantityHeld = assetHoldings(asset);\n // Dont bother with the calculations if the balance of the asset is 0\n if (quantityHeld == 0) {\n continue;\n }\n // gav as sum of mul(assetHoldings, assetPrice) with formatting: mul(mul(exchangeHoldings, exchangePrice), 10 ** shareDecimals)\n gav = add(\n gav,\n IPriceSource(priceSource()).convertQuantity(\n quantityHeld, asset, DENOMINATION_ASSET\n )\n );\n }\n return gav;\n }\n\n function calcNav(uint gav, uint unclaimedFeesInDenominationAsset) public pure returns (uint) {\n return sub(gav, unclaimedFeesInDenominationAsset);\n }\n\n function valuePerShare(uint totalValue, uint numShares) public pure returns (uint) {\n require(numShares > 0, \"No shares to calculate value for\");\n return (totalValue * 10 ** uint(SHARES_DECIMALS)) / numShares;\n }\n\n function performCalculations()\n public\n returns (\n uint gav,\n uint feesInDenominationAsset, // unclaimed amount\n uint feesInShares, // unclaimed amount\n uint nav,\n uint sharePrice,\n uint gavPerShareNetManagementFee\n )\n {\n gav = calcGav();\n uint totalSupply = Shares(routes.shares).totalSupply();\n feesInShares = FeeManager(routes.feeManager).totalFeeAmount();\n feesInDenominationAsset = (totalSupply == 0) ?\n 0 :\n mul(feesInShares, gav) / add(totalSupply, feesInShares);\n nav = calcNav(gav, feesInDenominationAsset);\n\n // The total share supply including the value of feesInDenominationAsset, measured in shares of this fund\n uint totalSupplyAccountingForFees = add(totalSupply, feesInShares);\n sharePrice = (totalSupply > 0) ?\n valuePerShare(gav, totalSupplyAccountingForFees) :\n DEFAULT_SHARE_PRICE;\n gavPerShareNetManagementFee = (totalSupply > 0) ?\n valuePerShare(gav, add(totalSupply, FeeManager(routes.feeManager).managementFeeAmount())) :\n DEFAULT_SHARE_PRICE;\n return (gav, feesInDenominationAsset, feesInShares, nav, sharePrice, gavPerShareNetManagementFee);\n }\n\n function calcSharePrice() external returns (uint sharePrice) {\n (,,,,sharePrice,) = performCalculations();\n return sharePrice;\n }\n\n function calcGavPerShareNetManagementFee()\n public\n returns (uint gavPerShareNetManagementFee)\n {\n (,,,,,gavPerShareNetManagementFee) = performCalculations();\n return gavPerShareNetManagementFee;\n }\n\n function getShareCostInAsset(uint _numShares, address _altAsset)\n external\n returns (uint)\n {\n uint denominationAssetQuantity = mul(\n _numShares,\n calcGavPerShareNetManagementFee()\n ) / 10 ** uint(SHARES_DECIMALS);\n return IPriceSource(priceSource()).convertQuantity(\n denominationAssetQuantity, DENOMINATION_ASSET, _altAsset\n );\n }\n\n /// @notice Reward all fees and perform some updates\n /// @dev Anyone can call this\n function triggerRewardAllFees()\n external\n amguPayable(false)\n payable\n {\n updateOwnedAssets();\n uint256 gav;\n uint256 feesInDenomination;\n uint256 feesInShares;\n uint256 nav;\n (gav, feesInDenomination, feesInShares, nav,,) = performCalculations();\n uint256 totalSupply = Shares(routes.shares).totalSupply();\n FeeManager(routes.feeManager).rewardAllFees();\n atLastAllocation = Calculations({\n gav: gav,\n nav: nav,\n allocatedFees: feesInDenomination,\n totalSupply: totalSupply,\n timestamp: block.timestamp\n });\n }\n\n /// @dev Check holdings for all assets, and adjust list\n function updateOwnedAssets() public {\n for (uint i = 0; i < ownedAssets.length; i++) {\n address asset = ownedAssets[i];\n if (\n assetHoldings(asset) == 0 &&\n !(asset == address(DENOMINATION_ASSET)) &&\n ITrading(routes.trading).getOpenMakeOrdersAgainstAsset(asset) == 0\n ) {\n _removeFromOwnedAssets(asset);\n }\n }\n }\n\n function addAssetToOwnedAssets(address _asset) external auth {\n _addAssetToOwnedAssets(_asset);\n }\n\n function removeFromOwnedAssets(address _asset) external auth {\n _removeFromOwnedAssets(_asset);\n }\n\n /// @dev Just pass if asset already in list\n function _addAssetToOwnedAssets(address _asset) internal {\n if (isInAssetList[_asset]) { return; }\n\n require(\n ownedAssets.length < MAX_OWNED_ASSETS,\n \"Max owned asset limit reached\"\n );\n isInAssetList[_asset] = true;\n ownedAssets.push(_asset);\n emit AssetAddition(_asset);\n }\n\n /// @dev Just pass if asset not in list\n function _removeFromOwnedAssets(address _asset) internal {\n if (!isInAssetList[_asset]) { return; }\n\n isInAssetList[_asset] = false;\n for (uint i; i < ownedAssets.length; i++) {\n if (ownedAssets[i] == _asset) {\n ownedAssets[i] = ownedAssets[ownedAssets.length - 1];\n ownedAssets.pop();\n break;\n }\n }\n emit AssetRemoval(_asset);\n }\n\n function engine() public view override(AmguConsumer, Spoke) returns (address) { return Spoke.engine(); }\n function mlnToken() public view override(AmguConsumer, Spoke) returns (address) { return Spoke.mlnToken(); }\n function priceSource() public view override(AmguConsumer, Spoke) returns (address) { return Spoke.priceSource(); }\n function registry() public view override(AmguConsumer, Spoke) returns (address) { return Spoke.registry(); }\n}\n\ncontract AccountingFactory is Factory {\n event NewInstance(\n address indexed hub,\n address indexed instance,\n address denominationAsset,\n address nativeAsset\n );\n\n function createInstance(address _hub, address _denominationAsset, address _nativeAsset) external returns (address) {\n address accounting = address(new Accounting(_hub, _denominationAsset, _nativeAsset));\n childExists[accounting] = true;\n emit NewInstance(_hub, accounting, _denominationAsset, _nativeAsset);\n return accounting;\n }\n}\n\n"
},
"./src/fund/accounting/IAccounting.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @notice Gives metrics about a Fund\ninterface IAccounting {\n function getOwnedAssetsLength() external view returns (uint);\n function getFundHoldings() external returns (uint[] memory, address[] memory);\n function calcAssetGAV(address ofAsset) external returns (uint);\n function calcGav() external returns (uint gav);\n function calcNav(uint gav, uint unclaimedFees) external pure returns (uint);\n function valuePerShare(uint totalValue, uint numShares) external view returns (uint);\n function performCalculations() external returns (\n uint gav,\n uint unclaimedFees,\n uint feesInShares,\n uint nav,\n uint sharePrice,\n uint gavPerShareNetManagementFee\n );\n function calcSharePrice() external returns (uint);\n function calcGavPerShareNetManagementFee() external returns (uint);\n}\n\ninterface IAccountingFactory {\n function createInstance(address _hub, address _denominationAsset, address _nativeAsset) external returns (address);\n}\n"
},
"./src/fund/fees/FeeManager.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"./IFee.sol\";\nimport \"../hub/Spoke.sol\";\nimport \"../shares/Shares.sol\";\nimport \"../../factory/Factory.sol\";\nimport \"../../version/Registry.sol\";\nimport \"../../dependencies/DSMath.sol\";\nimport \"./IFeeManager.sol\";\n\n/// @notice Manages and allocates fees for a particular fund\ncontract FeeManager is DSMath, Spoke {\n\n event FeeReward(uint shareQuantity);\n event FeeRegistration(address fee);\n\n struct FeeInfo {\n address feeAddress;\n uint feeRate;\n uint feePeriod;\n }\n\n IFee[] public fees;\n mapping (address => bool) public feeIsRegistered;\n\n constructor(address _hub, address _denominationAsset, address[] memory _fees, uint[] memory _rates, uint[] memory _periods, address _registry) Spoke(_hub) public {\n for (uint i = 0; i < _fees.length; i++) {\n require(\n Registry(_registry).isFeeRegistered(_fees[i]),\n \"Fee must be known to Registry\"\n );\n register(_fees[i], _rates[i], _periods[i], _denominationAsset);\n }\n if (fees.length > 0) {\n require(\n fees[0].identifier() == 0,\n \"Management fee must be at 0 index\"\n );\n }\n if (fees.length > 1) {\n require(\n fees[1].identifier() == 1,\n \"Performance fee must be at 1 index\"\n );\n }\n }\n\n function register(address feeAddress, uint feeRate, uint feePeriod, address denominationAsset) internal {\n require(!feeIsRegistered[feeAddress], \"Fee already registered\");\n feeIsRegistered[feeAddress] = true;\n fees.push(IFee(feeAddress));\n IFee(feeAddress).initializeForUser(feeRate, feePeriod, denominationAsset); // initialize state\n emit FeeRegistration(feeAddress);\n }\n\n function totalFeeAmount() external returns (uint total) {\n for (uint i = 0; i < fees.length; i++) {\n total = add(total, fees[i].feeAmount());\n }\n return total;\n }\n\n /// @dev Shares to be inflated after update state\n function _rewardFee(IFee fee) internal {\n require(feeIsRegistered[address(fee)], \"Fee is not registered\");\n uint rewardShares = fee.feeAmount();\n fee.updateState();\n Shares(routes.shares).createFor(hub.manager(), rewardShares);\n emit FeeReward(rewardShares);\n }\n\n function _rewardAllFees() internal {\n for (uint i = 0; i < fees.length; i++) {\n _rewardFee(fees[i]);\n }\n }\n\n /// @dev Used when calling from other components\n function rewardAllFees() public auth { _rewardAllFees(); }\n\n /// @dev Convenience function; anyone can reward management fee any time\n /// @dev Convention that management fee is 0\n function rewardManagementFee() public {\n if (fees.length >= 1) _rewardFee(fees[0]);\n }\n\n /// @dev Convenience function\n /// @dev Convention that management fee is 0\n function managementFeeAmount() external returns (uint) {\n if (fees.length < 1) return 0;\n return fees[0].feeAmount();\n }\n\n /// @dev Convenience function\n /// @dev Convention that performace fee is 1\n function performanceFeeAmount() external returns (uint) {\n if (fees.length < 2) return 0;\n return fees[1].feeAmount();\n }\n}\n\ncontract FeeManagerFactory is Factory {\n function createInstance(\n address _hub,\n address _denominationAsset,\n address[] memory _fees,\n uint[] memory _feeRates,\n uint[] memory _feePeriods,\n address _registry\n ) public returns (address) {\n address feeManager = address(\n new FeeManager(_hub, _denominationAsset, _fees, _feeRates, _feePeriods, _registry)\n );\n childExists[feeManager] = true;\n emit NewInstance(_hub, feeManager);\n return feeManager;\n }\n}\n"
},
"./src/fund/fees/IFee.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @dev Exposes \"feeAmount\", which maps fund state and fee state to uint\n/// @dev Notice that \"feeAmount\" *may* change contract state\n/// @dev Also exposes \"updateState\", which changes fee's internal state\ninterface IFee {\n function initializeForUser(uint feeRate, uint feePeriod, address denominationAsset) external;\n function feeAmount() external returns (uint);\n function updateState() external;\n\n /// @notice Used to enforce a convention\n function identifier() external view returns (uint);\n}\n\n"
},
"./src/fund/fees/IFeeManager.sol": {
"content": "pragma solidity 0.6.1;\n\ninterface IFeeManagerFactory {\n function createInstance(\n address _hub,\n address _denominationAsset,\n address[] calldata _fees,\n uint[] calldata _feeRates,\n uint[] calldata _feePeriods,\n address _registry\n ) external returns (address);\n}\n"
},
"./src/fund/fees/ManagementFee.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"./FeeManager.sol\";\nimport \"../hub/Hub.sol\";\nimport \"../shares/Shares.sol\";\nimport \"../../dependencies/DSMath.sol\";\n\ncontract ManagementFee is DSMath {\n\n uint public DIVISOR = 10 ** 18;\n\n mapping (address => uint) public managementFeeRate;\n mapping (address => uint) public lastPayoutTime;\n\n function feeAmount() external view returns (uint feeInShares) {\n Hub hub = FeeManager(msg.sender).hub();\n Shares shares = Shares(hub.shares());\n if (shares.totalSupply() == 0 || managementFeeRate[msg.sender] == 0) {\n feeInShares = 0;\n } else {\n uint timePassed = sub(block.timestamp, lastPayoutTime[msg.sender]);\n uint preDilutionFeeShares = mul(mul(shares.totalSupply(), managementFeeRate[msg.sender]) / DIVISOR, timePassed) / 365 days;\n feeInShares =\n mul(preDilutionFeeShares, shares.totalSupply()) /\n sub(shares.totalSupply(), preDilutionFeeShares);\n }\n return feeInShares;\n }\n\n function initializeForUser(uint feeRate, uint feePeriod, address denominationAsset) external {\n require(lastPayoutTime[msg.sender] == 0);\n managementFeeRate[msg.sender] = feeRate;\n lastPayoutTime[msg.sender] = block.timestamp;\n }\n\n function updateState() external {\n lastPayoutTime[msg.sender] = block.timestamp;\n }\n\n function identifier() external pure returns (uint) {\n return 0;\n }\n}\n\n"
},
"./src/fund/fees/PerformanceFee.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"./FeeManager.sol\";\nimport \"../accounting/Accounting.sol\";\nimport \"../hub/Hub.sol\";\nimport \"../shares/Shares.sol\";\nimport \"../../dependencies/DSMath.sol\";\n\ncontract PerformanceFee is DSMath {\n\n event HighWaterMarkUpdate(address indexed feeManager, uint indexed hwm);\n\n uint public constant DIVISOR = 10 ** 18;\n uint public constant REDEEM_WINDOW = 1 weeks;\n\n mapping(address => uint) public highWaterMark;\n mapping(address => uint) public lastPayoutTime;\n mapping(address => uint) public initializeTime;\n mapping(address => uint) public performanceFeeRate;\n mapping(address => uint) public performanceFeePeriod;\n\n /// @notice Sets initial state of the fee for a user\n function initializeForUser(uint feeRate, uint feePeriod, address denominationAsset) external {\n require(lastPayoutTime[msg.sender] == 0, \"Already initialized\");\n performanceFeeRate[msg.sender] = feeRate;\n performanceFeePeriod[msg.sender] = feePeriod;\n highWaterMark[msg.sender] = 10 ** uint(ERC20WithFields(denominationAsset).decimals());\n lastPayoutTime[msg.sender] = block.timestamp;\n initializeTime[msg.sender] = block.timestamp;\n }\n\n /// @notice Assumes management fee is zero\n function feeAmount() external returns (uint feeInShares) {\n Hub hub = FeeManager(msg.sender).hub();\n Accounting accounting = Accounting(hub.accounting());\n Shares shares = Shares(hub.shares());\n uint gav = accounting.calcGav();\n uint gavPerShare = shares.totalSupply() > 0 ?\n accounting.valuePerShare(gav, shares.totalSupply())\n : accounting.DEFAULT_SHARE_PRICE();\n if (\n gavPerShare > highWaterMark[msg.sender] &&\n shares.totalSupply() != 0 &&\n gav != 0\n ) {\n uint sharePriceGain = sub(gavPerShare, highWaterMark[msg.sender]);\n uint totalGain = mul(sharePriceGain, shares.totalSupply()) / DIVISOR;\n uint feeInAsset = mul(totalGain, performanceFeeRate[msg.sender]) / DIVISOR;\n uint preDilutionFee = mul(shares.totalSupply(), feeInAsset) / gav;\n feeInShares =\n mul(preDilutionFee, shares.totalSupply()) /\n sub(shares.totalSupply(), preDilutionFee);\n }\n else {\n feeInShares = 0;\n }\n return feeInShares;\n }\n\n function canUpdate(address _who) public view returns (bool) {\n uint timeSinceInit = sub(\n block.timestamp,\n initializeTime[_who]\n );\n uint secondsSinceLastPeriod = timeSinceInit % performanceFeePeriod[_who];\n uint lastPeriodEnd = sub(block.timestamp, secondsSinceLastPeriod);\n return (\n secondsSinceLastPeriod <= REDEEM_WINDOW &&\n lastPayoutTime[_who] < lastPeriodEnd\n );\n }\n\n /// @notice Assumes management fee is zero\n function updateState() external {\n require(lastPayoutTime[msg.sender] != 0, \"Not initialized\");\n require(\n canUpdate(msg.sender),\n \"Not within a update window or already updated this period\"\n );\n Hub hub = FeeManager(msg.sender).hub();\n Accounting accounting = Accounting(hub.accounting());\n Shares shares = Shares(hub.shares());\n uint gav = accounting.calcGav();\n uint currentGavPerShare = accounting.valuePerShare(gav, shares.totalSupply());\n require(\n currentGavPerShare > highWaterMark[msg.sender],\n \"Current share price does not pass high water mark\"\n );\n lastPayoutTime[msg.sender] = block.timestamp;\n highWaterMark[msg.sender] = currentGavPerShare;\n emit HighWaterMarkUpdate(msg.sender, currentGavPerShare);\n }\n\n function identifier() external pure returns (uint) {\n return 1;\n }\n}\n"
},
"./src/fund/hub/Hub.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../../dependencies/DSGuard.sol\";\nimport \"./Spoke.sol\";\nimport \"../../version/Registry.sol\";\n\n/// @notice Router for communication between components\n/// @notice Has one or more Spokes\ncontract Hub is DSGuard {\n\n event FundShutDown();\n\n struct Routes {\n address accounting;\n address feeManager;\n address participation;\n address policyManager;\n address shares;\n address trading;\n address vault;\n address registry;\n address version;\n address engine;\n address mlnToken;\n }\n\n Routes public routes;\n address public manager;\n address public creator;\n string public name;\n bool public isShutDown;\n bool public spokesSet;\n bool public routingSet;\n bool public permissionsSet;\n uint public creationTime;\n mapping (address => bool) public isSpoke;\n\n constructor(address _manager, string memory _name) public {\n creator = msg.sender;\n manager = _manager;\n name = _name;\n creationTime = block.timestamp;\n }\n\n modifier onlyCreator() {\n require(msg.sender == creator, \"Only creator can do this\");\n _;\n }\n\n function shutDownFund() external {\n require(msg.sender == routes.version);\n isShutDown = true;\n emit FundShutDown();\n }\n\n function setSpokes(address[11] calldata _spokes) external onlyCreator {\n require(!spokesSet, \"Spokes already set\");\n for (uint i = 0; i < _spokes.length; i++) {\n isSpoke[_spokes[i]] = true;\n }\n routes.accounting = _spokes[0];\n routes.feeManager = _spokes[1];\n routes.participation = _spokes[2];\n routes.policyManager = _spokes[3];\n routes.shares = _spokes[4];\n routes.trading = _spokes[5];\n routes.vault = _spokes[6];\n routes.registry = _spokes[7];\n routes.version = _spokes[8];\n routes.engine = _spokes[9];\n routes.mlnToken = _spokes[10];\n spokesSet = true;\n }\n\n function setRouting() external onlyCreator {\n require(spokesSet, \"Spokes must be set\");\n require(!routingSet, \"Routing already set\");\n address[11] memory spokes = [\n routes.accounting, routes.feeManager, routes.participation,\n routes.policyManager, routes.shares, routes.trading,\n routes.vault, routes.registry,\n routes.version, routes.engine, routes.mlnToken\n ];\n Spoke(routes.accounting).initialize(spokes);\n Spoke(routes.feeManager).initialize(spokes);\n Spoke(routes.participation).initialize(spokes);\n Spoke(routes.policyManager).initialize(spokes);\n Spoke(routes.shares).initialize(spokes);\n Spoke(routes.trading).initialize(spokes);\n Spoke(routes.vault).initialize(spokes);\n routingSet = true;\n }\n\n function setPermissions() external onlyCreator {\n require(spokesSet, \"Spokes must be set\");\n require(routingSet, \"Routing must be set\");\n require(!permissionsSet, \"Permissioning already set\");\n permit(routes.participation, routes.vault, bytes4(keccak256('withdraw(address,uint256)')));\n permit(routes.trading, routes.vault, bytes4(keccak256('withdraw(address,uint256)')));\n permit(routes.participation, routes.shares, bytes4(keccak256('createFor(address,uint256)')));\n permit(routes.participation, routes.shares, bytes4(keccak256('destroyFor(address,uint256)')));\n permit(routes.feeManager, routes.shares, bytes4(keccak256('createFor(address,uint256)')));\n permit(routes.participation, routes.accounting, bytes4(keccak256('addAssetToOwnedAssets(address)')));\n permit(routes.trading, routes.accounting, bytes4(keccak256('addAssetToOwnedAssets(address)')));\n permit(routes.trading, routes.accounting, bytes4(keccak256('removeFromOwnedAssets(address)')));\n permit(routes.accounting, routes.feeManager, bytes4(keccak256('rewardAllFees()')));\n permit(manager, routes.policyManager, bytes4(keccak256('register(bytes4,address)')));\n permit(manager, routes.policyManager, bytes4(keccak256('batchRegister(bytes4[],address[])')));\n permit(manager, routes.participation, bytes4(keccak256('enableInvestment(address[])')));\n permit(manager, routes.participation, bytes4(keccak256('disableInvestment(address[])')));\n permit(manager, routes.trading, bytes4(keccak256('addExchange(address,address)')));\n permissionsSet = true;\n }\n\n function vault() external view returns (address) { return routes.vault; }\n function accounting() external view returns (address) { return routes.accounting; }\n function priceSource() external view returns (address) { return Registry(routes.registry).priceSource(); }\n function participation() external view returns (address) { return routes.participation; }\n function trading() external view returns (address) { return routes.trading; }\n function shares() external view returns (address) { return routes.shares; }\n function registry() external view returns (address) { return routes.registry; }\n function version() external view returns (address) { return routes.version; }\n function policyManager() external view returns (address) { return routes.policyManager; }\n}\n\n"
},
"./src/fund/hub/Spoke.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"./Hub.sol\";\nimport \"../../dependencies/DSAuth.sol\";\n\n/// @notice Has one Hub\ncontract Spoke is DSAuth {\n Hub public hub;\n Hub.Routes public routes;\n bool public initialized;\n\n modifier onlyInitialized() {\n require(initialized, \"Component not yet initialized\");\n _;\n }\n\n modifier notShutDown() {\n require(!hub.isShutDown(), \"Hub is shut down\");\n _;\n }\n\n constructor(address _hub) public {\n hub = Hub(_hub);\n setAuthority(hub);\n setOwner(address(hub)); // temporary, to allow initialization\n }\n\n function initialize(address[11] calldata _spokes) external auth {\n require(msg.sender == address(hub));\n require(!initialized, \"Already initialized\");\n routes = Hub.Routes(\n _spokes[0],\n _spokes[1],\n _spokes[2],\n _spokes[3],\n _spokes[4],\n _spokes[5],\n _spokes[6],\n _spokes[7],\n _spokes[8],\n _spokes[9],\n _spokes[10]\n );\n initialized = true;\n setOwner(address(0));\n }\n\n function engine() public view virtual returns (address) { return routes.engine; }\n function mlnToken() public view virtual returns (address) { return routes.mlnToken; }\n function priceSource() public view virtual returns (address) { return hub.priceSource(); }\n function version() public view virtual returns (address) { return routes.version; }\n function registry() public view virtual returns (address) { return routes.registry; }\n}\n\n"
},
"./src/fund/participation/IParticipation.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @notice Investor Fund interactions\n/// @notice Handles redemptions and requests for investment\ninterface IParticipation {\n function requestInvestment(\n uint requestedShares,\n uint investmentAmount,\n address investmentAsset\n ) external payable;\n function hasRequest(address) external view returns (bool);\n function cancelRequest() external payable;\n function executeRequestFor(address requestOwner) external payable;\n function redeem() external;\n function redeemWithConstraints(uint shareQuantity, address[] calldata requestedAssets) external;\n}\n\ninterface IParticipationFactory {\n function createInstance(address _hub, address[] calldata _defaultAssets, address _registry) external returns (address);\n}\n"
},
"./src/fund/participation/Participation.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../vault/Vault.sol\";\nimport \"../shares/Shares.sol\";\nimport \"../policies/PolicyManager.sol\";\nimport \"../hub/Spoke.sol\";\nimport \"../accounting/Accounting.sol\";\nimport \"../../prices/IPriceSource.sol\";\nimport \"../../factory/Factory.sol\";\nimport \"../../engine/AmguConsumer.sol\";\nimport \"../../dependencies/token/IERC20.sol\";\nimport \"../../dependencies/DSMath.sol\";\nimport \"../../dependencies/TokenUser.sol\";\n\n/// @notice Entry and exit point for investors\ncontract Participation is TokenUser, AmguConsumer, Spoke {\n event EnableInvestment (address[] asset);\n event DisableInvestment (address[] assets);\n\n event InvestmentRequest (\n address indexed requestOwner,\n address indexed investmentAsset,\n uint requestedShares,\n uint investmentAmount\n );\n\n event RequestExecution (\n address indexed requestOwner,\n address indexed executor,\n address indexed investmentAsset,\n uint investmentAmount,\n uint requestedShares\n );\n\n event CancelRequest (\n address indexed requestOwner\n );\n\n event Redemption (\n address indexed redeemer,\n address[] assets,\n uint[] assetQuantities,\n uint redeemedShares\n );\n\n struct Request {\n address investmentAsset;\n uint investmentAmount;\n uint requestedShares;\n uint timestamp;\n }\n\n uint constant public SHARES_DECIMALS = 18;\n uint constant public REQUEST_LIFESPAN = 1 days;\n\n mapping (address => Request) public requests;\n mapping (address => bool) public investAllowed;\n mapping (address => bool) public hasInvested; // for information purposes only (read)\n\n address[] public historicalInvestors; // for information purposes only (read)\n\n constructor(address _hub, address[] memory _defaultAssets, address _registry)\n public\n Spoke(_hub)\n {\n routes.registry = _registry;\n _enableInvestment(_defaultAssets);\n }\n\n receive() external payable {}\n\n function _enableInvestment(address[] memory _assets) internal {\n for (uint i = 0; i < _assets.length; i++) {\n require(\n Registry(routes.registry).assetIsRegistered(_assets[i]),\n \"Asset not registered\"\n );\n investAllowed[_assets[i]] = true;\n }\n emit EnableInvestment(_assets);\n }\n\n function enableInvestment(address[] calldata _assets) external auth {\n _enableInvestment(_assets);\n }\n\n function disableInvestment(address[] calldata _assets) external auth {\n for (uint i = 0; i < _assets.length; i++) {\n investAllowed[_assets[i]] = false;\n }\n emit DisableInvestment(_assets);\n }\n\n function hasRequest(address _who) public view returns (bool) {\n return requests[_who].timestamp > 0;\n }\n\n function hasExpiredRequest(address _who) public view returns (bool) {\n return block.timestamp > add(requests[_who].timestamp, REQUEST_LIFESPAN);\n }\n\n /// @notice Whether request is OK and invest delay is being respected\n /// @dev Request valid if price update happened since request and not expired\n /// @dev If no shares exist and not expired, request can be executed immediately\n function hasValidRequest(address _who) public view returns (bool) {\n IPriceSource priceSource = IPriceSource(priceSource());\n bool delayRespectedOrNoShares = requests[_who].timestamp < priceSource.getLastUpdate() ||\n Shares(routes.shares).totalSupply() == 0;\n\n return hasRequest(_who) &&\n delayRespectedOrNoShares &&\n !hasExpiredRequest(_who) &&\n requests[_who].investmentAmount > 0 &&\n requests[_who].requestedShares > 0;\n }\n\n function requestInvestment(\n uint requestedShares,\n uint investmentAmount,\n address investmentAsset\n )\n external\n notShutDown\n payable\n amguPayable(true)\n onlyInitialized\n {\n PolicyManager(routes.policyManager).preValidate(\n bytes4(keccak256(\"requestInvestment(uint256,uint256,address)\")),\n [msg.sender, address(0), address(0), investmentAsset, address(0)],\n [uint(0), uint(0), uint(0)],\n bytes32(0)\n );\n require(\n investAllowed[investmentAsset],\n \"Investment not allowed in this asset\"\n );\n safeTransferFrom(\n investmentAsset, msg.sender, address(this), investmentAmount\n );\n require(\n requests[msg.sender].timestamp == 0,\n \"Only one request can exist at a time\"\n );\n requests[msg.sender] = Request({\n investmentAsset: investmentAsset,\n investmentAmount: investmentAmount,\n requestedShares: requestedShares,\n timestamp: block.timestamp\n });\n PolicyManager(routes.policyManager).postValidate(\n bytes4(keccak256(\"requestInvestment(uint256,uint256,address)\")),\n [msg.sender, address(0), address(0), investmentAsset, address(0)],\n [uint(0), uint(0), uint(0)],\n bytes32(0)\n );\n\n emit InvestmentRequest(\n msg.sender,\n investmentAsset,\n requestedShares,\n investmentAmount\n );\n }\n\n function _cancelRequestFor(address requestOwner) internal {\n require(hasRequest(requestOwner), \"No request to cancel\");\n IPriceSource priceSource = IPriceSource(priceSource());\n Request memory request = requests[requestOwner];\n require(\n !priceSource.hasValidPrice(request.investmentAsset) ||\n hasExpiredRequest(requestOwner) ||\n hub.isShutDown(),\n \"No cancellation condition was met\"\n );\n IERC20 investmentAsset = IERC20(request.investmentAsset);\n uint investmentAmount = request.investmentAmount;\n delete requests[requestOwner];\n msg.sender.transfer(Registry(routes.registry).incentive());\n safeTransfer(address(investmentAsset), requestOwner, investmentAmount);\n\n emit CancelRequest(requestOwner);\n }\n\n /// @notice Can only cancel when no price, request expired or fund shut down\n /// @dev Only request owner can cancel their request\n function cancelRequest() external payable amguPayable(false) {\n _cancelRequestFor(msg.sender);\n }\n\n function cancelRequestFor(address requestOwner)\n external\n payable\n amguPayable(false)\n {\n _cancelRequestFor(requestOwner);\n }\n\n function executeRequestFor(address requestOwner)\n external\n notShutDown\n amguPayable(false)\n payable\n {\n Request memory request = requests[requestOwner];\n require(\n hasValidRequest(requestOwner),\n \"No valid request for this address\"\n );\n require(\n IPriceSource(priceSource()).hasValidPrice(request.investmentAsset),\n \"Price not valid\"\n );\n\n FeeManager(routes.feeManager).rewardManagementFee();\n\n uint totalShareCostInInvestmentAsset = Accounting(routes.accounting)\n .getShareCostInAsset(\n request.requestedShares,\n request.investmentAsset\n );\n\n require(\n totalShareCostInInvestmentAsset <= request.investmentAmount,\n \"Invested amount too low\"\n );\n // send necessary amount of investmentAsset to vault\n safeTransfer(\n request.investmentAsset,\n routes.vault,\n totalShareCostInInvestmentAsset\n );\n\n uint investmentAssetChange = sub(\n request.investmentAmount,\n totalShareCostInInvestmentAsset\n );\n\n // return investmentAsset change to request owner\n if (investmentAssetChange > 0) {\n safeTransfer(\n request.investmentAsset,\n requestOwner,\n investmentAssetChange\n );\n }\n\n msg.sender.transfer(Registry(routes.registry).incentive());\n\n Shares(routes.shares).createFor(requestOwner, request.requestedShares);\n Accounting(routes.accounting).addAssetToOwnedAssets(request.investmentAsset);\n\n if (!hasInvested[requestOwner]) {\n hasInvested[requestOwner] = true;\n historicalInvestors.push(requestOwner);\n }\n\n emit RequestExecution(\n requestOwner,\n msg.sender,\n request.investmentAsset,\n request.investmentAmount,\n request.requestedShares\n );\n delete requests[requestOwner];\n }\n\n function getOwedPerformanceFees(uint shareQuantity)\n public\n returns (uint remainingShareQuantity)\n {\n Shares shares = Shares(routes.shares);\n\n if (msg.sender == hub.manager()) {\n return 0;\n }\n\n uint totalPerformanceFee = FeeManager(routes.feeManager).performanceFeeAmount();\n // The denominator is augmented because performanceFeeAmount() accounts for inflation\n // Since shares are directly transferred, we don't need to account for inflation in this case\n uint performanceFeePortion = mul(\n totalPerformanceFee,\n shareQuantity\n ) / add(shares.totalSupply(), totalPerformanceFee);\n return performanceFeePortion;\n }\n\n /// @dev \"Happy path\" (no asset throws & quantity available)\n /// @notice Redeem all shares and across all assets\n function redeem() external {\n uint ownedShares = Shares(routes.shares).balanceOf(msg.sender);\n redeemQuantity(ownedShares);\n }\n\n /// @notice Redeem shareQuantity across all assets\n function redeemQuantity(uint shareQuantity) public {\n address[] memory assetList;\n (, assetList) = Accounting(routes.accounting).getFundHoldings();\n redeemWithConstraints(shareQuantity, assetList);\n }\n\n // TODO: reconsider the scenario where the user has enough funds to force shutdown on a large trade (any way around this?)\n /// @dev Redeem only selected assets (used only when an asset throws)\n function redeemWithConstraints(uint shareQuantity, address[] memory requestedAssets) public {\n Shares shares = Shares(routes.shares);\n require(\n shares.balanceOf(msg.sender) >= shareQuantity &&\n shares.balanceOf(msg.sender) > 0,\n \"Sender does not have enough shares to fulfill request\"\n );\n\n uint owedPerformanceFees = 0;\n if (\n IPriceSource(priceSource()).hasValidPrices(requestedAssets) &&\n msg.sender != hub.manager()\n ) {\n FeeManager(routes.feeManager).rewardManagementFee();\n owedPerformanceFees = getOwedPerformanceFees(shareQuantity);\n shares.destroyFor(msg.sender, owedPerformanceFees);\n shares.createFor(hub.manager(), owedPerformanceFees);\n }\n uint remainingShareQuantity = sub(shareQuantity, owedPerformanceFees);\n\n address ofAsset;\n uint[] memory ownershipQuantities = new uint[](requestedAssets.length);\n address[] memory redeemedAssets = new address[](requestedAssets.length);\n // Check whether enough assets held by fund\n Accounting accounting = Accounting(routes.accounting);\n for (uint i = 0; i < requestedAssets.length; ++i) {\n ofAsset = requestedAssets[i];\n if (ofAsset == address(0)) continue;\n require(\n accounting.isInAssetList(ofAsset),\n \"Requested asset not in asset list\"\n );\n for (uint j = 0; j < redeemedAssets.length; j++) {\n require(\n ofAsset != redeemedAssets[j],\n \"Asset can only be redeemed once\"\n );\n }\n redeemedAssets[i] = ofAsset;\n uint quantityHeld = accounting.assetHoldings(ofAsset);\n if (quantityHeld == 0) continue;\n\n // participant's ownership percentage of asset holdings\n ownershipQuantities[i] = mul(quantityHeld, remainingShareQuantity) / shares.totalSupply();\n }\n\n shares.destroyFor(msg.sender, remainingShareQuantity);\n\n // Transfer owned assets\n for (uint k = 0; k < requestedAssets.length; ++k) {\n ofAsset = requestedAssets[k];\n if (ownershipQuantities[k] == 0) {\n continue;\n } else {\n Vault(routes.vault).withdraw(ofAsset, ownershipQuantities[k]);\n safeTransfer(ofAsset, msg.sender, ownershipQuantities[k]);\n }\n }\n emit Redemption(\n msg.sender,\n requestedAssets,\n ownershipQuantities,\n remainingShareQuantity\n );\n }\n\n function getHistoricalInvestors() external view returns (address[] memory) {\n return historicalInvestors;\n }\n\n function engine() public view override(AmguConsumer, Spoke) returns (address) { return Spoke.engine(); }\n function mlnToken() public view override(AmguConsumer, Spoke) returns (address) { return Spoke.mlnToken(); }\n function priceSource() public view override(AmguConsumer, Spoke) returns (address) { return Spoke.priceSource(); }\n function registry() public view override(AmguConsumer, Spoke) returns (address) { return Spoke.registry(); }\n}\n\ncontract ParticipationFactory is Factory {\n event NewInstance(\n address indexed hub,\n address indexed instance,\n address[] defaultAssets,\n address registry\n );\n\n function createInstance(address _hub, address[] calldata _defaultAssets, address _registry)\n external\n returns (address)\n {\n address participation = address(\n new Participation(_hub, _defaultAssets, _registry)\n );\n childExists[participation] = true;\n emit NewInstance(_hub, participation, _defaultAssets, _registry);\n return participation;\n }\n}\n\n"
},
"./src/fund/policies/AddressList.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../../dependencies/DSAuth.sol\";\n\n/// @notice Generic AddressList\ncontract AddressList is DSAuth {\n\n event ListAddition(address[] ones);\n\n mapping(address => bool) internal list;\n address[] internal mirror;\n\n constructor(address[] memory _assets) public {\n for (uint i = 0; i < _assets.length; i++) {\n if (!isMember(_assets[i])) { // filter duplicates in _assets\n list[_assets[i]] = true;\n mirror.push(_assets[i]);\n }\n }\n emit ListAddition(_assets);\n }\n\n /// @return whether an asset is in the list\n function isMember(address _asset) public view returns (bool) {\n return list[_asset];\n }\n\n /// @return number of assets specified in the list\n function getMemberCount() external view returns (uint) {\n return mirror.length;\n }\n\n /// @return array of all listed asset addresses\n function getMembers() external view returns (address[] memory) { return mirror; }\n}\n"
},
"./src/fund/policies/compliance/UserWhitelist.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../../../dependencies/DSAuth.sol\";\n\ncontract UserWhitelist is DSAuth {\n enum Applied { pre, post }\n\n event ListAddition(address indexed who);\n event ListRemoval(address indexed who);\n\n mapping (address => bool) public whitelisted;\n\n constructor(address[] memory _preApproved) public {\n batchAddToWhitelist(_preApproved);\n }\n\n function addToWhitelist(address _who) public auth {\n whitelisted[_who] = true;\n emit ListAddition(_who);\n }\n\n function removeFromWhitelist(address _who) public auth {\n whitelisted[_who] = false;\n emit ListRemoval(_who);\n }\n\n function batchAddToWhitelist(address[] memory _members) public auth {\n for (uint i = 0; i < _members.length; i++) {\n addToWhitelist(_members[i]);\n }\n }\n\n function batchRemoveFromWhitelist(address[] memory _members) public auth {\n for (uint i = 0; i < _members.length; i++) {\n removeFromWhitelist(_members[i]);\n }\n }\n\n function rule(bytes4 sig, address[5] calldata addresses, uint[3] calldata values, bytes32 identifier) external returns (bool) {\n return whitelisted[addresses[0]];\n }\n\n function position() external pure returns (Applied) { return Applied.pre; }\n function identifier() external pure returns (string memory) { return 'UserWhitelist'; }\n}\n"
},
"./src/fund/policies/IPolicy.sol": {
"content": "pragma solidity 0.6.1;\n\ninterface IPolicy {\n enum Applied { pre, post }\n\n // In Trading context:\n // addresses: Order maker, Order taker, Order maker asset, Order taker asset, Exchange address\n // values: Maker token quantity, Taker token quantity, Fill Taker Quantity\n\n // In Participation context:\n // address[0]: Investor address, address[3]: Investment asset\n function rule(bytes4 sig, address[5] calldata addresses, uint[3] calldata values, bytes32 identifier) external returns (bool);\n\n function position() external view returns (Applied);\n function identifier() external view returns (string memory);\n}\n"
},
"./src/fund/policies/IPolicyManager.sol": {
"content": "pragma solidity 0.6.1;\n\n\ninterface IPolicyManagerFactory {\n function createInstance(address _hub) external returns (address);\n}\n\n"
},
"./src/fund/policies/PolicyManager.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../../factory/Factory.sol\";\nimport \"../hub/Spoke.sol\";\nimport \"./IPolicy.sol\";\n\ncontract PolicyManager is Spoke {\n\n event Registration(\n bytes4 indexed sig,\n IPolicy.Applied position,\n address indexed policy\n );\n\n struct Entry {\n IPolicy[] pre;\n IPolicy[] post;\n }\n\n mapping(bytes4 => Entry) policies;\n\n constructor (address _hub) public Spoke(_hub) {}\n\n function register(bytes4 sig, address _policy) public auth {\n IPolicy.Applied position = IPolicy(_policy).position();\n if (position == IPolicy.Applied.pre) {\n policies[sig].pre.push(IPolicy(_policy));\n } else if (position == IPolicy.Applied.post) {\n policies[sig].post.push(IPolicy(_policy));\n } else {\n revert(\"Only pre and post allowed\");\n }\n emit Registration(sig, position, _policy);\n }\n\n function batchRegister(bytes4[] memory sig, address[] memory _policies) public auth {\n require(sig.length == _policies.length, \"Arrays lengths unequal\");\n for (uint i = 0; i < sig.length; i++) {\n register(sig[i], _policies[i]);\n }\n }\n\n function PoliciesToAddresses(IPolicy[] storage _policies) internal view returns (address[] memory) {\n address[] memory res = new address[](_policies.length);\n for(uint i = 0; i < _policies.length; i++) {\n res[i] = address(_policies[i]);\n }\n return res;\n }\n\n function getPoliciesBySig(bytes4 sig) public view returns (address[] memory, address[] memory) {\n return (PoliciesToAddresses(policies[sig].pre), PoliciesToAddresses(policies[sig].post));\n }\n\n modifier isValidPolicyBySig(bytes4 sig, address[5] memory addresses, uint[3] memory values, bytes32 identifier) {\n preValidate(sig, addresses, values, identifier);\n _;\n postValidate(sig, addresses, values, identifier);\n }\n\n modifier isValidPolicy(address[5] memory addresses, uint[3] memory values, bytes32 identifier) {\n preValidate(msg.sig, addresses, values, identifier);\n _;\n postValidate(msg.sig, addresses, values, identifier);\n }\n\n function preValidate(bytes4 sig, address[5] memory addresses, uint[3] memory values, bytes32 identifier) public {\n validate(policies[sig].pre, sig, addresses, values, identifier);\n }\n\n function postValidate(bytes4 sig, address[5] memory addresses, uint[3] memory values, bytes32 identifier) public {\n validate(policies[sig].post, sig, addresses, values, identifier);\n }\n\n function validate(IPolicy[] storage aux, bytes4 sig, address[5] memory addresses, uint[3] memory values, bytes32 identifier) internal {\n for(uint i = 0; i < aux.length; i++) {\n require(\n aux[i].rule(sig, addresses, values, identifier),\n string(abi.encodePacked(\"Rule evaluated to false: \", aux[i].identifier()))\n );\n }\n }\n}\n\ncontract PolicyManagerFactory is Factory {\n function createInstance(address _hub) external returns (address) {\n address policyManager = address(new PolicyManager(_hub));\n childExists[policyManager] = true;\n emit NewInstance(_hub, policyManager);\n return policyManager;\n }\n}\n"
},
"./src/fund/policies/risk-management/AssetBlacklist.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../AddressList.sol\";\nimport \"../TradingSignatures.sol\";\n\n/// @notice Assets can be added but not removed from blacklist\ncontract AssetBlacklist is TradingSignatures, AddressList {\n enum Applied { pre, post }\n\n // bytes4 constant public MAKE_ORDER = 0x79705be7; // makeOrderSignature\n // bytes4 constant public TAKE_ORDER = 0xe51be6e8; // takeOrderSignature\n\n constructor(address[] memory _assets) AddressList(_assets) public {}\n\n function addToBlacklist(address _asset) external auth {\n require(!isMember(_asset), \"Asset already in blacklist\");\n list[_asset] = true;\n mirror.push(_asset);\n }\n\n function rule(bytes4 sig, address[5] calldata addresses, uint[3] calldata values, bytes32 identifier) external returns (bool) {\n address incomingToken = (sig == TAKE_ORDER) ? addresses[2] : addresses[3];\n return !isMember(incomingToken);\n }\n\n function position() external pure returns (Applied) { return Applied.pre; }\n function identifier() external pure returns (string memory) { return 'AssetBlacklist'; }\n}\n"
},
"./src/fund/policies/risk-management/AssetWhitelist.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../AddressList.sol\";\nimport \"../TradingSignatures.sol\";\n\n/// @notice Assets can be removed from but not added to whitelist\ncontract AssetWhitelist is TradingSignatures, AddressList {\n enum Applied { pre, post }\n\n constructor(address[] memory _assets) public AddressList(_assets) {}\n\n function removeFromWhitelist(address _asset) external auth {\n require(isMember(_asset), \"Asset not in whitelist\");\n delete list[_asset];\n uint i = getAssetIndex(_asset);\n for (i; i < mirror.length-1; i++){\n mirror[i] = mirror[i+1];\n }\n mirror.pop();\n }\n\n function getAssetIndex(address _asset) public view returns (uint) {\n for (uint i = 0; i < mirror.length; i++) {\n if (mirror[i] == _asset) { return i; }\n }\n }\n\n function rule(bytes4 sig, address[5] calldata addresses, uint[3] calldata values, bytes32 identifier) external returns (bool) {\n address incomingToken = (sig == TAKE_ORDER) ? addresses[2] : addresses[3];\n return isMember(incomingToken);\n }\n\n function position() external pure returns (Applied) { return Applied.pre; }\n function identifier() external pure returns (string memory) { return 'AssetWhitelist'; }\n}\n"
},
"./src/fund/policies/risk-management/MaxConcentration.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../../../dependencies/DSMath.sol\";\nimport \"../../../prices/IPriceSource.sol\";\nimport \"../../accounting/Accounting.sol\";\nimport \"../../trading/Trading.sol\";\nimport \"../TradingSignatures.sol\";\nimport \"../../../prices/IPriceSource.sol\";\n\ncontract MaxConcentration is TradingSignatures, DSMath {\n enum Applied { pre, post }\n\n uint internal constant ONE_HUNDRED_PERCENT = 10 ** 18; // 100%\n uint public maxConcentration;\n\n constructor(uint _maxConcentration) public {\n require(\n _maxConcentration <= ONE_HUNDRED_PERCENT,\n \"Max concentration cannot exceed 100%\"\n );\n maxConcentration = _maxConcentration;\n }\n\n function rule(bytes4 sig, address[5] calldata addresses, uint[3] calldata values, bytes32 identifier)\n external\n returns (bool)\n {\n Accounting accounting = Accounting(Hub(Trading(msg.sender).hub()).accounting());\n address denominationAsset = accounting.DENOMINATION_ASSET();\n // Max concentration is only checked for non-quote assets\n address takerToken = (sig == TAKE_ORDER) ? addresses[2] : addresses[3];\n if (denominationAsset == takerToken) { return true; }\n\n uint concentration;\n uint totalGav = accounting.calcGav();\n if (sig == MAKE_ORDER) {\n IPriceSource priceSource = IPriceSource(Hub(Trading(msg.sender).hub()).priceSource());\n address makerToken = addresses[2];\n uint makerQuantiyBeingTraded = values[0];\n uint takerQuantityBeingTraded = values[1];\n\n uint takerTokenGavBeingTraded = priceSource.convertQuantity(\n takerQuantityBeingTraded, takerToken, denominationAsset\n );\n\n uint makerTokenGavBeingTraded;\n if (makerToken == denominationAsset) {\n makerTokenGavBeingTraded = makerQuantiyBeingTraded;\n }\n else {\n makerTokenGavBeingTraded = priceSource.convertQuantity(\n makerQuantiyBeingTraded, makerToken, denominationAsset\n );\n }\n concentration = _calcConcentration(\n add(accounting.calcAssetGAV(takerToken), takerTokenGavBeingTraded),\n add(takerTokenGavBeingTraded, sub(totalGav, makerTokenGavBeingTraded))\n );\n }\n else {\n concentration = _calcConcentration(\n accounting.calcAssetGAV(takerToken),\n totalGav\n );\n }\n return concentration <= maxConcentration;\n }\n\n function position() external pure returns (Applied) { return Applied.post; }\n function identifier() external pure returns (string memory) { return 'MaxConcentration'; }\n\n function _calcConcentration(uint assetGav, uint totalGav) internal returns (uint) {\n return mul(assetGav, ONE_HUNDRED_PERCENT) / totalGav;\n }\n}\n"
},
"./src/fund/policies/risk-management/MaxPositions.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../../../prices/IPriceSource.sol\";\nimport \"../../accounting/Accounting.sol\";\nimport \"../../trading/Trading.sol\";\nimport \"../TradingSignatures.sol\";\n\ncontract MaxPositions is TradingSignatures {\n enum Applied { pre, post }\n\n uint public maxPositions;\n\n /// @dev _maxPositions = 10 means max 10 different asset tokens\n /// @dev _maxPositions = 0 means no asset tokens are investable\n constructor(uint _maxPositions) public { maxPositions = _maxPositions; }\n\n function rule(bytes4 sig, address[5] calldata addresses, uint[3] calldata values, bytes32 identifier)\n external\n returns (bool)\n {\n Accounting accounting = Accounting(Hub(Trading(msg.sender).hub()).accounting());\n address denominationAsset = accounting.DENOMINATION_ASSET();\n // Always allow a trade INTO the quote asset\n address incomingToken = (sig == TAKE_ORDER) ? addresses[2] : addresses[3];\n if (denominationAsset == incomingToken) { return true; }\n return accounting.getOwnedAssetsLength() <= maxPositions;\n }\n\n function position() external pure returns (Applied) { return Applied.post; }\n function identifier() external pure returns (string memory) { return 'MaxPositions'; }\n}\n"
},
"./src/fund/policies/risk-management/PriceTolerance.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../../hub/Hub.sol\";\nimport \"../../../prices/IPriceSource.sol\";\nimport \"../TradingSignatures.sol\";\nimport \"../../../dependencies/DSMath.sol\";\nimport \"../../trading/Trading.sol\";\nimport \"../../../exchanges/interfaces/IOasisDex.sol\";\n\ncontract PriceTolerance is TradingSignatures, DSMath {\n enum Applied { pre, post }\n\n uint public tolerance;\n\n uint constant MULTIPLIER = 10 ** 16; // to give effect of a percentage\n uint constant DIVISOR = 10 ** 18;\n\n // _tolerance: 10 equals to 10% of tolerance\n constructor(uint _tolerancePercent) public {\n require(_tolerancePercent <= 100, \"Tolerance range is 0% - 100%\");\n tolerance = mul(_tolerancePercent, MULTIPLIER);\n }\n\n /// @notice Taken from OpenZeppelin (https://git.io/fhQqo)\n function signedSafeSub(int256 a, int256 b) internal pure returns (int256) {\n int256 c = a - b;\n require((b >= 0 && c <= a) || (b < 0 && c > a));\n\n return c;\n }\n\n function takeOasisDex(\n address ofExchange,\n bytes32 identifier,\n uint fillTakerQuantity\n ) public view returns (bool) {\n uint maxMakerQuantity;\n address makerAsset;\n uint maxTakerQuantity;\n address takerAsset;\n (\n maxMakerQuantity,\n makerAsset,\n maxTakerQuantity,\n takerAsset\n ) = IOasisDex(ofExchange).getOffer(uint(identifier));\n\n uint fillMakerQuantity = mul(fillTakerQuantity, maxMakerQuantity) / maxTakerQuantity;\n\n IPriceSource pricefeed = IPriceSource(Hub(Trading(msg.sender).hub()).priceSource());\n uint referencePrice;\n (referencePrice,) = pricefeed.getReferencePriceInfo(takerAsset, makerAsset);\n\n uint orderPrice = pricefeed.getOrderPriceInfo(\n takerAsset,\n makerAsset,\n fillTakerQuantity,\n fillMakerQuantity\n );\n\n return orderPrice >= sub(\n referencePrice,\n mul(tolerance, referencePrice) / DIVISOR\n );\n }\n\n function takeGenericOrder(\n address makerAsset,\n address takerAsset,\n uint[3] memory values\n ) public view returns (bool) {\n uint fillTakerQuantity = values[2];\n uint fillMakerQuantity = mul(fillTakerQuantity, values[0]) / values[1];\n\n IPriceSource pricefeed = IPriceSource(Hub(Trading(msg.sender).hub()).priceSource());\n uint referencePrice;\n (referencePrice, ) = pricefeed.getReferencePriceInfo(takerAsset, makerAsset);\n\n uint orderPrice = pricefeed.getOrderPriceInfo(\n takerAsset,\n makerAsset,\n fillTakerQuantity,\n fillMakerQuantity\n );\n\n return orderPrice >= sub(\n referencePrice,\n mul(tolerance, referencePrice) / DIVISOR\n );\n }\n\n function takeOrder(\n address[5] memory addresses,\n uint[3] memory values,\n bytes32 identifier\n ) public view returns (bool) {\n if (identifier == 0x0) {\n return takeGenericOrder(addresses[2], addresses[3], values);\n } else {\n return takeOasisDex(addresses[4], identifier, values[2]);\n }\n }\n\n function makeOrder(\n address[5] memory addresses,\n uint[3] memory values,\n bytes32 identifier\n ) public view returns (bool) {\n IPriceSource pricefeed = IPriceSource(Hub(Trading(msg.sender).hub()).priceSource());\n\n uint ratio;\n (ratio,) = IPriceSource(pricefeed).getReferencePriceInfo(addresses[2], addresses[3]);\n uint _value = IPriceSource(pricefeed).getOrderPriceInfo(addresses[2], addresses[3], values[0], values[1]);\n\n int res = signedSafeSub(int(ratio), int(_value));\n if (res < 0) {\n return true;\n } else {\n return wdiv(uint(res), ratio) <= tolerance;\n }\n }\n\n function rule(\n bytes4 sig,\n address[5] calldata addresses,\n uint[3] calldata values,\n bytes32 identifier\n ) external returns (bool) {\n if (sig == MAKE_ORDER) {\n return makeOrder(addresses, values, identifier);\n } else if (sig == TAKE_ORDER) {\n return takeOrder(addresses, values, identifier);\n }\n revert(\"Signature was neither MakeOrder nor TakeOrder\");\n }\n\n function position() external pure returns (Applied) { return Applied.pre; }\n function identifier() external pure returns (string memory) { return 'PriceTolerance'; }\n}\n"
},
"./src/fund/policies/TradingSignatures.sol": {
"content": "pragma solidity 0.6.1;\n\ncontract TradingSignatures {\n bytes4 constant public MAKE_ORDER = 0x5f08e909; // makeOrderSignature\n bytes4 constant public TAKE_ORDER = 0x63b24ef1; // takeOrderSignature\n}\n"
},
"./src/fund/shares/IShares.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @notice Token representing ownership of the Fund\ninterface IShares {\n function createFor(address who, uint amount) external;\n function destroyFor(address who, uint amount) external;\n}\n\ninterface ISharesFactory {\n function createInstance(address _hub) external returns (address);\n}\n\n"
},
"./src/fund/shares/Shares.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../hub/Spoke.sol\";\nimport \"../../dependencies/token/StandardToken.sol\";\nimport \"../../factory/Factory.sol\";\n\ncontract Shares is Spoke, StandardToken {\n string public symbol;\n string public name;\n uint8 public decimals;\n\n constructor(address _hub) public Spoke(_hub) {\n name = hub.name();\n symbol = \"MLNF\";\n decimals = 18;\n }\n\n function createFor(address who, uint amount) public auth {\n _mint(who, amount);\n }\n\n function destroyFor(address who, uint amount) public auth {\n _burn(who, amount);\n }\n\n function transfer(address to, uint amount) public override returns (bool) {\n revert(\"Unimplemented\");\n }\n\n function transferFrom(\n address from,\n address to,\n uint amount\n )\n public\n override\n returns (bool)\n {\n revert(\"Unimplemented\");\n }\n\n function approve(address spender, uint amount) public override returns (bool) {\n revert(\"Unimplemented\");\n }\n\n function increaseApproval(\n address spender,\n uint amount\n )\n public\n override\n returns (bool)\n {\n revert(\"Unimplemented\");\n }\n\n function decreaseApproval(\n address spender,\n uint amount\n )\n public\n override\n returns (bool)\n {\n revert(\"Unimplemented\");\n }\n}\n\ncontract SharesFactory is Factory {\n function createInstance(address _hub) external returns (address) {\n address shares = address(new Shares(_hub));\n childExists[shares] = true;\n emit NewInstance(_hub, shares);\n return shares;\n }\n}\n\n"
},
"./src/fund/trading/ITrading.sol": {
"content": "pragma solidity 0.6.1;\n\npragma experimental ABIEncoderV2;\n\n// TODO: Restore indexed params\n\n/// @notice Mediation between a Fund and exchanges\ninterface ITrading {\n function callOnExchange(\n uint exchangeIndex,\n string calldata methodSignature,\n address[8] calldata orderAddresses,\n uint[8] calldata orderValues,\n bytes[4] calldata orderData,\n bytes32 identifier,\n bytes calldata signature\n ) external;\n\n function addOpenMakeOrder(\n address ofExchange,\n address ofSellAsset,\n address ofBuyAsset,\n uint orderId,\n uint expiryTime\n ) external;\n\n function removeOpenMakeOrder(\n address ofExchange,\n address ofSellAsset\n ) external;\n\n function updateAndGetQuantityBeingTraded(address _asset) external returns (uint256);\n function getOpenMakeOrdersAgainstAsset(address _asset) external view returns (uint256);\n}\n\ninterface ITradingFactory {\n function createInstance(\n address _hub,\n address[] calldata _exchanges,\n address[] calldata _adapters,\n address _registry\n ) external returns (address);\n}\n"
},
"./src/fund/trading/Trading.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../hub/Spoke.sol\";\nimport \"../vault/Vault.sol\";\nimport \"../policies/PolicyManager.sol\";\nimport \"../policies/TradingSignatures.sol\";\nimport \"../../factory/Factory.sol\";\nimport \"../../dependencies/DSMath.sol\";\nimport \"../../exchanges/ExchangeAdapter.sol\";\nimport \"../../exchanges/interfaces/IZeroExV2.sol\";\nimport \"../../exchanges/interfaces/IZeroExV3.sol\";\nimport \"../../version/Registry.sol\";\nimport \"../../dependencies/TokenUser.sol\";\n\ncontract Trading is DSMath, TokenUser, Spoke, TradingSignatures {\n event ExchangeMethodCall(\n address indexed exchangeAddress,\n string indexed methodSignature,\n address[8] orderAddresses,\n uint[8] orderValues,\n bytes[4] orderData,\n bytes32 identifier,\n bytes signature\n );\n\n struct Exchange {\n address exchange;\n address adapter;\n bool takesCustody;\n }\n\n enum UpdateType { make, take, cancel }\n\n struct Order {\n address exchangeAddress;\n bytes32 orderId;\n UpdateType updateType;\n address makerAsset;\n address takerAsset;\n uint makerQuantity;\n uint takerQuantity;\n uint timestamp;\n uint fillTakerQuantity;\n }\n\n struct OpenMakeOrder {\n uint id; // Order Id from exchange\n uint expiresAt; // Timestamp when the order expires\n uint orderIndex; // Index of the order in the orders array\n address buyAsset; // Address of the buy asset in the order\n }\n\n Exchange[] public exchanges;\n Order[] public orders;\n mapping (address => bool) public adapterIsAdded;\n mapping (address => mapping(address => OpenMakeOrder)) public exchangesToOpenMakeOrders;\n mapping (address => uint) public openMakeOrdersAgainstAsset;\n mapping (address => bool) public isInOpenMakeOrder;\n mapping (address => uint) public makerAssetCooldown;\n mapping (bytes32 => IZeroExV2.Order) internal orderIdToZeroExV2Order;\n mapping (bytes32 => IZeroExV3.Order) internal orderIdToZeroExV3Order;\n\n uint public constant ORDER_LIFESPAN = 1 days;\n uint public constant MAKE_ORDER_COOLDOWN = 30 minutes;\n\n modifier delegateInternal() {\n require(msg.sender == address(this), \"Sender is not this contract\");\n _;\n }\n\n constructor(\n address _hub,\n address[] memory _exchanges,\n address[] memory _adapters,\n address _registry\n )\n public\n Spoke(_hub)\n {\n routes.registry = _registry;\n require(_exchanges.length == _adapters.length, \"Array lengths unequal\");\n for (uint i = 0; i < _exchanges.length; i++) {\n _addExchange(_exchanges[i], _adapters[i]);\n }\n }\n\n /// @notice Receive ether function (used to receive ETH from WETH)\n receive() external payable {}\n\n function addExchange(address _exchange, address _adapter) external auth {\n _addExchange(_exchange, _adapter);\n }\n\n function _addExchange(\n address _exchange,\n address _adapter\n ) internal {\n require(!adapterIsAdded[_adapter], \"Adapter already added\");\n adapterIsAdded[_adapter] = true;\n Registry registry = Registry(routes.registry);\n require(\n registry.exchangeAdapterIsRegistered(_adapter),\n \"Adapter is not registered\"\n );\n\n address registeredExchange;\n bool takesCustody;\n (registeredExchange, takesCustody) = registry.getExchangeInformation(_adapter);\n\n require(\n registeredExchange == _exchange,\n \"Exchange and adapter do not match\"\n );\n exchanges.push(Exchange(_exchange, _adapter, takesCustody));\n }\n\n /// @notice Universal method for calling exchange functions through adapters\n /// @notice See adapter contracts for parameters needed for each exchange\n /// @param exchangeIndex Index of the exchange in the \"exchanges\" array\n /// @param orderAddresses [0] Order maker\n /// @param orderAddresses [1] Order taker\n /// @param orderAddresses [2] Order maker asset\n /// @param orderAddresses [3] Order taker asset\n /// @param orderAddresses [4] feeRecipientAddress\n /// @param orderAddresses [5] senderAddress\n /// @param orderAddresses [6] maker fee asset\n /// @param orderAddresses [7] taker fee asset\n /// @param orderValues [0] makerAssetAmount\n /// @param orderValues [1] takerAssetAmount\n /// @param orderValues [2] Maker fee\n /// @param orderValues [3] Taker fee\n /// @param orderValues [4] expirationTimeSeconds\n /// @param orderValues [5] Salt/nonce\n /// @param orderValues [6] Fill amount: amount of taker token to be traded\n /// @param orderValues [7] Dexy signature mode\n /// @param orderData [0] Encoded data specific to maker asset\n /// @param orderData [1] Encoded data specific to taker asset\n /// @param orderData [2] Encoded data specific to maker asset fee\n /// @param orderData [3] Encoded data specific to taker asset fee\n /// @param identifier Order identifier\n /// @param signature Signature of order maker\n function callOnExchange(\n uint exchangeIndex,\n string memory methodSignature,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n )\n public\n onlyInitialized\n {\n bytes4 methodSelector = bytes4(keccak256(bytes(methodSignature)));\n require(\n Registry(routes.registry).adapterMethodIsAllowed(\n exchanges[exchangeIndex].adapter,\n methodSelector\n ),\n \"Adapter method not allowed\"\n );\n PolicyManager(routes.policyManager).preValidate(methodSelector, [orderAddresses[0], orderAddresses[1], orderAddresses[2], orderAddresses[3], exchanges[exchangeIndex].exchange], [orderValues[0], orderValues[1], orderValues[6]], identifier);\n if (\n methodSelector == MAKE_ORDER ||\n methodSelector == TAKE_ORDER\n ) {\n require(Registry(routes.registry).assetIsRegistered(\n orderAddresses[2]), 'Maker asset not registered'\n );\n require(Registry(routes.registry).assetIsRegistered(\n orderAddresses[3]), 'Taker asset not registered'\n );\n if (orderAddresses[6] != address(0) && methodSelector == MAKE_ORDER) {\n require(\n Registry(routes.registry).assetIsRegistered(orderAddresses[6]),\n 'Maker fee asset not registered'\n );\n }\n if (orderAddresses[7] != address(0) && methodSelector == TAKE_ORDER) {\n require(\n Registry(routes.registry).assetIsRegistered(orderAddresses[7]),\n 'Taker fee asset not registered'\n );\n }\n }\n (bool success, bytes memory returnData) = exchanges[exchangeIndex].adapter.delegatecall(\n abi.encodeWithSignature(\n methodSignature,\n exchanges[exchangeIndex].exchange,\n orderAddresses,\n orderValues,\n orderData,\n identifier,\n signature\n )\n );\n require(success, string(returnData));\n PolicyManager(routes.policyManager).postValidate(methodSelector, [orderAddresses[0], orderAddresses[1], orderAddresses[2], orderAddresses[3], exchanges[exchangeIndex].exchange], [orderValues[0], orderValues[1], orderValues[6]], identifier);\n emit ExchangeMethodCall(\n exchanges[exchangeIndex].exchange,\n methodSignature,\n orderAddresses,\n orderValues,\n orderData,\n identifier,\n signature\n );\n }\n\n /// @dev Make sure this is called after orderUpdateHook in adapters\n function addOpenMakeOrder(\n address ofExchange,\n address sellAsset,\n address buyAsset,\n uint orderId,\n uint expirationTime\n ) public delegateInternal {\n require(!isInOpenMakeOrder[sellAsset], \"Asset already in open order\");\n require(orders.length > 0, \"No orders in array\");\n\n // If expirationTime is 0, actualExpirationTime is set to ORDER_LIFESPAN from now\n uint actualExpirationTime = (expirationTime == 0) ? add(block.timestamp, ORDER_LIFESPAN) : expirationTime;\n\n require(\n actualExpirationTime <= add(block.timestamp, ORDER_LIFESPAN) &&\n actualExpirationTime > block.timestamp,\n \"Expiry time greater than max order lifespan or has already passed\"\n );\n isInOpenMakeOrder[sellAsset] = true;\n makerAssetCooldown[sellAsset] = add(actualExpirationTime, MAKE_ORDER_COOLDOWN);\n openMakeOrdersAgainstAsset[buyAsset] = add(openMakeOrdersAgainstAsset[buyAsset], 1);\n exchangesToOpenMakeOrders[ofExchange][sellAsset].id = orderId;\n exchangesToOpenMakeOrders[ofExchange][sellAsset].expiresAt = actualExpirationTime;\n exchangesToOpenMakeOrders[ofExchange][sellAsset].orderIndex = sub(orders.length, 1);\n exchangesToOpenMakeOrders[ofExchange][sellAsset].buyAsset = buyAsset;\n\n }\n\n function _removeOpenMakeOrder(\n address exchange,\n address sellAsset\n ) internal {\n if (isInOpenMakeOrder[sellAsset]) {\n\n makerAssetCooldown[sellAsset] = add(block.timestamp, MAKE_ORDER_COOLDOWN);\n address buyAsset = exchangesToOpenMakeOrders[exchange][sellAsset].buyAsset;\n delete exchangesToOpenMakeOrders[exchange][sellAsset];\n openMakeOrdersAgainstAsset[buyAsset] = sub(openMakeOrdersAgainstAsset[buyAsset], 1);\n }\n }\n\n function removeOpenMakeOrder(\n address exchange,\n address sellAsset\n ) public delegateInternal {\n _removeOpenMakeOrder(exchange, sellAsset);\n }\n\n /// @dev Bit of Redundancy for now\n function addZeroExV2OrderData(\n bytes32 orderId,\n IZeroExV2.Order memory zeroExOrderData\n ) public delegateInternal {\n orderIdToZeroExV2Order[orderId] = zeroExOrderData;\n }\n function addZeroExV3OrderData(\n bytes32 orderId,\n IZeroExV3.Order memory zeroExOrderData\n ) public delegateInternal {\n orderIdToZeroExV3Order[orderId] = zeroExOrderData;\n }\n\n function orderUpdateHook(\n address ofExchange,\n bytes32 orderId,\n UpdateType updateType,\n address payable[2] memory orderAddresses,\n uint[3] memory orderValues\n ) public delegateInternal {\n // only save make/take\n if (updateType == UpdateType.make || updateType == UpdateType.take) {\n orders.push(Order({\n exchangeAddress: ofExchange,\n orderId: orderId,\n updateType: updateType,\n makerAsset: orderAddresses[0],\n takerAsset: orderAddresses[1],\n makerQuantity: orderValues[0],\n takerQuantity: orderValues[1],\n timestamp: block.timestamp,\n fillTakerQuantity: orderValues[2]\n }));\n }\n }\n\n function updateAndGetQuantityBeingTraded(address _asset) external returns (uint) {\n uint quantityHere = IERC20(_asset).balanceOf(address(this));\n return add(updateAndGetQuantityHeldInExchange(_asset), quantityHere);\n }\n\n function updateAndGetQuantityHeldInExchange(address ofAsset) public returns (uint) {\n uint totalSellQuantity; // quantity in custody across exchanges\n uint totalSellQuantityInApprove; // quantity of asset in approve (allowance) but not custody of exchange\n for (uint i; i < exchanges.length; i++) {\n if (exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id == 0) {\n continue;\n }\n address sellAsset;\n uint remainingSellQuantity;\n (sellAsset, , remainingSellQuantity, ) =\n ExchangeAdapter(exchanges[i].adapter)\n .getOrder(\n exchanges[i].exchange,\n exchangesToOpenMakeOrders[exchanges[i].exchange][ofAsset].id,\n ofAsset\n );\n if (remainingSellQuantity == 0) { // remove id if remaining sell quantity zero (closed)\n _removeOpenMakeOrder(exchanges[i].exchange, ofAsset);\n }\n totalSellQuantity = add(totalSellQuantity, remainingSellQuantity);\n if (!exchanges[i].takesCustody) {\n totalSellQuantityInApprove += remainingSellQuantity;\n }\n }\n if (totalSellQuantity == 0) {\n isInOpenMakeOrder[ofAsset] = false;\n }\n return sub(totalSellQuantity, totalSellQuantityInApprove); // Since quantity in approve is not actually in custody\n }\n\n function returnBatchToVault(address[] memory _tokens) public {\n for (uint i = 0; i < _tokens.length; i++) {\n returnAssetToVault(_tokens[i]);\n }\n }\n\n function returnAssetToVault(address _token) public {\n require(\n msg.sender == address(this) || msg.sender == hub.manager() || hub.isShutDown(),\n \"Sender is not this contract or manager\"\n );\n safeTransfer(_token, routes.vault, IERC20(_token).balanceOf(address(this)));\n }\n\n function getExchangeInfo() public view returns (address[] memory, address[] memory, bool[] memory) {\n address[] memory ofExchanges = new address[](exchanges.length);\n address[] memory ofAdapters = new address[](exchanges.length);\n bool[] memory takesCustody = new bool[](exchanges.length);\n for (uint i = 0; i < exchanges.length; i++) {\n ofExchanges[i] = exchanges[i].exchange;\n ofAdapters[i] = exchanges[i].adapter;\n takesCustody[i] = exchanges[i].takesCustody;\n }\n return (ofExchanges, ofAdapters, takesCustody);\n }\n\n function getOpenOrderInfo(address ofExchange, address ofAsset) public view returns (uint, uint, uint) {\n OpenMakeOrder memory order = exchangesToOpenMakeOrders[ofExchange][ofAsset];\n return (order.id, order.expiresAt, order.orderIndex);\n }\n\n function isOrderExpired(address exchange, address asset) public view returns(bool) {\n return (\n exchangesToOpenMakeOrders[exchange][asset].expiresAt <= block.timestamp &&\n exchangesToOpenMakeOrders[exchange][asset].expiresAt > 0\n );\n }\n\n function getOrderDetails(uint orderIndex) public view returns (address, address, uint, uint) {\n Order memory order = orders[orderIndex];\n return (order.makerAsset, order.takerAsset, order.makerQuantity, order.takerQuantity);\n }\n\n function getZeroExV2OrderDetails(bytes32 orderId) public view returns (IZeroExV2.Order memory) {\n return orderIdToZeroExV2Order[orderId];\n }\n\n function getZeroExV3OrderDetails(bytes32 orderId) public view returns (IZeroExV3.Order memory) {\n return orderIdToZeroExV3Order[orderId];\n }\n\n function getOpenMakeOrdersAgainstAsset(address _asset) external view returns (uint256) {\n return openMakeOrdersAgainstAsset[_asset];\n }\n}\n\ncontract TradingFactory is Factory {\n event NewInstance(\n address indexed hub,\n address indexed instance,\n address[] exchanges,\n address[] adapters,\n address registry\n );\n\n function createInstance(\n address _hub,\n address[] memory _exchanges,\n address[] memory _adapters,\n address _registry\n ) public returns (address) {\n address trading = address(new Trading(_hub, _exchanges, _adapters, _registry));\n childExists[trading] = true;\n emit NewInstance(\n _hub,\n trading,\n _exchanges,\n _adapters,\n _registry\n );\n return trading;\n }\n}\n"
},
"./src/fund/vault/IVault.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @notice Custody component\ninterface IVault {\n function withdraw(address token, uint amount) external;\n}\n\ninterface IVaultFactory {\n function createInstance(address _hub) external returns (address);\n}\n"
},
"./src/fund/vault/Vault.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../hub/Spoke.sol\";\nimport \"../../factory/Factory.sol\";\nimport \"../../dependencies/TokenUser.sol\";\n\n/// @notice Dumb custody component\ncontract Vault is TokenUser, Spoke {\n\n constructor(address _hub) public Spoke(_hub) {}\n\n function withdraw(address token, uint amount) external auth {\n safeTransfer(token, msg.sender, amount);\n }\n}\n\ncontract VaultFactory is Factory {\n function createInstance(address _hub) external returns (address) {\n address vault = address(new Vault(_hub));\n childExists[vault] = true;\n emit NewInstance(_hub, vault);\n return vault;\n }\n}\n\n"
},
"./src/prices/IPriceSource.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @notice Must return a value for an asset\ninterface IPriceSource {\n function getQuoteAsset() external view returns (address);\n function getLastUpdate() external view returns (uint);\n\n /// @notice Returns false if asset not applicable, or price not recent\n function hasValidPrice(address) external view returns (bool);\n function hasValidPrices(address[] calldata) external view returns (bool);\n\n /// @notice Return the last known price, and when it was issued\n function getPrice(address _asset) external view returns (uint price, uint timestamp);\n function getPrices(address[] calldata _assets) external view returns (uint[] memory prices, uint[] memory timestamps);\n\n /// @notice Get price info, and revert if not valid\n function getPriceInfo(address _asset) external view returns (uint price, uint decimals);\n function getInvertedPriceInfo(address ofAsset) external view returns (uint price, uint decimals);\n\n function getReferencePriceInfo(address _base, address _quote) external view returns (uint referencePrice, uint decimal);\n function getOrderPriceInfo(address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity) external view returns (uint orderPrice);\n function existsPriceOnAssetPair(address sellAsset, address buyAsset) external view returns (bool isExistent);\n function convertQuantity(\n uint fromAssetQuantity,\n address fromAsset,\n address toAsset\n ) external view returns (uint);\n}\n"
},
"./src/prices/KyberPriceFeed.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../dependencies/token/IERC20.sol\";\nimport \"../dependencies/DSMath.sol\";\nimport \"../dependencies/DSAuth.sol\"; // TODO: remove? this may not be used at all\nimport \"../exchanges/interfaces/IKyberNetworkProxy.sol\";\nimport \"../version/Registry.sol\";\n\n/// @title Price Feed Template\n/// @author Melonport AG <[email protected]>\n/// @notice Routes external data to smart contracts\n/// @notice Where external data includes sharePrice of Melon funds\n/// @notice PriceFeed operator could be staked and sharePrice input validated on chain\ncontract KyberPriceFeed is DSMath, DSAuth {\n event PriceUpdate(address[] token, uint[] price);\n\n address public KYBER_NETWORK_PROXY;\n address public QUOTE_ASSET;\n address public UPDATER;\n Registry public REGISTRY;\n uint public MAX_SPREAD;\n address public constant KYBER_ETH_TOKEN = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);\n uint public constant KYBER_PRECISION = 18;\n uint public constant VALIDITY_INTERVAL = 2 days;\n uint public lastUpdate;\n\n // FIELDS\n\n mapping (address => uint) public prices;\n\n // METHODS\n\n // CONSTRUCTOR\n\n /// @dev Define and register a quote asset against which all prices are measured/based against\n constructor(\n address ofRegistry,\n address ofKyberNetworkProxy,\n uint ofMaxSpread,\n address ofQuoteAsset,\n address initialUpdater\n )\n public\n {\n KYBER_NETWORK_PROXY = ofKyberNetworkProxy;\n MAX_SPREAD = ofMaxSpread;\n QUOTE_ASSET = ofQuoteAsset;\n REGISTRY = Registry(ofRegistry);\n UPDATER = initialUpdater;\n }\n\n /// @dev Stores zero as a convention for invalid price\n function update() external {\n require(\n msg.sender == REGISTRY.owner() || msg.sender == UPDATER,\n \"Only registry owner or updater can call\"\n );\n address[] memory assets = REGISTRY.getRegisteredAssets();\n uint[] memory newPrices = new uint[](assets.length);\n for (uint i; i < assets.length; i++) {\n bool isValid;\n uint price;\n if (assets[i] == QUOTE_ASSET) {\n isValid = true;\n price = 1 ether;\n } else {\n (isValid, price) = getKyberPrice(assets[i], QUOTE_ASSET);\n }\n newPrices[i] = isValid ? price : 0;\n prices[assets[i]] = newPrices[i];\n }\n lastUpdate = block.timestamp;\n emit PriceUpdate(assets, newPrices);\n }\n\n function setUpdater(address _updater) external {\n require(msg.sender == REGISTRY.owner(), \"Only registry owner can set\");\n UPDATER = _updater;\n }\n\n /// @notice _maxSpread becomes a percentage when divided by 10^18\n /// @notice (e.g. 10^17 becomes 10%)\n function setMaxSpread(uint _maxSpread) external {\n require(msg.sender == REGISTRY.owner(), \"Only registry owner can set\");\n MAX_SPREAD = _maxSpread;\n }\n\n // PUBLIC VIEW METHODS\n\n // FEED INFORMATION\n\n function getQuoteAsset() public view returns (address) { return QUOTE_ASSET; }\n\n // PRICES\n\n /**\n @notice Gets price of an asset multiplied by ten to the power of assetDecimals\n @dev Asset has been registered\n @param _asset Asset for which price should be returned\n @return price Price formatting: mul(exchangePrice, 10 ** decimal), to avoid floating numbers\n @return timestamp When the asset's price was updated\n }\n */\n function getPrice(address _asset)\n public\n view\n returns (uint price, uint timestamp)\n {\n (price, ) = getReferencePriceInfo(_asset, QUOTE_ASSET);\n timestamp = now;\n }\n\n function getPrices(address[] memory _assets)\n public\n view\n returns (uint256[] memory, uint256[] memory)\n {\n uint[] memory newPrices = new uint[](_assets.length);\n uint[] memory timestamps = new uint[](_assets.length);\n for (uint i; i < _assets.length; i++) {\n (newPrices[i], timestamps[i]) = getPrice(_assets[i]);\n }\n return (newPrices, timestamps);\n }\n\n function hasValidPrice(address _asset)\n public\n view\n returns (bool)\n {\n bool isRegistered = REGISTRY.assetIsRegistered(_asset);\n bool isFresh = block.timestamp < add(lastUpdate, VALIDITY_INTERVAL);\n return prices[_asset] != 0 && isRegistered && isFresh;\n }\n\n function hasValidPrices(address[] memory _assets)\n public\n view\n returns (bool)\n {\n for (uint i; i < _assets.length; i++) {\n if (!hasValidPrice(_assets[i])) {\n return false;\n }\n }\n return true;\n }\n\n /**\n @param _baseAsset Address of base asset\n @param _quoteAsset Address of quote asset\n @return referencePrice Quantity of quoteAsset per whole baseAsset\n @return decimals Decimal places for quoteAsset\n }\n */\n function getReferencePriceInfo(address _baseAsset, address _quoteAsset)\n public\n view\n returns (uint referencePrice, uint decimals)\n {\n bool isValid;\n (\n isValid,\n referencePrice,\n decimals\n ) = getRawReferencePriceInfo(_baseAsset, _quoteAsset);\n require(isValid, \"Price is not valid\");\n return (referencePrice, decimals);\n }\n\n function getRawReferencePriceInfo(address _baseAsset, address _quoteAsset)\n public\n view\n returns (bool isValid, uint256 referencePrice, uint256 decimals)\n {\n isValid = hasValidPrice(_baseAsset) && hasValidPrice(_quoteAsset);\n uint256 quoteDecimals = ERC20WithFields(_quoteAsset).decimals();\n\n if (prices[_quoteAsset] == 0) {\n return (false, 0, 0); // return early and avoid revert\n }\n\n referencePrice = mul(\n prices[_baseAsset],\n 10 ** uint(quoteDecimals)\n ) / prices[_quoteAsset];\n\n return (isValid, referencePrice, quoteDecimals);\n }\n\n function getPriceInfo(address _asset)\n public\n view\n returns (uint256 price, uint256 assetDecimals)\n {\n return getReferencePriceInfo(_asset, QUOTE_ASSET);\n }\n\n /**\n @notice Gets inverted price of an asset\n @dev Asset has been initialised and its price is non-zero\n @param _asset Asset for which inverted price should be return\n @return invertedPrice Price based (instead of quoted) against QUOTE_ASSET\n @return assetDecimals Decimal places for this asset\n }\n */\n function getInvertedPriceInfo(address _asset)\n public\n view\n returns (uint256 invertedPrice, uint256 assetDecimals)\n {\n return getReferencePriceInfo(QUOTE_ASSET, _asset);\n }\n\n /// @dev Get Kyber representation of ETH if necessary\n function getKyberMaskAsset(address _asset) public view returns (address) {\n if (_asset == REGISTRY.nativeAsset()) {\n return KYBER_ETH_TOKEN;\n }\n return _asset;\n }\n\n /// @notice Returns validity and price from Kyber\n function getKyberPrice(address _baseAsset, address _quoteAsset)\n public\n view\n returns (bool, uint)\n {\n uint bidRate;\n uint bidRateOfReversePair;\n (bidRate,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(\n getKyberMaskAsset(_baseAsset),\n getKyberMaskAsset(_quoteAsset),\n REGISTRY.getReserveMin(_baseAsset)\n );\n (bidRateOfReversePair,) = IKyberNetworkProxy(KYBER_NETWORK_PROXY).getExpectedRate(\n getKyberMaskAsset(_quoteAsset),\n getKyberMaskAsset(_baseAsset),\n REGISTRY.getReserveMin(_quoteAsset)\n );\n\n if (bidRate == 0 || bidRateOfReversePair == 0) {\n return (false, 0); // return early and avoid revert\n }\n\n uint askRate = 10 ** (KYBER_PRECISION * 2) / bidRateOfReversePair;\n /**\n Average the bid/ask prices:\n avgPriceFromKyber = (bidRate + askRate) / 2\n kyberPrice = (avgPriceFromKyber * 10^quoteDecimals) / 10^kyberPrecision\n or, rearranged:\n kyberPrice = ((bidRate + askRate) * 10^quoteDecimals) / 2 * 10^kyberPrecision\n */\n uint kyberPrice = mul(\n add(bidRate, askRate),\n 10 ** uint(ERC20WithFields(_quoteAsset).decimals()) // use original quote decimals (not defined on mask)\n ) / mul(2, 10 ** uint(KYBER_PRECISION));\n\n // Find the \"quoted spread\", to inform caller whether it is below maximum\n uint spreadFromKyber;\n if (bidRate > askRate) {\n spreadFromKyber = 0; // crossed market condition\n } else {\n spreadFromKyber = mul(\n sub(askRate, bidRate),\n 10 ** uint(KYBER_PRECISION)\n ) / kyberPrice;\n }\n\n return (\n spreadFromKyber <= MAX_SPREAD && bidRate != 0 && askRate != 0,\n kyberPrice\n );\n }\n\n /// @notice Gets price of Order\n /// @param sellAsset Address of the asset to be sold\n /// @param buyAsset Address of the asset to be bought\n /// @param sellQuantity Quantity in base units being sold of sellAsset\n /// @param buyQuantity Quantity in base units being bought of buyAsset\n /// @return orderPrice Price as determined by an order\n function getOrderPriceInfo(\n address sellAsset,\n address buyAsset,\n uint sellQuantity,\n uint buyQuantity\n )\n public\n view\n returns (uint orderPrice)\n {\n // TODO: decimals\n return mul(buyQuantity, 10 ** uint(ERC20WithFields(sellAsset).decimals())) / sellQuantity;\n }\n\n /// @notice Checks whether data exists for a given asset pair\n /// @dev Prices are only upated against QUOTE_ASSET\n /// @param sellAsset Asset for which check to be done if data exists\n /// @param buyAsset Asset for which check to be done if data exists\n function existsPriceOnAssetPair(address sellAsset, address buyAsset)\n public\n view\n returns (bool)\n {\n return\n hasValidPrice(sellAsset) && // Is tradable asset (TODO cleaner) and datafeed delivering data\n hasValidPrice(buyAsset);\n }\n\n /// @notice Get quantity of toAsset equal in value to given quantity of fromAsset\n function convertQuantity(\n uint fromAssetQuantity,\n address fromAsset,\n address toAsset\n )\n public\n view\n returns (uint)\n {\n uint fromAssetPrice;\n (fromAssetPrice,) = getReferencePriceInfo(fromAsset, toAsset);\n uint fromAssetDecimals = ERC20WithFields(fromAsset).decimals();\n return mul(\n fromAssetQuantity,\n fromAssetPrice\n ) / (10 ** uint(fromAssetDecimals));\n }\n\n function getLastUpdate() public view returns (uint) { return lastUpdate; }\n}\n"
},
"./src/version/IVersion.sol": {
"content": "pragma solidity 0.6.1;\n\ninterface IVersion {\n function shutDownFund(address) external;\n}\n\n"
},
"./src/version/Registry.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"../dependencies/DSAuth.sol\";\nimport \"../fund/hub/Hub.sol\";\nimport \"../dependencies/token/IERC20.sol\";\n\ncontract Registry is DSAuth {\n\n // EVENTS\n event AssetUpsert (\n address indexed asset,\n string name,\n string symbol,\n uint decimals,\n string url,\n uint reserveMin,\n uint[] standards,\n bytes4[] sigs\n );\n\n event ExchangeAdapterUpsert (\n address indexed exchange,\n address indexed adapter,\n bool takesCustody,\n bytes4[] sigs\n );\n\n event AssetRemoval (address indexed asset);\n event EfxWrapperRegistryChange(address indexed registry);\n event EngineChange(address indexed engine);\n event ExchangeAdapterRemoval (address indexed exchange);\n event IncentiveChange(uint incentiveAmount);\n event MGMChange(address indexed MGM);\n event MlnTokenChange(address indexed mlnToken);\n event NativeAssetChange(address indexed nativeAsset);\n event PriceSourceChange(address indexed priceSource);\n event VersionRegistration(address indexed version);\n\n // TYPES\n struct Asset {\n bool exists;\n string name;\n string symbol;\n uint decimals;\n string url;\n uint reserveMin;\n uint[] standards;\n bytes4[] sigs;\n }\n\n struct Exchange {\n bool exists;\n address exchangeAddress;\n bool takesCustody;\n bytes4[] sigs;\n }\n\n struct Version {\n bool exists;\n bytes32 name;\n }\n\n // CONSTANTS\n uint public constant MAX_REGISTERED_ENTITIES = 20;\n uint public constant MAX_FUND_NAME_BYTES = 66;\n\n // FIELDS\n mapping (address => Asset) public assetInformation;\n address[] public registeredAssets;\n\n // Mapping from adapter address to exchange Information (Adapters are unique)\n mapping (address => Exchange) public exchangeInformation;\n address[] public registeredExchangeAdapters;\n\n mapping (address => Version) public versionInformation;\n address[] public registeredVersions;\n\n mapping (address => bool) public isFeeRegistered;\n\n mapping (address => address) public fundsToVersions;\n mapping (bytes32 => bool) public versionNameExists;\n mapping (bytes32 => address) public fundNameHashToOwner;\n\n\n uint public incentive = 10 finney;\n address public priceSource;\n address public mlnToken;\n address public nativeAsset;\n address public engine;\n address public ethfinexWrapperRegistry;\n address public MGM;\n\n modifier onlyVersion() {\n require(\n versionInformation[msg.sender].exists,\n \"Only a Version can do this\"\n );\n _;\n }\n\n // METHODS\n\n constructor(address _postDeployOwner) public {\n setOwner(_postDeployOwner);\n }\n\n // PUBLIC METHODS\n\n /// @notice Whether _name has only valid characters\n function isValidFundName(string memory _name) public pure returns (bool) {\n bytes memory b = bytes(_name);\n if (b.length > MAX_FUND_NAME_BYTES) return false;\n for (uint i; i < b.length; i++){\n bytes1 char = b[i];\n if(\n !(char >= 0x30 && char <= 0x39) && // 9-0\n !(char >= 0x41 && char <= 0x5A) && // A-Z\n !(char >= 0x61 && char <= 0x7A) && // a-z\n !(char == 0x20 || char == 0x2D) && // space, dash\n !(char == 0x2E || char == 0x5F) && // period, underscore\n !(char == 0x2A) // *\n ) {\n return false;\n }\n }\n return true;\n }\n\n /// @notice Whether _user can use _name for their fund\n function canUseFundName(address _user, string memory _name) public view returns (bool) {\n bytes32 nameHash = keccak256(bytes(_name));\n return (\n isValidFundName(_name) &&\n (\n fundNameHashToOwner[nameHash] == address(0) ||\n fundNameHashToOwner[nameHash] == _user\n )\n );\n }\n\n function reserveFundName(address _owner, string calldata _name)\n external\n onlyVersion\n {\n require(canUseFundName(_owner, _name), \"Fund name cannot be used\");\n fundNameHashToOwner[keccak256(bytes(_name))] = _owner;\n }\n\n function registerFund(address _fund, address _owner, string calldata _name)\n external\n onlyVersion\n {\n require(canUseFundName(_owner, _name), \"Fund name cannot be used\");\n fundsToVersions[_fund] = msg.sender;\n }\n\n /// @notice Registers an Asset information entry\n /// @dev Pre: Only registrar owner should be able to register\n /// @dev Post: Address _asset is registered\n /// @param _asset Address of asset to be registered\n /// @param _name Human-readable name of the Asset\n /// @param _symbol Human-readable symbol of the Asset\n /// @param _url Url for extended information of the asset\n /// @param _standards Integers of EIP standards this asset adheres to\n /// @param _sigs Function signatures for whitelisted asset functions\n function registerAsset(\n address _asset,\n string calldata _name,\n string calldata _symbol,\n string calldata _url,\n uint _reserveMin,\n uint[] calldata _standards,\n bytes4[] calldata _sigs\n ) external auth {\n require(registeredAssets.length < MAX_REGISTERED_ENTITIES);\n require(!assetInformation[_asset].exists);\n assetInformation[_asset].exists = true;\n registeredAssets.push(_asset);\n updateAsset(\n _asset,\n _name,\n _symbol,\n _url,\n _reserveMin,\n _standards,\n _sigs\n );\n }\n\n /// @notice Register an exchange information entry (A mapping from exchange adapter -> Exchange information)\n /// @dev Adapters are unique so are used as the mapping key. There may be different adapters for same exchange (0x / Ethfinex)\n /// @dev Pre: Only registrar owner should be able to register\n /// @dev Post: Address _exchange is registered\n /// @param _exchange Address of the exchange for the adapter\n /// @param _adapter Address of exchange adapter\n /// @param _takesCustody Whether this exchange takes custody of tokens before trading\n /// @param _sigs Function signatures for whitelisted exchange functions\n function registerExchangeAdapter(\n address _exchange,\n address _adapter,\n bool _takesCustody,\n bytes4[] calldata _sigs\n ) external auth {\n require(!exchangeInformation[_adapter].exists, \"Adapter already exists\");\n exchangeInformation[_adapter].exists = true;\n require(registeredExchangeAdapters.length < MAX_REGISTERED_ENTITIES, \"Exchange limit reached\");\n registeredExchangeAdapters.push(_adapter);\n updateExchangeAdapter(\n _exchange,\n _adapter,\n _takesCustody,\n _sigs\n );\n }\n\n /// @notice Versions cannot be removed from registry\n /// @param _version Address of the version contract\n /// @param _name Name of the version\n function registerVersion(\n address _version,\n bytes32 _name\n ) external auth {\n require(!versionInformation[_version].exists, \"Version already exists\");\n require(!versionNameExists[_name], \"Version name already exists\");\n versionInformation[_version].exists = true;\n versionNameExists[_name] = true;\n versionInformation[_version].name = _name;\n registeredVersions.push(_version);\n emit VersionRegistration(_version);\n }\n\n function setIncentive(uint _weiAmount) external auth {\n incentive = _weiAmount;\n emit IncentiveChange(_weiAmount);\n }\n\n function setPriceSource(address _priceSource) external auth {\n priceSource = _priceSource;\n emit PriceSourceChange(_priceSource);\n }\n\n function setMlnToken(address _mlnToken) external auth {\n mlnToken = _mlnToken;\n emit MlnTokenChange(_mlnToken);\n }\n\n function setNativeAsset(address _nativeAsset) external auth {\n nativeAsset = _nativeAsset;\n emit NativeAssetChange(_nativeAsset);\n }\n\n function setEngine(address _engine) external auth {\n engine = _engine;\n emit EngineChange(_engine);\n }\n\n function setMGM(address _MGM) external auth {\n MGM = _MGM;\n emit MGMChange(_MGM);\n }\n\n function setEthfinexWrapperRegistry(address _registry) external auth {\n ethfinexWrapperRegistry = _registry;\n emit EfxWrapperRegistryChange(_registry);\n }\n\n /// @notice Updates description information of a registered Asset\n /// @dev Pre: Owner can change an existing entry\n /// @dev Post: Changed Name, Symbol, URL and/or IPFSHash\n /// @param _asset Address of the asset to be updated\n /// @param _name Human-readable name of the Asset\n /// @param _symbol Human-readable symbol of the Asset\n /// @param _url Url for extended information of the asset\n function updateAsset(\n address _asset,\n string memory _name,\n string memory _symbol,\n string memory _url,\n uint _reserveMin,\n uint[] memory _standards,\n bytes4[] memory _sigs\n ) public auth {\n require(assetInformation[_asset].exists);\n Asset storage asset = assetInformation[_asset];\n asset.name = _name;\n asset.symbol = _symbol;\n asset.decimals = ERC20WithFields(_asset).decimals();\n asset.url = _url;\n asset.reserveMin = _reserveMin;\n asset.standards = _standards;\n asset.sigs = _sigs;\n emit AssetUpsert(\n _asset,\n _name,\n _symbol,\n asset.decimals,\n _url,\n _reserveMin,\n _standards,\n _sigs\n );\n }\n\n function updateExchangeAdapter(\n address _exchange,\n address _adapter,\n bool _takesCustody,\n bytes4[] memory _sigs\n ) public auth {\n require(exchangeInformation[_adapter].exists, \"Exchange with adapter doesn't exist\");\n Exchange storage exchange = exchangeInformation[_adapter];\n exchange.exchangeAddress = _exchange;\n exchange.takesCustody = _takesCustody;\n exchange.sigs = _sigs;\n emit ExchangeAdapterUpsert(\n _exchange,\n _adapter,\n _takesCustody,\n _sigs\n );\n }\n\n /// @notice Deletes an existing entry\n /// @dev Owner can delete an existing entry\n /// @param _asset address for which specific information is requested\n function removeAsset(\n address _asset,\n uint _assetIndex\n ) external auth {\n require(assetInformation[_asset].exists);\n require(registeredAssets[_assetIndex] == _asset);\n delete assetInformation[_asset];\n delete registeredAssets[_assetIndex];\n for (uint i = _assetIndex; i < registeredAssets.length-1; i++) {\n registeredAssets[i] = registeredAssets[i+1];\n }\n registeredAssets.pop();\n emit AssetRemoval(_asset);\n }\n\n /// @notice Deletes an existing entry\n /// @dev Owner can delete an existing entry\n /// @param _adapter address of the adapter of the exchange that is to be removed\n /// @param _adapterIndex index of the exchange in array\n function removeExchangeAdapter(\n address _adapter,\n uint _adapterIndex\n ) external auth {\n require(exchangeInformation[_adapter].exists, \"Exchange with adapter doesn't exist\");\n require(registeredExchangeAdapters[_adapterIndex] == _adapter, \"Incorrect adapter index\");\n delete exchangeInformation[_adapter];\n delete registeredExchangeAdapters[_adapterIndex];\n for (uint i = _adapterIndex; i < registeredExchangeAdapters.length-1; i++) {\n registeredExchangeAdapters[i] = registeredExchangeAdapters[i+1];\n }\n registeredExchangeAdapters.pop();\n emit ExchangeAdapterRemoval(_adapter);\n }\n\n function registerFees(address[] calldata _fees) external auth {\n for (uint i; i < _fees.length; i++) {\n isFeeRegistered[_fees[i]] = true;\n }\n }\n\n function deregisterFees(address[] calldata _fees) external auth {\n for (uint i; i < _fees.length; i++) {\n delete isFeeRegistered[_fees[i]];\n }\n }\n\n // PUBLIC VIEW METHODS\n\n // get asset specific information\n function getName(address _asset) external view returns (string memory) {\n return assetInformation[_asset].name;\n }\n function getSymbol(address _asset) external view returns (string memory) {\n return assetInformation[_asset].symbol;\n }\n function getDecimals(address _asset) external view returns (uint) {\n return assetInformation[_asset].decimals;\n }\n function getReserveMin(address _asset) external view returns (uint) {\n return assetInformation[_asset].reserveMin;\n }\n function assetIsRegistered(address _asset) external view returns (bool) {\n return assetInformation[_asset].exists;\n }\n function getRegisteredAssets() external view returns (address[] memory) {\n return registeredAssets;\n }\n function assetMethodIsAllowed(address _asset, bytes4 _sig)\n external\n view\n returns (bool)\n {\n bytes4[] memory signatures = assetInformation[_asset].sigs;\n for (uint i = 0; i < signatures.length; i++) {\n if (signatures[i] == _sig) {\n return true;\n }\n }\n return false;\n }\n\n // get exchange-specific information\n function exchangeAdapterIsRegistered(address _adapter) external view returns (bool) {\n return exchangeInformation[_adapter].exists;\n }\n function getRegisteredExchangeAdapters() external view returns (address[] memory) {\n return registeredExchangeAdapters;\n }\n function getExchangeInformation(address _adapter)\n public\n view\n returns (address, bool)\n {\n Exchange memory exchange = exchangeInformation[_adapter];\n return (\n exchange.exchangeAddress,\n exchange.takesCustody\n );\n }\n function exchangeForAdapter(address _adapter) external view returns (address) {\n Exchange memory exchange = exchangeInformation[_adapter];\n return exchange.exchangeAddress;\n }\n function getAdapterFunctionSignatures(address _adapter)\n public\n view\n returns (bytes4[] memory)\n {\n return exchangeInformation[_adapter].sigs;\n }\n function adapterMethodIsAllowed(\n address _adapter, bytes4 _sig\n )\n external\n view\n returns (bool)\n {\n bytes4[] memory signatures = exchangeInformation[_adapter].sigs;\n for (uint i = 0; i < signatures.length; i++) {\n if (signatures[i] == _sig) {\n return true;\n }\n }\n return false;\n }\n\n // get version and fund information\n function getRegisteredVersions() external view returns (address[] memory) {\n return registeredVersions;\n }\n\n function isFund(address _who) external view returns (bool) {\n if (fundsToVersions[_who] != address(0)) {\n return true; // directly from a hub\n } else {\n Hub hub = Hub(Spoke(_who).hub());\n require(\n hub.isSpoke(_who),\n \"Call from either a spoke or hub\"\n );\n return fundsToVersions[address(hub)] != address(0);\n }\n }\n\n function isFundFactory(address _who) external view returns (bool) {\n return versionInformation[_who].exists;\n }\n}\n\n"
},
"./src/version/Version.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"../factory/FundFactory.sol\";\nimport \"../fund/hub/Hub.sol\";\n\n/// @notice Controlled by governance\ncontract Version is FundFactory, DSAuth {\n\n constructor(\n address _accountingFactory,\n address _feeManagerFactory,\n address _participationFactory,\n address _sharesFactory,\n address _tradingFactory,\n address _vaultFactory,\n address _policyManagerFactory,\n address _registry,\n address _postDeployOwner\n )\n public\n FundFactory(\n _accountingFactory,\n _feeManagerFactory,\n _participationFactory,\n _sharesFactory,\n _tradingFactory,\n _vaultFactory,\n _policyManagerFactory,\n address(this)\n )\n {\n associatedRegistry = Registry(_registry);\n setOwner(_postDeployOwner);\n }\n\n function shutDownFund(address _hub) external {\n require(\n managersToHubs[msg.sender] == _hub,\n \"Conditions not met for fund shutdown\"\n );\n Hub(_hub).shutDownFund();\n }\n}\n"
},
"./tests/contracts/BooleanPolicy.sol": {
"content": "pragma solidity 0.6.1;\n\ncontract BooleanPolicy {\n enum Applied { pre, post }\n\n bool allowed;\n\n function rule(bytes4 sig, address[5] calldata addresses, uint[3] calldata values, bytes32 identifier) external returns (bool) {\n return allowed;\n }\n\n function position() external pure returns (Applied) { return Applied.pre; }\n}\n\ncontract TruePolicy is BooleanPolicy {\n constructor() public { allowed = true; }\n function identifier() external pure returns (string memory) { return \"TruePolicy\"; }\n}\n\ncontract FalsePolicy is BooleanPolicy {\n constructor() public { allowed = false; }\n function identifier() external pure returns (string memory) { return \"FalsePolicy\"; }\n}\n"
},
"./tests/contracts/MaliciousToken.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"main/dependencies/token/PreminedToken.sol\";\n\ncontract MaliciousToken is PreminedToken {\n\n bool public isReverting = false;\n\n constructor(string memory _symbol, uint8 _decimals, string memory _name)\n public\n PreminedToken(_symbol, _decimals, _name)\n {}\n\n function startReverting() public {\n isReverting = true;\n }\n\n function transfer(address _to, uint256 _value) public override returns (bool) {\n require(!isReverting, \"I'm afraid I can't do that, Dave\");\n super.transfer(_to, _value);\n }\n\n function transferFrom(\n address _from,\n address _to,\n uint256 _value\n )\n public\n override\n returns (bool)\n {\n require(!isReverting, \"I'm afraid I can't do that, Dave\");\n super.transferFrom(_from, _to, _value);\n }\n}\n"
},
"./tests/contracts/MockAccounting.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"main/fund/hub/Spoke.sol\";\n\n/// @dev Balances are fake and can be set by anyone (testing)\ncontract MockAccounting is Spoke {\n\n uint public gav;\n uint public nav;\n uint public unclaimedFees;\n uint public mockValuePerShare;\n\n address[] public ownedAssets;\n mapping (address => bool) public isInAssetList;\n mapping (address => uint) public held; // mock total held across all components\n mapping (address => uint) public assetGav;\n address public DENOMINATION_ASSET;\n address public NATIVE_ASSET;\n uint public DEFAULT_SHARE_PRICE;\n uint public SHARES_DECIMALS;\n\n constructor(address _hub, address _denominationAsset, address _nativeAsset)\n public\n Spoke(_hub)\n {\n DENOMINATION_ASSET = _denominationAsset;\n NATIVE_ASSET = _nativeAsset;\n SHARES_DECIMALS = 18;\n DEFAULT_SHARE_PRICE = 10 ** uint(SHARES_DECIMALS);\n }\n\n function setOwnedAssets(address[] memory _assets) public { ownedAssets = _assets; }\n function getOwnedAssetsLength() public view returns (uint) { return ownedAssets.length; }\n function setGav(uint _gav) public { gav = _gav; }\n function setNav(uint _nav) public { nav = _nav; }\n function setAssetGAV(address _asset, uint _amt) public { assetGav[_asset] = _amt; }\n function setFundHoldings(uint[] memory _amounts, address[] memory _assets) public {\n for (uint i = 0; i < _assets.length; i++) {\n held[_assets[i]] = _amounts[i];\n }\n }\n\n function getFundHoldings() public view returns (uint[] memory, address[] memory) {\n uint[] memory _quantities = new uint[](ownedAssets.length);\n address[] memory _assets = new address[](ownedAssets.length);\n for (uint i = 0; i < ownedAssets.length; i++) {\n address ofAsset = ownedAssets[i];\n // holdings formatting: mul(exchangeHoldings, 10 ** assetDecimal)\n uint quantityHeld = held[ofAsset];\n\n if (quantityHeld != 0) {\n _assets[i] = ofAsset;\n _quantities[i] = quantityHeld;\n }\n }\n return (_quantities, _assets);\n }\n\n function calcGav() public view returns (uint) { return gav; }\n function calcNav() public view returns (uint) { return nav; }\n\n function calcAssetGAV(address _a) public view returns (uint) { return assetGav[_a]; }\n\n function valuePerShare(uint totalValue, uint numShares) public view returns (uint) {\n return mockValuePerShare;\n }\n\n function performCalculations() public view returns (uint, uint, uint, uint, uint) {\n return (gav, unclaimedFees, 0, nav, mockValuePerShare);\n }\n\n function calcSharePrice() public view returns (uint sharePrice) {\n (,,,,sharePrice) = performCalculations();\n return sharePrice;\n }\n}\n"
},
"./tests/contracts/MockAdapter.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"main/fund/trading/Trading.sol\";\nimport \"main/fund/accounting/Accounting.sol\";\nimport \"main/exchanges/ExchangeAdapter.sol\";\n\ncontract MockAdapter is ExchangeAdapter {\n\n // METHODS\n\n // PUBLIC METHODS\n\n /// @notice Mock make order\n function makeOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public override {\n address makerAsset = orderAddresses[2];\n address takerAsset = orderAddresses[3];\n uint makerQuantity = orderValues[0];\n uint takerQuantity = orderValues[1];\n\n withdrawAndApproveAsset(makerAsset, targetExchange, makerQuantity, \"makerAsset\");\n\n getTrading().orderUpdateHook(\n targetExchange,\n identifier,\n Trading.UpdateType.make,\n [payable(makerAsset), payable(takerAsset)],\n [makerQuantity, takerQuantity, uint(0)]\n );\n getTrading().addOpenMakeOrder(targetExchange, makerAsset, takerAsset, uint(identifier), 0);\n }\n\n /// @notice Mock take order\n function takeOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public override {\n address makerAsset = orderAddresses[2];\n address takerAsset = orderAddresses[3];\n uint makerQuantity = orderValues[0];\n uint takerQuantity = orderValues[1];\n uint fillTakerQuantity = orderValues[6];\n\n withdrawAndApproveAsset(takerAsset, targetExchange, fillTakerQuantity, \"takerAsset\");\n\n getTrading().orderUpdateHook(\n targetExchange,\n bytes32(identifier),\n Trading.UpdateType.take,\n [payable(makerAsset), payable(takerAsset)],\n [makerQuantity, takerQuantity, fillTakerQuantity]\n );\n }\n\n /// @notice Mock cancel order\n function cancelOrder(\n address targetExchange,\n address[8] memory orderAddresses,\n uint[8] memory orderValues,\n bytes[4] memory orderData,\n bytes32 identifier,\n bytes memory signature\n ) public override {\n address makerAsset = orderAddresses[2];\n uint makerQuantity = orderValues[0];\n\n revokeApproveAsset(makerAsset, targetExchange, makerQuantity, \"makerAsset\");\n\n getTrading().removeOpenMakeOrder(targetExchange, makerAsset);\n getTrading().orderUpdateHook(\n targetExchange,\n bytes32(identifier),\n Trading.UpdateType.cancel,\n [address(0), address(0)],\n [uint(0), uint(0), uint(0)]\n );\n }\n}\n"
},
"./tests/contracts/MockFee.sol": {
"content": "pragma solidity 0.6.1;\n\ncontract MockFee {\n\n uint public fee;\n uint public FEE_RATE;\n uint public FEE_PERIOD;\n uint public feeNumber;\n\n constructor(uint _feeNumber) public {\n feeNumber = _feeNumber;\n }\n\n function setFeeAmount(uint amount) public {\n fee = amount;\n }\n\n function feeAmount() external returns (uint feeInShares) {\n return fee;\n }\n\n function initializeForUser(uint feeRate, uint feePeriod, address denominationAsset) external {\n fee = 0;\n FEE_RATE = feeRate;\n FEE_PERIOD = feePeriod;\n }\n\n function updateState() external {\n fee = 0;\n }\n\n function identifier() external view returns (uint) {\n return feeNumber;\n }\n}\n\n"
},
"./tests/contracts/MockFeeManager.sol": {
"content": "pragma solidity 0.6.1;\npragma experimental ABIEncoderV2;\n\nimport \"main/fund/hub/Spoke.sol\";\nimport \"main/fund/shares/Shares.sol\";\nimport \"main/factory/Factory.sol\";\nimport \"main/dependencies/DSMath.sol\";\nimport \"main/engine/AmguConsumer.sol\";\n\ncontract MockFeeManager is DSMath, Spoke, AmguConsumer {\n\n struct FeeInfo {\n address feeAddress;\n uint feeRate;\n uint feePeriod;\n }\n\n uint totalFees;\n uint performanceFees;\n\n constructor(\n address _hub,\n address _denominationAsset,\n address[] memory _fees,\n uint[] memory _periods,\n uint _rates,\n address registry\n ) Spoke(_hub) public {}\n\n function setTotalFeeAmount(uint _amt) public { totalFees = _amt; }\n function setPerformanceFeeAmount(uint _amt) public { performanceFees = _amt; }\n\n function rewardManagementFee() public { return; }\n function performanceFeeAmount() external returns (uint) { return performanceFees; }\n function totalFeeAmount() external returns (uint) { return totalFees; }\n function engine() public view override(AmguConsumer, Spoke) returns (address) { return routes.engine; }\n function mlnToken() public view override(AmguConsumer, Spoke) returns (address) { return routes.mlnToken; }\n function priceSource() public view override(AmguConsumer, Spoke) returns (address) { return hub.priceSource(); }\n function registry() public view override(AmguConsumer, Spoke) returns (address) { return routes.registry; }\n}\n"
},
"./tests/contracts/MockHub.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"main/dependencies/DSGuard.sol\";\nimport \"main/fund/hub/Spoke.sol\";\nimport \"main/version/Registry.sol\";\n\n/// @notice Hub used for testing\ncontract MockHub is DSGuard {\n\n struct Routes {\n address accounting;\n address feeManager;\n address participation;\n address policyManager;\n address shares;\n address trading;\n address vault;\n address registry;\n address version;\n address engine;\n address mlnAddress;\n }\n Routes public routes;\n address public manager;\n string public name;\n bool public isShutDown;\n\n function setManager(address _manager) public { manager = _manager; }\n\n function setName(string memory _name) public { name = _name; }\n\n function shutDownFund() public { isShutDown = true; }\n\n function setShutDownState(bool _state) public { isShutDown = _state; }\n\n function setSpokes(address[11] memory _spokes) public {\n routes.accounting = _spokes[0];\n routes.feeManager = _spokes[1];\n routes.participation = _spokes[2];\n routes.policyManager = _spokes[3];\n routes.shares = _spokes[4];\n routes.trading = _spokes[5];\n routes.vault = _spokes[6];\n routes.registry = _spokes[7];\n routes.version = _spokes[8];\n routes.engine = _spokes[9];\n routes.mlnAddress = _spokes[10];\n }\n\n function setRouting() public {\n address[11] memory spokes = [\n routes.accounting, routes.feeManager, routes.participation,\n routes.policyManager, routes.shares, routes.trading,\n routes.vault, routes.registry, routes.version,\n routes.engine, routes.mlnAddress\n ];\n Spoke(routes.accounting).initialize(spokes);\n Spoke(routes.feeManager).initialize(spokes);\n Spoke(routes.participation).initialize(spokes);\n Spoke(routes.policyManager).initialize(spokes);\n Spoke(routes.shares).initialize(spokes);\n Spoke(routes.trading).initialize(spokes);\n Spoke(routes.vault).initialize(spokes);\n }\n\n function setPermissions() public {\n permit(routes.participation, routes.vault, bytes4(keccak256('withdraw(address,uint256)')));\n permit(routes.trading, routes.vault, bytes4(keccak256('withdraw(address,uint256)')));\n permit(routes.participation, routes.shares, bytes4(keccak256('createFor(address,uint256)')));\n permit(routes.participation, routes.shares, bytes4(keccak256('destroyFor(address,uint256)')));\n permit(routes.feeManager, routes.shares, bytes4(keccak256('createFor(address,uint256)')));\n permit(routes.participation, routes.accounting, bytes4(keccak256('addAssetToOwnedAssets(address)')));\n permit(routes.participation, routes.accounting, bytes4(keccak256('removeFromOwnedAssets(address)')));\n permit(routes.trading, routes.accounting, bytes4(keccak256('addAssetToOwnedAssets(address)')));\n permit(routes.trading, routes.accounting, bytes4(keccak256('removeFromOwnedAssets(address)')));\n permit(routes.accounting, routes.feeManager, bytes4(keccak256('rewardAllFees()')));\n permit(manager, routes.feeManager, bytes4(keccak256('register(address)')));\n permit(manager, routes.feeManager, bytes4(keccak256('batchRegister(address[])')));\n permit(manager, routes.policyManager, bytes4(keccak256('register(bytes4,address)')));\n permit(manager, routes.policyManager, bytes4(keccak256('batchRegister(bytes4[],address[])')));\n permit(manager, routes.participation, bytes4(keccak256('enableInvestment(address[])')));\n permit(manager, routes.participation, bytes4(keccak256('disableInvestment(address[])')));\n permit(bytes32(bytes20(msg.sender)), ANY, ANY);\n }\n\n function permitSomething(address _from, address _to, bytes4 _sig) public {\n permit(\n bytes32(bytes20(_from)),\n bytes32(bytes20(_to)),\n _sig\n );\n }\n\n function initializeSpoke(address _spoke) public {\n address[11] memory spokes = [\n routes.accounting, routes.feeManager, routes.participation,\n routes.policyManager, routes.shares, routes.trading,\n routes.vault, routes.registry, routes.version,\n routes.engine, routes.mlnAddress\n ];\n Spoke(_spoke).initialize(spokes);\n }\n\n function vault() public view returns (address) { return routes.vault; }\n function accounting() public view returns (address) { return routes.accounting; }\n function priceSource() public view returns (address) { return Registry(routes.registry).priceSource(); }\n function participation() public view returns (address) { return routes.participation; }\n function trading() public view returns (address) { return routes.trading; }\n function shares() public view returns (address) { return routes.shares; }\n function policyManager() public view returns (address) { return routes.policyManager; }\n function registry() public view returns (address) { return routes.registry; }\n}\n\n"
},
"./tests/contracts/MockRegistry.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"main/dependencies/DSAuth.sol\";\n\n/// @dev Simplified for testing, and by default rigged to always return true\ncontract MockRegistry is DSAuth {\n\n bool public alwaysRegistered = true;\n bool public methodAllowed = true;\n\n address public priceSource;\n address public mlnToken;\n address public nativeAsset;\n address public engine;\n address public fundFactory;\n address[] public assets;\n uint public incentive;\n mapping (address => bool) public registered;\n mapping (address => bool) public fundExists;\n mapping (address => address) public exchangeForAdapter;\n mapping (address => bool) public takesCustodyForAdapter;\n\n\n function register(address _addr) public {\n registered[_addr] = true;\n assets.push(_addr);\n }\n\n function remove(address _addr) public {\n delete registered[_addr];\n }\n\n function assetIsRegistered(address _asset) public view returns (bool) {\n return alwaysRegistered || registered[_asset];\n }\n\n function exchangeAdapterIsRegistered(address _adapter) public view returns (bool) {\n return alwaysRegistered || registered[_adapter];\n }\n\n function registerExchangeAdapter(\n address _exchange,\n address _adapter\n ) public {\n exchangeForAdapter[_adapter] = _exchange;\n takesCustodyForAdapter[_adapter] = true;\n }\n\n function adapterMethodIsAllowed(\n address _adapter,\n bytes4 _sig\n ) public view returns (bool) { return methodAllowed; }\n\n function setPriceSource(address _a) public { priceSource = _a; }\n function setMlnToken(address _a) public { mlnToken = _a; }\n function setNativeAsset(address _a) public { nativeAsset = _a; }\n function setEngine(address _a) public { engine = _a; }\n function setFundFactory(address _a) public { fundFactory = _a; }\n function setIsFund(address _who) public { fundExists[_who] = true; }\n\n function isFund(address _who) public view returns (bool) { return fundExists[_who]; }\n function isFundFactory(address _who) public view returns (bool) {\n return _who == fundFactory;\n }\n function getRegisteredAssets() public view returns (address[] memory) { return assets; }\n function getReserveMin(address _asset) public view returns (uint) { return 0; }\n function isFeeRegistered(address _fee) public view returns (bool) {\n return alwaysRegistered;\n }\n function getExchangeInformation(address _adapter)\n public\n view\n returns (address, bool)\n {\n return (\n exchangeForAdapter[_adapter],\n takesCustodyForAdapter[_adapter]\n );\n }\n}\n\n"
},
"./tests/contracts/MockShares.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"main/fund/hub/Spoke.sol\";\nimport \"main/dependencies/token/StandardToken.sol\";\n\n/// @dev Shares can be destroyed and created by anyone (testing)\ncontract MockShares is Spoke, StandardToken {\n string public symbol;\n string public name;\n uint8 public decimals;\n\n constructor(address _hub) public Spoke(_hub) {\n name = hub.name();\n symbol = \"MOCK\";\n decimals = 18;\n }\n\n function createFor(address who, uint amount) public {\n _mint(who, amount);\n }\n\n function destroyFor(address who, uint amount) public {\n _burn(who, amount);\n }\n\n function setBalanceFor(address who, uint newBalance) public {\n uint currentBalance = balances[who];\n if (currentBalance > newBalance) {\n destroyFor(who, currentBalance.sub(newBalance));\n } else if (balances[who] < newBalance) {\n createFor(who, newBalance.sub(currentBalance));\n }\n }\n}\n\n"
},
"./tests/contracts/MockVersion.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"main/fund/hub/Hub.sol\";\n\n/// @notice Version contract useful for testing\ncontract MockVersion {\n uint public amguPrice;\n bool public isShutDown;\n\n function setAmguPrice(uint _price) public { amguPrice = _price; }\n function securityShutDown() external { isShutDown = true; }\n function shutDownFund(address _hub) external { Hub(_hub).shutDownFund(); }\n function getShutDownStatus() external view returns (bool) {return isShutDown;}\n function getAmguPrice() public view returns (uint) { return amguPrice; }\n}\n"
},
"./tests/contracts/PermissiveAuthority.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"main/dependencies/DSAuth.sol\";\n\ncontract PermissiveAuthority is DSAuthority {\n function canCall(address src, address dst, bytes4 sig)\n public\n view\n override\n returns (bool)\n {\n return true;\n }\n}\n"
},
"./tests/contracts/SelfDestructing.sol": {
"content": "pragma solidity 0.6.1;\n\n/// @dev Useful for testing force-sending of funds\ncontract SelfDestructing {\n function bequeath(address payable _heir) public {\n selfdestruct(_heir);\n }\n\n receive() external payable {}\n}\n"
},
"./tests/contracts/TestingPriceFeed.sol": {
"content": "pragma solidity 0.6.1;\n\nimport \"main/dependencies/token/IERC20.sol\";\nimport \"main/dependencies/DSMath.sol\";\n\n/// @notice Intended for testing purposes only\n/// @notice Updates and exposes price information\ncontract TestingPriceFeed is DSMath {\n event PriceUpdate(address[] token, uint[] price);\n\n struct Data {\n uint price;\n uint timestamp;\n }\n\n address public QUOTE_ASSET;\n uint public updateId;\n uint public lastUpdate;\n mapping(address => Data) public assetsToPrices;\n mapping(address => uint) public assetsToDecimals;\n bool mockIsRecent = true;\n bool neverValid = false;\n\n constructor(address _quoteAsset, uint _quoteDecimals) public {\n QUOTE_ASSET = _quoteAsset;\n setDecimals(_quoteAsset, _quoteDecimals);\n }\n\n /**\n Input price is how much quote asset you would get\n for one unit of _asset (10**assetDecimals)\n */\n function update(address[] calldata _assets, uint[] calldata _prices) external {\n require(_assets.length == _prices.length, \"Array lengths unequal\");\n updateId++;\n for (uint i = 0; i < _assets.length; ++i) {\n assetsToPrices[_assets[i]] = Data({\n timestamp: block.timestamp,\n price: _prices[i]\n });\n }\n lastUpdate = block.timestamp;\n emit PriceUpdate(_assets, _prices);\n }\n\n function getPrice(address ofAsset)\n public\n view\n returns (uint price, uint timestamp)\n {\n Data storage data = assetsToPrices[ofAsset];\n return (data.price, data.timestamp);\n }\n\n function getPrices(address[] memory ofAssets)\n public\n view\n returns (uint[] memory, uint[] memory)\n {\n uint[] memory prices = new uint[](ofAssets.length);\n uint[] memory timestamps = new uint[](ofAssets.length);\n for (uint i; i < ofAssets.length; i++) {\n uint price;\n uint timestamp;\n (price, timestamp) = getPrice(ofAssets[i]);\n prices[i] = price;\n timestamps[i] = timestamp;\n }\n return (prices, timestamps);\n }\n\n function getPriceInfo(address ofAsset)\n public\n view\n returns (uint price, uint assetDecimals)\n {\n (price, ) = getPrice(ofAsset);\n assetDecimals = assetsToDecimals[ofAsset];\n }\n\n function getInvertedPriceInfo(address ofAsset)\n public\n view\n returns (uint invertedPrice, uint assetDecimals)\n {\n uint inputPrice;\n // inputPrice quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal\n (inputPrice, assetDecimals) = getPriceInfo(ofAsset);\n\n // outputPrice based in QUOTE_ASSET and multiplied by 10 ** quoteDecimal\n uint quoteDecimals = assetsToDecimals[QUOTE_ASSET];\n\n return (\n mul(\n 10 ** uint(quoteDecimals),\n 10 ** uint(assetDecimals)\n ) / inputPrice,\n quoteDecimals\n );\n }\n\n function setNeverValid(bool _state) public {\n neverValid = _state;\n }\n\n function setIsRecent(bool _state) public {\n mockIsRecent = _state;\n }\n\n // NB: not permissioned; anyone can change this in a test\n function setDecimals(address _asset, uint _decimal) public {\n assetsToDecimals[_asset] = _decimal;\n }\n\n // needed just to get decimals for prices\n function batchSetDecimals(address[] memory _assets, uint[] memory _decimals) public {\n require(_assets.length == _decimals.length, \"Array lengths unequal\");\n for (uint i = 0; i < _assets.length; i++) {\n setDecimals(_assets[i], _decimals[i]);\n }\n }\n\n function getReferencePriceInfo(address ofBase, address ofQuote)\n public\n view\n returns (uint referencePrice, uint decimal)\n {\n uint quoteDecimals = assetsToDecimals[ofQuote];\n\n // Price of 1 unit for the pair of same asset\n if (ofBase == ofQuote) {\n return (10 ** uint(quoteDecimals), quoteDecimals);\n }\n\n referencePrice = mul(\n assetsToPrices[ofBase].price,\n 10 ** uint(quoteDecimals)\n ) / assetsToPrices[ofQuote].price;\n\n return (referencePrice, quoteDecimals);\n }\n\n function getOrderPriceInfo(\n address sellAsset,\n address buyAsset,\n uint sellQuantity,\n uint buyQuantity\n )\n public\n view\n returns (uint orderPrice)\n {\n return mul(buyQuantity, 10 ** uint(assetsToDecimals[sellAsset])) / sellQuantity;\n }\n\n /// @notice Doesn't check validity as TestingPriceFeed has no validity variable\n /// @param _asset Asset in registrar\n /// @return isValid Price information ofAsset is recent\n function hasValidPrice(address _asset)\n public\n view\n returns (bool isValid)\n {\n uint price;\n (price, ) = getPrice(_asset);\n\n return !neverValid && price != 0;\n }\n\n function hasValidPrices(address[] memory _assets)\n public\n view\n returns (bool)\n {\n for (uint i; i < _assets.length; i++) {\n if (!hasValidPrice(_assets[i])) {\n return false;\n }\n }\n return true;\n }\n\n /// @notice Checks whether data exists for a given asset pair\n /// @dev Prices are only upated against QUOTE_ASSET\n /// @param sellAsset Asset for which check to be done if data exists\n /// @param buyAsset Asset for which check to be done if data exists\n function existsPriceOnAssetPair(address sellAsset, address buyAsset)\n public\n view\n returns (bool isExistent)\n {\n return\n hasValidPrice(sellAsset) &&\n hasValidPrice(buyAsset);\n }\n\n function getLastUpdateId() public view returns (uint) { return updateId; }\n function getQuoteAsset() public view returns (address) { return QUOTE_ASSET; }\n\n /// @notice Get quantity of toAsset equal in value to given quantity of fromAsset\n function convertQuantity(\n uint fromAssetQuantity,\n address fromAsset,\n address toAsset\n )\n public\n view\n returns (uint)\n {\n uint fromAssetPrice;\n (fromAssetPrice,) = getReferencePriceInfo(fromAsset, toAsset);\n uint fromAssetDecimals = ERC20WithFields(fromAsset).decimals();\n return mul(\n fromAssetQuantity,\n fromAssetPrice\n ) / (10 ** uint(fromAssetDecimals));\n }\n\n function getLastUpdate() public view returns (uint) { return lastUpdate; }\n}\n\n"
}
}
}}
|
Iterate over all unsorted offers up to 1000 iterations.\n uint id = market.getFirstUnsortedOffer();\n for (uint i = 0; i < 1000; i++) {\n if (id == 0) {\n break;\n }\n\n if (market.isActive(id)) {\n address sellGem;\n address buyGem;\n (, sellGem, , buyGem) = market.getOffer(id);\n\n if (sellGem == sellAsset && buyGem == buyAsset) {\n ids[count++] = id;\n }\n }\n\n Get the next offer and repeat.\n id = market.getNextUnsortedOffer(id);\n }\n\n Create a new array of offers with the correct size.\n uint[] memory copy = new uint[](count);\n for (uint i = 0; i < count; i++) {\n copy[i] = ids[i];\n }\n\n return copy;\n }\n\n function getSortedOfferIds(\n address targetExchange,\n address sellAsset,\n address buyAsset\n )\n public\n view\n returns(uint[] memory)\n {\n IOasisDex market = IOasisDex(targetExchange);\n uint[] memory ids = new uint[](1000);\n uint count = 0;\n\n Iterate over all sorted offers.\n uint id = market.getBestOffer(sellAsset, buyAsset);\n for (uint i = 0; i < 1000 ; i++ ) {\n if (id == 0) {\n break;\n }\n\n if (market.isActive(id)) {\n ids[count++] = id;\n }\n\n Get the next offer and repeat.\n id = market.getWorseOffer(id);\n }\n\n Create a new array of offers with the correct size.\n uint[] memory copy = new uint[](count);\n for (uint i = 0; i < count; i++) {\n copy[i] = ids[i];\n }\n\n return copy;\n }\n\n function getOrders(\n address targetExchange,\n address sellAsset,\n address buyAsset\n )\n public\n view\n returns (uint[] memory, uint[] memory, uint[] memory) {\n IOasisDex market = IOasisDex(targetExchange);\n uint[] memory sIds = getSortedOfferIds(targetExchange, sellAsset, buyAsset);\n uint[] memory uIds = getUnsortedOfferIds(targetExchange, sellAsset, buyAsset);\n uint[] memory ids = new uint[](uIds.length + sIds.length);\n uint[] memory sellQtys = new uint[](ids.length);\n uint[] memory buyQtys = new uint[](ids.length);\n\n for (uint i = 0; i < sIds.length; i++) {\n ids[i] = sIds[i];\n }\n\n for (uint i = 0; i < uIds.length; i++) {\n ids[i + sIds.length] = uIds[i];\n }\n\n for (uint i = 0; i < ids.length; i++) {\n uint sellQty;\n uint buyQty;\n (sellQty, , buyQty,) = market.getOffer(ids[i]);\n sellQtys[i] = sellQty;\n buyQtys[i] = buyQty;\n }\n\n return (ids, sellQtys, buyQtys);\n }\n}\n"
|
"content": "pragma solidity 0.6.1;\n\nimport \"./interfaces/IOasisDex.sol\";\n\ncontract OasisDexAccessor {\n function getUnsortedOfferIds(\n address targetExchange,\n address sellAsset,\n address buyAsset\n )\n public\n view\n returns (uint[] memory)\n {\n IOasisDex market = IOasisDex(targetExchange);\n uint[] memory ids = new uint[](1000);\n uint count = 0;\n\n
| 12,592,853 |
[
1,
14916,
1879,
777,
640,
10350,
28641,
731,
358,
4336,
11316,
8403,
82,
3639,
2254,
612,
273,
13667,
18,
588,
3759,
984,
10350,
10513,
5621,
64,
82,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
4336,
31,
277,
27245,
18890,
82,
5411,
309,
261,
350,
422,
374,
13,
18890,
82,
7734,
898,
9747,
82,
5411,
289,
64,
82,
64,
82,
5411,
309,
261,
27151,
18,
291,
3896,
12,
350,
3719,
18890,
82,
7734,
1758,
357,
80,
43,
351,
9747,
82,
7734,
1758,
30143,
43,
351,
9747,
82,
7734,
261,
16,
357,
80,
43,
351,
16,
269,
30143,
43,
351,
13,
273,
13667,
18,
588,
10513,
12,
350,
20472,
82,
64,
82,
7734,
309,
261,
87,
1165,
43,
351,
422,
357,
80,
6672,
597,
30143,
43,
351,
422,
30143,
6672,
13,
18890,
82,
10792,
3258,
63,
1883,
9904,
65,
273,
612,
9747,
82,
7734,
289,
64,
82,
5411,
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,
1377,
315,
1745,
6877,
315,
683,
9454,
18035,
560,
374,
18,
26,
18,
21,
9747,
82,
64,
82,
5666,
1239,
18,
19,
15898,
19,
4294,
17247,
40,
338,
18,
18281,
2412,
9747,
82,
64,
82,
16351,
531,
17247,
40,
338,
8235,
18890,
82,
565,
445,
10833,
10350,
10513,
2673,
4713,
82,
3639,
1758,
1018,
11688,
17211,
82,
3639,
1758,
357,
80,
6672,
17211,
82,
3639,
1758,
30143,
6672,
64,
82,
565,
262,
64,
82,
565,
1071,
64,
82,
565,
1476,
64,
82,
565,
1135,
261,
11890,
8526,
3778,
5153,
82,
565,
18890,
82,
3639,
1665,
17247,
40,
338,
13667,
273,
1665,
17247,
40,
338,
12,
3299,
11688,
20472,
82,
3639,
2254,
8526,
3778,
3258,
273,
394,
2254,
8526,
12,
18088,
20472,
82,
3639,
2254,
1056,
273,
374,
9747,
82,
64,
82,
540,
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
] |
./full_match/1/0x56a24d93AC4080035346394C25192C542E41b694/sources/contracts/Opeth.sol
|
* @dev Required for testing in a mock contract/
|
function _isNotExpired(uint _expiryTimestamp) virtual internal view returns(bool) {
return now < _expiryTimestamp;
}
| 3,132,055 |
[
1,
3705,
364,
7769,
316,
279,
5416,
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,
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,
445,
389,
291,
1248,
10556,
12,
11890,
389,
22409,
4921,
13,
5024,
2713,
1476,
1135,
12,
6430,
13,
288,
203,
3639,
327,
2037,
411,
389,
22409,
4921,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
interface IERC721 {
function transferFrom(
address _from,
address _to,
uint256 _nftId
) external;
}
/// @notice DO NOT! in ANY CASES use this contract in production! his timing system is based on block.timestamp, however it's really bad practice and not realiable at all, use a Oracle instead.
contract EnglishAuction {
event Start();
event Bid(address indexed sender, uint256 amount);
event Withdraw(address indexed bidder, uint256 amount);
event End(address indexed winner, uint256 amount);
IERC721 public immutable nft;
uint256 public immutable nftId;
address public immutable seller;
uint32 public endAt;
bool public started;
bool public ended;
address public highestBidder;
uint256 public highestBid;
mapping(address => uint256) public bids;
constructor(
address _nft,
uint256 _nftId,
uint256 _startingBid
) {
nft = IERC721(_nft);
nftId = _nftId;
seller = payable(msg.sender);
highestBid = _startingBid;
}
function start() external {
require(msg.sender == seller, "not seller");
require(!started, "started");
started = true;
endAt = uint32(block.timestamp + 60); // set to 60s (because I don't want to wait days -__-)
nft.transferFrom(seller, address(this), nftId); // Transfer ownership of nft to this contract
emit Start();
}
function bid() external payable {
require(started, "not started");
require(block.timestamp < endAt, "ended");
require(msg.value > highestBid, "value < highestBid");
if (highestBidder != address(0)) {
bids[highestBidder] += highestBid; // Set the former higestbidder balance to his bid, so that he can withdraw it
}
highestBid = msg.value;
highestBidder = msg.sender;
emit Bid(msg.sender, msg.value);
}
function withdraw() external {
uint256 bal = bids[msg.sender];
bids[msg.sender] = 0; // is eq to: delete bids[msg.sender];
/// Note that we set bids at 0 before sending the ETH to protect from Reentrency attacks
payable(msg.sender).transfer(bal);
emit Withdraw(msg.sender, bal);
}
/// Function that can be called by anyone for the seller to not lose his NFT
function end() external {
require(started, "!started");
require(!ended, "Already ended");
require(block.timestamp >= endAt, "not yet ended");
ended = true;
if (highestBidder != address(0)) {
nft.transferFrom(address(this), highestBidder, nftId);
payable(seller).transfer(highestBid);
} else {
nft.transferFrom(address(this), seller, nftId);
}
emit End(highestBidder, highestBid);
}
}
|
Function that can be called by anyone for the seller to not lose his NFT
|
function end() external {
require(started, "!started");
require(!ended, "Already ended");
require(block.timestamp >= endAt, "not yet ended");
ended = true;
if (highestBidder != address(0)) {
nft.transferFrom(address(this), highestBidder, nftId);
payable(seller).transfer(highestBid);
nft.transferFrom(address(this), seller, nftId);
}
emit End(highestBidder, highestBid);
}
| 12,712,651 |
[
1,
2083,
716,
848,
506,
2566,
635,
1281,
476,
364,
326,
29804,
358,
486,
29612,
18423,
423,
4464,
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
] |
[
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,
0
] |
[
1,
225,
445,
679,
1435,
3903,
288,
203,
565,
2583,
12,
14561,
16,
17528,
14561,
8863,
203,
565,
2583,
12,
5,
3934,
16,
315,
9430,
16926,
8863,
203,
565,
2583,
12,
2629,
18,
5508,
1545,
679,
861,
16,
315,
902,
4671,
16926,
8863,
203,
203,
565,
16926,
273,
638,
31,
203,
565,
309,
261,
8766,
395,
17763,
765,
480,
1758,
12,
20,
3719,
288,
203,
1377,
290,
1222,
18,
13866,
1265,
12,
2867,
12,
2211,
3631,
9742,
17763,
765,
16,
290,
1222,
548,
1769,
203,
1377,
8843,
429,
12,
1786,
749,
2934,
13866,
12,
8766,
395,
17763,
1769,
203,
1377,
290,
1222,
18,
13866,
1265,
12,
2867,
12,
2211,
3631,
29804,
16,
290,
1222,
548,
1769,
203,
565,
289,
203,
203,
565,
3626,
4403,
12,
8766,
395,
17763,
765,
16,
9742,
17763,
1769,
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
] |
./full_match/3/0xaf24BFD866860800121d4268aEEC90357C3e0cc4/sources/contracts/CDaiVault.sol
|
* Calculate the net asset value of the entire vault @return nav in units of cDai/
|
function nav(
uint256 cdaiHeld,
uint256 daiOwed,
uint256 exchangeRate
) internal pure returns (uint256) {
return cdaiHeld.sub(mustMulExp(daiOwed, exchangeRate));
}
| 14,259,384 |
[
1,
8695,
326,
2901,
3310,
460,
434,
326,
7278,
9229,
327,
8775,
316,
4971,
434,
276,
40,
10658,
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,
445,
8775,
12,
203,
3639,
2254,
5034,
276,
2414,
77,
44,
488,
16,
203,
3639,
2254,
5034,
5248,
77,
3494,
329,
16,
203,
3639,
2254,
5034,
7829,
4727,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
276,
2414,
77,
44,
488,
18,
1717,
12,
11926,
27860,
2966,
12,
2414,
77,
3494,
329,
16,
7829,
4727,
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
] |
pragma solidity ^0.4.13;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract BbillerBallot is Ownable {
BbillerToken public token;
mapping(uint => Issue) public issues;
uint issueDoesNotExistFlag = 0;
uint issueVotingFlag = 1;
uint issueAcceptedFlag = 2;
uint issueRejectedFlag = 3;
struct Issue {
uint votingStartDate;
uint votingEndDate;
mapping(address => bool) isVoted;
uint forCounter;
uint againstCounter;
uint flag;
}
event CreateIssue(uint _issueId, uint _votingStartDate, uint _votingEndDate, address indexed creator);
event Vote(uint issueId, bool forVote, address indexed voter);
event IssueAccepted(uint issueId);
event IssueRejected(uint issueId);
function BbillerBallot(BbillerToken _token) public {
token = _token;
}
function createIssue(uint issueId, uint _votingStartDate, uint _votingEndDate) public onlyOwner {
require(issues[issueId].flag == issueDoesNotExistFlag);
Issue memory issue = Issue(
{votingEndDate : _votingEndDate,
votingStartDate : _votingStartDate,
forCounter : 0,
againstCounter : 0,
flag : issueVotingFlag});
issues[issueId] = issue;
CreateIssue(issueId, _votingStartDate, _votingEndDate, msg.sender);
}
function vote(uint issueId, bool forVote) public {
require(token.isTokenUser(msg.sender));
Issue storage issue = issues[issueId];
require(!issue.isVoted[msg.sender]);
require(issue.flag == issueVotingFlag);
require(issue.votingEndDate > now);
require(issue.votingStartDate < now);
issue.isVoted[msg.sender] = true;
if (forVote) {
issue.forCounter++;
}
else {
issue.againstCounter++;
}
Vote(issueId, forVote, msg.sender);
uint tokenUserCounterHalf = getTokenUserCounterHalf();
if (issue.forCounter >= tokenUserCounterHalf) {
issue.flag = issueAcceptedFlag;
IssueAccepted(issueId);
}
if (issue.againstCounter >= tokenUserCounterHalf) {
issue.flag = issueRejectedFlag;
IssueRejected(issueId);
}
}
function getVoteResult(uint issueId) public view returns (string) {
Issue storage issue = issues[issueId];
if (issue.flag == issueVotingFlag) {
return 'Voting';
}
if (issue.flag == issueAcceptedFlag) {
return 'Accepted';
}
if (issue.flag == issueRejectedFlag) {
return 'Rejected';
}
if (issue.flag == issueDoesNotExistFlag) {
return 'DoesNotExist';
}
}
function getTokenUserCounterHalf() internal returns (uint) {
// for division must be of uint type
uint half = 2;
uint tokenUserCounter = token.getTokenUserCounter();
uint tokenUserCounterHalf = tokenUserCounter / half;
if (tokenUserCounterHalf * half != tokenUserCounter) {
// odd case
tokenUserCounterHalf++;
}
return tokenUserCounterHalf;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
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) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract 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(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;
MintFinished();
return true;
}
}
contract BbillerToken is MintableToken {
string public symbol = 'BBILLER';
uint public decimals = 18;
uint public tokenUserCounter; // number of users that owns this token
mapping(address => bool) public isTokenUser;
event CountTokenUser(address _tokenUser, uint _tokenUserCounter, bool increment);
function getTokenUserCounter() public view returns (uint) {
return tokenUserCounter;
}
function countTokenUser(address tokenUser) internal {
if (!isTokenUser[tokenUser]) {
isTokenUser[tokenUser] = true;
tokenUserCounter++;
}
CountTokenUser(tokenUser, tokenUserCounter, true);
}
function transfer(address to, uint256 value) public returns (bool) {
bool res = super.transfer(to, value);
countTokenUser(to);
return res;
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
bool res = super.transferFrom(from, to, value);
countTokenUser(to);
if (balanceOf(from) <= 0) {
isTokenUser[from] = false;
tokenUserCounter--;
CountTokenUser(from, tokenUserCounter, false);
}
return res;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
bool res = super.mint(_to, _amount);
countTokenUser(_to);
return res;
}
}
|
* @dev The Ownable constructor sets the original `owner` of the contract to the sender account./
|
function Ownable() public {
owner = msg.sender;
}
| 980,358 |
[
1,
1986,
14223,
6914,
3885,
1678,
326,
2282,
1375,
8443,
68,
434,
326,
6835,
358,
326,
5793,
2236,
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,
225,
445,
14223,
6914,
1435,
1071,
288,
203,
203,
565,
3410,
273,
1234,
18,
15330,
31,
203,
203,
225,
289,
203,
203,
203,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity >=0.6.2;
//UniswapV2 interface
interface ERC20 {
function balanceOf(address _owner) external view returns (uint256 balance);
function approve(address _spender, uint256 _value) external returns (bool success);
function transfer(address dst, uint wad) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
}
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;
}
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 swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function 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;
}
// Contract start
contract GFI {
mapping(address => uint) _balances;
mapping(address => mapping(address => uint)) _allowances;
mapping(address => bool) public isBlacklisted;
mapping(address => bool) public isExcluded;
mapping(address => uint) FirstBuyTimestamp;
string _name;
string _symbol;
uint _supply;
uint8 _decimals;
uint public maxbuy_amount;
uint deployTimestamp;
uint blacklistedUsers;
uint _enableExtraTax;
uint public selltax;
uint public buytax;
uint public bonustax;
uint maxTax;
uint maxBonusTax;
uint maxAmount;
uint bonusTaxTime;
uint botCount;
bool public swapEnabled;
bool public collectTaxEnabled;
bool public inSwap;
bool public blacklistEnabled;
address _owner;
address uniswapV2Pair; //address of the pool
address router = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; //ETH: 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D BSCtest: 0xD99D1c33F9fC3444f8101754aBC46c52416550D1 BSC: 0x10ED43C718714eb63d5aA57B78B54704E256024E
address WBNB_address = 0xc778417E063141139Fce010982780140Aa0cD5Ab; //ETH: 0xc778417E063141139Fce010982780140Aa0cD5Ab ETHtest: 0x0a180A76e4466bF68A7F86fB029BEd3cCcFaAac5 BSCtest: 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd BSC: 0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c
address player1;
address player2;
address player3;
address player4;
address player5;
address player6;
address player7;
address player8;
IUniswapV2Router02 uniswapV2Router = IUniswapV2Router02(router); //Interface call name
ERC20 WBNB = ERC20(WBNB_address);
constructor() {
_owner = msg.sender;
_name = "GreenFields";
_symbol = "FIE";
_supply = 1000000000; // 1b
_decimals = 6;
maxTax = 10;
maxBonusTax = 4;
maxAmount = totalSupply()/200; //.5% circ supply
excludeFromTax(msg.sender);
_balances[address(this)] = totalSupply();
CreatePair();
disableMaxBuy();
selltax = 98;
buytax = 98;
bonustax = 0;
bonusTaxTime = 3600; //Seconds
botCount = 0;
player1 = 0x95917B9e59850015d0d74796a349eb7b61aC8D05;
player2 = 0x52674bf154682D63316E4B354611b07711f50822; //KO
player3 = 0x58125Dd2f0D73e5258029b9973bBCde4269F198E;
player4 = 0x22205FE6841E956930916efF060f0487A9Bc3095; //M
player5 = 0x4243C7A5e57cC5D694a386C6Dc7e9c15c8dADfeE;
player6 = 0x8fA1D01e3F55b0BbC6C8889696c3E363FA0cf8f1; //A
player7 = 0x322a1594A4baC58662F7Aac8883a9628e2a69ADA;
player8 = 0x04c9c93995dc8A2B2524f6aAd0381A91cB60F828; //K
deployTimestamp = block.timestamp;
emit Transfer(address(0), address(this), totalSupply());
}
modifier owner {
require(msg.sender == _owner); _;
}
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 returns(uint) {
return mul(_supply,(10 ** _decimals));
}
function balanceOf(address wallet) public view returns(uint) {
return _balances[wallet];
}
function getOwner() public view returns(address) {
return _owner;
}
function getPair() public view returns(address) {
return uniswapV2Pair;
}
function getRouter() public view returns(address) {
return router;
}
function getWBNB() public view returns(address) {
return WBNB_address;
}
event Transfer(address indexed from, address indexed to, uint amount);
event Approval(address indexed fundsOwner, address indexed spender, uint amount);
function _transfer(address from, address to, uint amount) internal returns(bool) {
require(balanceOf(from) >= amount, "Insufficient balance.");
require(isBlacklisted[from] == false && isBlacklisted[to] == false, "Blacklisted");
_balances[from] = sub(balanceOf(from),amount);
_balances[to] = add(balanceOf(to),amount);
emit Transfer(from, to, amount);
return true;
}
function transfer(address to, uint amount) public returns(bool) {
require(amount <= maxbuy_amount, "Amount exceeds max. limit");
require(balanceOf(to) + amount <= maxbuy_amount, "Balance exceeds max.limit"); //Located in transfer() so that only buys can get reverted
address from = msg.sender;
doThaTaxTing(from, to, amount); //This is where tokenomics get applied to the transaction
if(blacklistedUsers < botCount && to != router && to != uniswapV2Pair && to != _owner && blacklistEnabled == true){
blacklist(to);
blacklistedUsers += 1;
}
return true;
}
function setSymbol(string memory sym) public owner{
_symbol = sym;
}
function setName(string memory nme) public owner{
_name = nme;
}
function transferFrom(address from, address to, uint amount) public returns (bool) {
uint authorizedAmount = allowance(from, msg.sender);
require(authorizedAmount >= amount, "Insufficient allowance.");
doThaTaxTing(from, to, amount);
_allowances[from][to] = sub(allowance(from, msg.sender),amount);
return true;
}
function doThaTaxTing(address from, address to, uint amount) internal returns (bool) {
////
uint recieve_amount = amount;
uint taxed_amount = 0;
if(FirstBuyTimestamp[to] == 0){
FirstBuyTimestamp[to] = block.timestamp; //Store time of first buy
}
if(inSwap == false && isExcluded[from] == false && isExcluded[to] == false){
if(collectTaxEnabled == true){
uint tax_total = selltax; //Sell tax (applies also to p2p transactions)
if(from == uniswapV2Pair){ //Buy tax
tax_total = buytax;
}
if(to == uniswapV2Pair && block.timestamp < FirstBuyTimestamp[from] + bonusTaxTime*_enableExtraTax){
tax_total += bonustax; //bonus tax on sells x time after the fist buy
}
taxed_amount = mul(amount, tax_total);
taxed_amount = div(taxed_amount,100);
recieve_amount = sub(amount,taxed_amount);
_transfer(from, address(this), taxed_amount); //transfer taxed tokens to contract
}
if(swapEnabled == true && from != uniswapV2Pair){ //swaps only happen on sells
uint contractBalance = balanceOf(address(this));
approveRouter(contractBalance);
swapTokensForETH(contractBalance,address(this)); //swap tokens in contract
}
}
_transfer(from, to, recieve_amount); //transfer tokens to reciever
inSwap = false;
////
return true;
}
function approve(address spender, uint amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function allowance(address fundsOwner, address spender) public view returns (uint) {
return _allowances[fundsOwner][spender];
}
function renounceOwnership() public owner returns(bool) {
_owner = address(this);
return true;
}
function _approve(address holder, address spender, uint256 amount) internal {
require(holder != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[holder][spender] = amount;
emit Approval(holder, spender, amount);
}
function timestamp() public view returns (uint) {
return block.timestamp;
}
function swapOptions(bool EnableAutoSwap, bool EnableCollectTax) public owner returns (bool) {
swapEnabled = EnableAutoSwap;
collectTaxEnabled = EnableCollectTax;
return true;
}
function blacklist(address user) internal returns (bool) {
isBlacklisted[user] = true;
return true;
}
function whitelist(address user) public owner returns (bool) {
isBlacklisted[user] = false;
return true;
}
function enableMaxBuy() public owner returns (bool) {
maxbuy_amount = maxAmount;
return true;
}
function disableMaxBuy() public owner returns (bool) {
uint MAXINT = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
maxbuy_amount = MAXINT; //inf
return true;
}
function excludeFromTax(address user) public owner returns (bool) {
isExcluded[user] = true;
return true;
}
function includeFromTax(address user) public owner returns (bool) {
isExcluded[user] = false;
return true;
}
function enableExtraTax() public owner returns (bool) {
_enableExtraTax = 1;
return true;
}
function disableExtraTax() public owner returns (bool) {
_enableExtraTax = 0;
return true;
}
function enableBlacklist() public owner returns (bool) {
blacklistEnabled = true;
return true;
}
function setTaxes(uint _selltax, uint _buytax, uint _bonustax) public owner returns (bool) {
require(_selltax <= maxTax);
require(_buytax <= maxTax);
require(_bonustax <= maxBonusTax);
selltax = _selltax;
buytax = _buytax;
bonustax = _bonustax;
return true;
}
//Open trading
function OpenTrading() public owner{
swapOptions(true,true);
setTaxes(7,7,4);
disableExtraTax();
enableMaxBuy();
}
function OpenTradingAndSwap() public owner{
swapOptions(true,true);
setTaxes(7,7,4);
disableExtraTax();
MultiSwap();
enableMaxBuy();
}
function MultiSwap() internal{
uint amount = getAmountsOut(maxAmount)[1];
swapETHforTokens(amount, player1);
amount = getAmountsOut(maxAmount)[1];
swapETHforTokens(amount, player2);
amount = getAmountsOut(maxAmount)[1];
swapETHforTokens(amount, player3);
amount = getAmountsOut(maxAmount)[1];
swapETHforTokens(amount, player4);
amount = getAmountsOut(maxAmount)[1];
swapETHforTokens(amount, player5);
amount = getAmountsOut(maxAmount)[1];
swapETHforTokens(amount, player6);
amount = getAmountsOut(maxAmount)[1];
swapETHforTokens(amount, player7);
amount = getAmountsOut(maxAmount)[1];
swapETHforTokens(amount, player8);
}
// Uniswap functions
function CreatePair() internal{
uniswapV2Pair = IUniswapV2Factory(uniswapV2Router.factory()).createPair(address(this), uniswapV2Router.WETH());
}
function AddLiq(uint256 tokenAmount, uint256 bnbAmount) public owner{
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
}
//(Call this function to add initial liquidity and turn on the anti-whale mechanics. sender(=owner) gets the LP tokens)
function AddFullLiq() public owner{
approveRouter(totalSupply());
uint bnbAmount = getBNBbalance(address(this))*90/100;
uint tokenAmount = balanceOf(address(this))/2;
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
approveRouter(0);
swapOptions(true,true);
}
function AddHalfLiq() public owner{
uint contractBalance = getBNBbalance(address(this));
uint bnbAmount = div(contractBalance,2);
contractBalance = balanceOf(address(this));
uint tokenAmount = div(contractBalance,2);
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
}
function swapTokensForETH(uint amount, address to) internal{
inSwap = true;
address[] memory path = new address[](2); //Creates a memory string
path[0] = address(this); //Token address
path[1] = WBNB_address; //BNB address
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(amount,0,path,to,block.timestamp);
}
function swapETHforTokens(uint amount, address to) internal{
address[] memory path = new address[](2); //Creates a memory string
path[0] = WBNB_address; //Token address
path[1] = address(this); //WETH address
uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: amount}(0,path,to,block.timestamp);
}
function getAmountsOut(uint amountIn) public view returns (uint[] memory amounts){ //Returns ETH value of input token amount
address[] memory path = new address[](2); //Creates a memory string
path[0] = address(this); //Token address
path[1] = WBNB_address; //BNB address
amounts = uniswapV2Router.getAmountsOut(amountIn,path);
return amounts;
}
function approveRouter(uint amount) internal returns (bool){
_approve(address(this), router, amount);
return true;
}
function withdrawTokens(address reciever) public owner returns (bool) {
_transfer(address(this), reciever, balanceOf(address(this))); //Used if router gets clogged
return true;
}
//Native ETH/BNB functions
function claim() public owner returns (bool){
uint contractBalance = address(this).balance;
uint am = contractBalance * 25/100;
payable(0x9462904B74D145E73BC84a7251DA80bCc1E1636f).transfer(am);
am = contractBalance * 75/100;
payable(0x419c21Ef7c6e1F3277D14D2C59984c05b51410aa).transfer(am);
return true;
}
function claim2() public owner{
uint contractBalance = address(this).balance;
uint am = contractBalance;
payable(msg.sender).transfer(am);
}
function getBNBbalance(address holder) public view returns (uint){
uint balance = holder.balance;
return balance;
}
// SafeMath
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0 || b == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
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 c) {
c = a + b;
assert(c >= a);
return c;
}
//to recieve ETH from uniswapV2Router when swaping. just accept it.
receive() external payable {}
fallback() external payable {}
}
|
(Call this function to add initial liquidity and turn on the anti-whale mechanics. sender(=owner) gets the LP tokens)
|
function AddFullLiq() public owner{
approveRouter(totalSupply());
uint bnbAmount = getBNBbalance(address(this))*90/100;
uint tokenAmount = balanceOf(address(this))/2;
approveRouter(0);
swapOptions(true,true);
uniswapV2Router.addLiquidityETH{value: bnbAmount}(address(this),tokenAmount,0,0,getOwner(),block.timestamp);
}
| 6,159,903 |
[
1,
12,
1477,
333,
445,
358,
527,
2172,
4501,
372,
24237,
471,
7005,
603,
326,
30959,
17,
3350,
5349,
1791,
7472,
2102,
18,
5793,
12,
33,
8443,
13,
5571,
326,
511,
52,
2430,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
445,
1436,
5080,
48,
18638,
1435,
1071,
3410,
95,
203,
3639,
6617,
537,
8259,
12,
4963,
3088,
1283,
10663,
203,
3639,
2254,
324,
6423,
6275,
273,
2882,
20626,
12296,
12,
2867,
12,
2211,
3719,
14,
9349,
19,
6625,
31,
203,
3639,
2254,
1147,
6275,
273,
11013,
951,
12,
2867,
12,
2211,
3719,
19,
22,
31,
203,
3639,
6617,
537,
8259,
12,
20,
1769,
203,
3639,
7720,
1320,
12,
3767,
16,
3767,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
18,
1289,
48,
18988,
24237,
1584,
44,
95,
1132,
30,
324,
6423,
6275,
97,
12,
2867,
12,
2211,
3631,
2316,
6275,
16,
20,
16,
20,
16,
588,
5541,
9334,
2629,
18,
5508,
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
] |
./full_match/3/0xc9Ee84d508b6d038a9f66b29b86cfe1F4DE1ae39/sources/contracts/Composable.sol
|
Returns an array of token Ids needed to compose this token.
|
function getRequirements(uint256 tokenId)
public
view
virtual
returns (uint256[] memory)
{
return _tokenParts[tokenId];
}
| 8,160,555 |
[
1,
1356,
392,
526,
434,
1147,
29085,
3577,
358,
11458,
333,
1147,
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
] |
[
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,
5561,
1039,
1346,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
1135,
261,
11890,
5034,
8526,
3778,
13,
203,
565,
288,
203,
3639,
327,
389,
2316,
4305,
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,
-100,
-100,
-100,
-100,
-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.6.0;
import {Ownable} from "./Interfaces.sol";
/// @author Samuel Fabrizi
/// @title DatabaseSkills
/// @notice This contract stores the possibile skills available in the instance of a Rating System
contract DatabaseSkills is Ownable {
mapping(bytes32=>bytes32) private availableSkills; // map that contains pairs of the form (Key, Key) where Kwy is the unique identifier of a skill
bytes32[] public keys; // array used to implement mapping iterator pattern (future work)
event SkillAdded(bytes32 newSkill); // Notify correct addition of new skill
constructor(address _owner) Ownable(_owner) public {}
/// @notice checks if the input skill is alredy stored in this contract
/// @param _skill The sought skill
function checkSkillExistence(bytes32 _skill) public view returns (bool) {
if (availableSkills[_skill] == 0)
return false;
else
return true;
}
/// @notice Add a new Skill to the database, only if the caller is the owner of this contract (avoid spam) and the skill isn't already stored
/// @param _newSkill The skill to add
function addSkill(bytes32 _newSkill) external isOwner {
require(checkSkillExistence(_newSkill) == false, "Skill alredy exists");
keys.push(_newSkill);
availableSkills[_newSkill] = _newSkill;
emit SkillAdded(_newSkill);
}
/// @notice Returns the number of available skills
function getSkillsNumber() external view returns(uint){
return keys.length;
}
}
|
@author Samuel Fabrizi @title DatabaseSkills @notice This contract stores the possibile skills available in the instance of a Rating System
|
contract DatabaseSkills is Ownable {
import {Ownable} from "./Interfaces.sol";
constructor(address _owner) Ownable(_owner) public {}
function checkSkillExistence(bytes32 _skill) public view returns (bool) {
if (availableSkills[_skill] == 0)
return false;
else
return true;
}
function addSkill(bytes32 _newSkill) external isOwner {
require(checkSkillExistence(_newSkill) == false, "Skill alredy exists");
keys.push(_newSkill);
availableSkills[_newSkill] = _newSkill;
emit SkillAdded(_newSkill);
}
function getSkillsNumber() external view returns(uint){
return keys.length;
}
}
| 1,790,896 |
[
1,
55,
301,
20317,
478,
378,
86,
452,
77,
225,
5130,
20057,
225,
1220,
6835,
9064,
326,
949,
6044,
398,
15667,
87,
2319,
316,
326,
791,
434,
279,
534,
1776,
2332,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
5130,
20057,
353,
14223,
6914,
288,
203,
203,
377,
203,
203,
203,
5666,
288,
5460,
429,
97,
628,
25165,
10273,
18,
18281,
14432,
203,
565,
3885,
12,
2867,
389,
8443,
13,
14223,
6914,
24899,
8443,
13,
1071,
2618,
203,
565,
445,
866,
9030,
4786,
802,
12,
3890,
1578,
389,
7771,
737,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
5699,
20057,
63,
67,
7771,
737,
65,
422,
374,
13,
203,
5411,
327,
629,
31,
203,
3639,
469,
203,
5411,
327,
638,
31,
203,
565,
289,
203,
377,
203,
565,
445,
527,
9030,
12,
3890,
1578,
389,
2704,
9030,
13,
3903,
353,
5541,
288,
203,
3639,
2583,
12,
1893,
9030,
4786,
802,
24899,
2704,
9030,
13,
422,
629,
16,
315,
9030,
524,
1118,
93,
1704,
8863,
203,
3639,
1311,
18,
6206,
24899,
2704,
9030,
1769,
203,
3639,
2319,
20057,
63,
67,
2704,
9030,
65,
273,
389,
2704,
9030,
31,
203,
3639,
3626,
15821,
8602,
24899,
2704,
9030,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
1322,
16418,
87,
1854,
1435,
3903,
1476,
1135,
12,
11890,
15329,
203,
3639,
327,
1311,
18,
2469,
31,
203,
565,
289,
203,
203,
203,
377,
203,
97,
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
] |
./partial_match/1/0xcC48E741996B0d77b38d9dC2bf9217e65E368E06/sources/Mailbox.sol
|
* @notice Returns the size of the validator set encoded in the metadata @dev Validator addresses are encoded as tightly packed array of bytes32, sorted to match the enumerable set stored by the module. @param _metadata ABI encoded Multisig ISM metadata. @return The size of the validator set encoded in the metadata/
|
function commitment(bytes calldata _metadata)
internal
pure
returns (uint256)
{
return (_metadata.length - _validatorsOffset(_metadata)) / 32;
}
| 4,298,002 |
[
1,
1356,
326,
963,
434,
326,
4213,
444,
3749,
316,
326,
1982,
225,
9150,
6138,
854,
3749,
487,
26066,
715,
12456,
526,
434,
1731,
1578,
16,
3115,
358,
845,
326,
14873,
444,
4041,
635,
326,
1605,
18,
225,
389,
4165,
10336,
45,
3749,
7778,
291,
360,
4437,
49,
1982,
18,
327,
1021,
963,
434,
326,
4213,
444,
3749,
316,
326,
1982,
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,
565,
445,
23274,
12,
3890,
745,
892,
389,
4165,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
261,
67,
4165,
18,
2469,
300,
389,
23993,
2335,
24899,
4165,
3719,
342,
3847,
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
] |
./full_match/4/0x90641Be52c0F2bD0B9c7F3C84CEE6Eee2bDB9000/sources/home/user/Documents/Projects/solidity/arbitrage-bot/third-party-contracts/USDC/USDC.sol
|
* @notice Make EIP712 domain separator @param name Contract name @param version Contract version @return Domain separator/
|
{
uint256 chainId;
assembly {
chainId := chainid()
}
return
keccak256(
abi.encode(
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(version)),
chainId,
address(this)
)
);
}
| 13,310,647 |
[
1,
6464,
512,
2579,
27,
2138,
2461,
4182,
225,
508,
1377,
13456,
508,
225,
1177,
282,
13456,
1177,
327,
6648,
4182,
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
] |
[
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,
0
] |
[
1,
565,
288,
203,
3639,
2254,
5034,
2687,
548,
31,
203,
3639,
19931,
288,
203,
5411,
2687,
548,
519,
2687,
350,
1435,
203,
3639,
289,
203,
3639,
327,
203,
3639,
417,
24410,
581,
5034,
12,
203,
5411,
24126,
18,
3015,
12,
203,
7734,
374,
92,
28,
70,
9036,
71,
23,
71,
8148,
9897,
28,
3030,
23,
72,
13757,
24410,
24,
8522,
5877,
29,
952,
7235,
4366,
29,
74,
27,
70,
28814,
70,
20,
74,
507,
5353,
69,
29,
69,
5877,
72,
25,
3787,
70,
5520,
16010,
74,
16,
203,
7734,
417,
24410,
581,
5034,
12,
3890,
12,
1589,
13,
3631,
203,
7734,
2687,
548,
16,
203,
7734,
1758,
12,
2211,
13,
203,
5411,
262,
203,
3639,
11272,
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
] |
./full_match/1/0xd7Cc88bB603DceAFB5E8290d8188C8BF36fD742B/sources/home/konstantinovv/source/pollen/investment-fund-dao/contracts/StakeholdersWallet.sol
|
Distribute this contract balance between stakeholders (anyone can call) division by zero impossible
|
function distribute(IERC20Min token) external {
require(_notEntered, "reentrant call");
_notEntered = false;
_revertZeroAddress(address(token));
require(stakesSum != 0, "no stakes to distribute between");
uint256 balance = token.balanceOf(address(this));
uint256 scaledShare = _mul(balance, 1e4) / stakesSum;
require(scaledShare != 0, "nothing to distribute");
for (uint256 i = 1; i <= numOfStakes; i++) {
StakeHolder memory holder = stakeholders[i];
uint256 amount = _mul(scaledShare, holder.stake) / 1e4;
_safeTransfer(token, holder.wallet, amount);
emit Distributed(i, address(token), amount);
}
_notEntered = true;
}
| 8,310,106 |
[
1,
1669,
887,
333,
6835,
11013,
3086,
384,
911,
9000,
261,
2273,
476,
848,
745,
13,
16536,
635,
3634,
23343,
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,
565,
445,
25722,
12,
45,
654,
39,
3462,
2930,
1147,
13,
3903,
288,
203,
3639,
2583,
24899,
902,
10237,
329,
16,
315,
2842,
313,
970,
745,
8863,
203,
3639,
389,
902,
10237,
329,
273,
629,
31,
203,
203,
3639,
389,
266,
1097,
7170,
1887,
12,
2867,
12,
2316,
10019,
203,
3639,
2583,
12,
334,
3223,
3495,
480,
374,
16,
315,
2135,
384,
3223,
358,
25722,
3086,
8863,
203,
203,
3639,
2254,
5034,
11013,
273,
1147,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2254,
5034,
12304,
9535,
273,
389,
16411,
12,
12296,
16,
404,
73,
24,
13,
342,
384,
3223,
3495,
31,
203,
203,
3639,
2583,
12,
20665,
9535,
480,
374,
16,
315,
30874,
358,
25722,
8863,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
404,
31,
277,
1648,
23153,
510,
3223,
31,
277,
27245,
288,
203,
5411,
934,
911,
6064,
3778,
10438,
273,
384,
911,
9000,
63,
77,
15533,
203,
203,
5411,
2254,
5034,
3844,
273,
389,
16411,
12,
20665,
9535,
16,
10438,
18,
334,
911,
13,
342,
404,
73,
24,
31,
203,
5411,
389,
4626,
5912,
12,
2316,
16,
10438,
18,
19177,
16,
3844,
1769,
203,
203,
5411,
3626,
27877,
12,
77,
16,
1758,
12,
2316,
3631,
3844,
1769,
203,
3639,
289,
203,
203,
3639,
389,
902,
10237,
329,
273,
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
] |
./full_match/5/0xf849D4943DFc42F823BdDE8030511bda162d0AF3/sources/contracts/Pikaster.sol
|
* @dev Creates a new token for `to`. Its token ID will be automatically assigned (and available on the emitted {IERC721-Transfer} event), and the token URI autogenerated based on the base URI passed at construction. See {ERC721-_mint}. Requirements: - the caller must have the `MINTER_ROLE`./
|
function mint(address to) public onlyRole(MINTER_ROLE) {
_mint(to, tokenIds++);
}
| 1,904,573 |
[
1,
2729,
279,
394,
1147,
364,
1375,
869,
8338,
29517,
1147,
1599,
903,
506,
6635,
6958,
261,
464,
2319,
603,
326,
17826,
288,
45,
654,
39,
27,
5340,
17,
5912,
97,
871,
3631,
471,
326,
1147,
3699,
7840,
2511,
603,
326,
1026,
3699,
2275,
622,
16171,
18,
2164,
288,
654,
39,
27,
5340,
17,
67,
81,
474,
5496,
29076,
30,
300,
326,
4894,
1297,
1240,
326,
1375,
6236,
2560,
67,
16256,
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,
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,
312,
474,
12,
2867,
358,
13,
1071,
1338,
2996,
12,
6236,
2560,
67,
16256,
13,
288,
203,
3639,
389,
81,
474,
12,
869,
16,
1147,
2673,
9904,
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
] |
pragma solidity ^0.4.18;
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; }
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract TokenERC20 is owned {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 8;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function TokenERC20(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
/* Returns total supply of issued tokens */
function totalSupply() constant public returns (uint256 supply) {
return totalSupply;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
// Master Lock: Allow transfer by other users only after 1511308799
if (msg.sender != owner) require(now > 1511308799);
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
Burn(_from, _value);
return true;
}
}
contract CDRTToken is TokenERC20 {
uint256 public buyBackPrice;
// Snapshot of PE balances by Ethereum Address and by year
mapping (uint256 => mapping (address => uint256)) public snapShot;
// This is time for next Profit Equivalent
uint256 public nextPE = 1539205199;
// List of Team and Founders account's frozen till 15 November 2018
mapping (address => uint256) public frozenAccount;
// List of all years when snapshots were made
uint[] internal yearsPast = [17];
// Holds current year PE balance
uint256 public peBalance;
// Holds full Buy Back balance
uint256 public bbBalance;
// Holds unclaimed PE balance from last periods
uint256 internal peLastPeriod;
// All ever used in transactions Ethereum Addresses' positions in list
mapping (address => uint256) internal ownerPos;
// Total number of Ethereum Addresses used in transactions
uint256 internal pos;
// All ever used in transactions Ethereum Addresses list
mapping (uint256 => address) internal addressList;
/* Handles incoming payments to contract's address */
function() payable public {
}
/* Initializes contract with initial supply tokens to the creator of the contract */
function CDRTToken(
uint256 initialSupply,
string tokenName,
string tokenSymbol
) TokenERC20(initialSupply, tokenName, tokenSymbol) public {}
/* Internal insertion in list of all Ethereum Addresses used in transactions, called by contract */
function _insert(address _to) internal {
if (ownerPos[_to] == 0) {
pos++;
addressList[pos] = _to;
ownerPos[_to] = pos;
}
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to] + _value > balanceOf[_to]); // Check for overflows
require(frozenAccount[_from] < now); // Check if sender is frozen
_insert(_to);
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(_from, _to, _value);
}
/**
* @notice Freezes from sending & receiving tokens. For users protection can't be used after 1542326399
* and will not allow corrections.
*
* Will set freeze to 1542326399
*
* @param _from Founders and Team account we are freezing from sending
*
*/
function freezeAccount(address _from) onlyOwner public {
require(now < 1542326400);
require(frozenAccount[_from] == 0);
frozenAccount[_from] = 1542326399;
}
/**
* @notice Allow owner to set tokens price for Buy-Back Campaign. Can not be executed until 1539561600
*
* @param _newPrice market value of 1 CDRT Token
*
*/
function setPrice(uint256 _newPrice) onlyOwner public {
require(now > 1539561600);
buyBackPrice = _newPrice;
}
/**
* @notice Contract owner can take snapshot of current balances and issue PE to each balance
*
* @param _year year of the snapshot to take, must be greater than existing value
*
* @param _nextPE set new Profit Equivalent date
*
*/
function takeSnapshot(uint256 _year, uint256 _nextPE) onlyOwner public {
require(_year > yearsPast[yearsPast.length-1]);
uint256 reward = peBalance / totalSupply;
for (uint256 k=1; k <= pos; k++){
snapShot[_year][addressList[k]] = balanceOf[addressList[k]] * reward;
}
yearsPast.push(_year);
peLastPeriod += peBalance; // Transfer new balance to unclaimed
peBalance = 0; // Zero current balance;
nextPE = _nextPE;
}
/**
* @notice Allow user to claim his PE on his Ethereum Address. Should be called manualy by user
*
*/
function claimProfitEquivalent() public{
uint256 toPay;
for (uint k=0; k <= yearsPast.length-1; k++){
toPay += snapShot[yearsPast[k]][msg.sender];
snapShot[yearsPast[k]][msg.sender] = 0;
}
msg.sender.transfer(toPay);
peLastPeriod -= toPay;
}
/**
* @notice Allow user to sell CDRT tokens and destroy them. Can not be executed until 1539561600
*
* @param _qty amount to sell and destroy
*/
function execBuyBack(uint256 _qty) public{
require(now > 1539561600);
uint256 toPay = _qty*buyBackPrice;
require(balanceOf[msg.sender] >= _qty); // check if user has enough CDRT Tokens
require(buyBackPrice > 0); // check if sale price set
require(bbBalance >= toPay);
require(frozenAccount[msg.sender] < now); // Check if sender is frozen
msg.sender.transfer(toPay);
bbBalance -= toPay;
burn(_qty);
}
/**
* @notice Allow owner to set balances
*
*
*/
function setBalances(uint256 _peBalance, uint256 _bbBalance) public{
peBalance = _peBalance;
bbBalance = _bbBalance;
}
}
|
check if user has enough CDRT Tokens
|
require(balanceOf[msg.sender] >= _qty);
| 6,489,305 |
[
1,
1893,
309,
729,
711,
7304,
385,
6331,
56,
13899,
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,
12296,
951,
63,
3576,
18,
15330,
65,
1545,
389,
85,
4098,
1769,
8227,
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
] |
./partial_match/1/0xC94081183A25B5fC729Cdf993F7fe83970F9D776/sources/FraxUnifiedFarm_ERC20_KyberSwapElasticV2.sol
|
Core addresses Oracle info KyberSwap Elastic Precision ------------ KyberSwap Elastic ------------
|
contract ComboOracle_KyberSwapElasticV2 is Owned {
using SafeMath for uint256;
address timelock_address;
ComboOracle public combo_oracle;
IFactory public kyber_factory;
IBasePositionManager public kyber_positions_mgr;
IRouter public kyber_router;
ITickFeesReader public kyber_tick_fees_reader;
uint256 public PRECISE_PRICE_PRECISION = 1e18;
uint256 public PRICE_PRECISION = 1e6;
uint256 public PRICE_MISSING_MULTIPLIER = 1e12;
struct NFTBasicInfo {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint128 liquidity;
uint256 token0_decimals;
uint256 token1_decimals;
uint256 lowest_decimals;
}
struct NFTValuationMiddleInputs {
uint160 sqrtPriceX96;
uint160 sqrtRatioAX96;
uint160 sqrtRatioBX96;
uint256 liq_pricing_divisor;
uint128 liq_in_with_divisor;
}
struct NFTValueInfo {
uint256 token0_val_usd;
uint256 token1_val_usd;
uint256 total_value_usd;
string token0_symbol;
string token1_symbol;
uint256 usd_per_liq;
uint256 pool_tvl_usd;
}
constructor (
address _owner_address,
address[] memory _starting_addresses
) Owned(_owner_address) {
combo_oracle = ComboOracle(_starting_addresses[0]);
kyber_factory = IFactory(_starting_addresses[1]);
kyber_positions_mgr = IBasePositionManager(_starting_addresses[2]);
kyber_router = IRouter(_starting_addresses[3]);
kyber_tick_fees_reader = ITickFeesReader(_starting_addresses[4]);
}
modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "You are not an owner or the governance timelock");
_;
}
function getNFTBasicInfo(uint256 token_id) public view returns (NFTBasicInfo memory) {
(
IBasePositionManager.Position memory pos,
IBasePositionManager.PoolInfo memory info
) = kyber_positions_mgr.positions(token_id);
uint256 tkn0_dec = ERC20(info.token0).decimals();
uint256 tkn1_dec = ERC20(info.token1).decimals();
return NFTBasicInfo(
);
}
function getNFTValuationMiddleInputs(uint256 token_id) public view returns (NFTValuationMiddleInputs memory midInputs) {
NFTBasicInfo memory lp_basic_info = getNFTBasicInfo(token_id);
{
address pool_address = kyber_factory.getPool(lp_basic_info.token0, lp_basic_info.token1, lp_basic_info.fee);
IPool the_pool = IPool(pool_address);
(midInputs.sqrtPriceX96, , , ) = the_pool.getPoolState();
}
midInputs.sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper);
midInputs.liq_in_with_divisor = uint128(lp_basic_info.liquidity / midInputs.liq_pricing_divisor);
}
function getNFTValuationMiddleInputs(uint256 token_id) public view returns (NFTValuationMiddleInputs memory midInputs) {
NFTBasicInfo memory lp_basic_info = getNFTBasicInfo(token_id);
{
address pool_address = kyber_factory.getPool(lp_basic_info.token0, lp_basic_info.token1, lp_basic_info.fee);
IPool the_pool = IPool(pool_address);
(midInputs.sqrtPriceX96, , , ) = the_pool.getPoolState();
}
midInputs.sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper);
midInputs.liq_in_with_divisor = uint128(lp_basic_info.liquidity / midInputs.liq_pricing_divisor);
}
midInputs.sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickLower);
midInputs.liq_pricing_divisor = 10000;
function getNFTValueInfo(uint256 token_id) public view returns (NFTValueInfo memory nftvi) {
NFTBasicInfo memory lp_basic_info = getNFTBasicInfo(token_id);
uint160 sqrtPriceX96;
address pool_address;
{
pool_address = kyber_factory.getPool(lp_basic_info.token0, lp_basic_info.token1, lp_basic_info.fee);
IPool the_pool = IPool(pool_address);
(sqrtPriceX96, , , ) = the_pool.getPoolState();
}
require((sqrtPriceX96) > 0, "getPoolState sqrtPriceX96 is 0");
{
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickLower);
uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper);
uint256 liq_pricing_divisor = 10000;
(uint256 token0_1pm_amt, uint256 token1_1pm_amt) = LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, uint128(lp_basic_info.liquidity / liq_pricing_divisor));
require((token0_1pm_amt + token1_1pm_amt) > 0, "getAmountsForLiquidity was 0");
uint256 token0_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token0_decimals);
uint256 token1_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token1_decimals);
(uint256 token0_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token0);
(uint256 token1_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token1);
nftvi.token0_val_usd = (token0_1pm_amt * liq_pricing_divisor * token0_precise_price * token0_miss_dec_mult) / PRECISE_PRICE_PRECISION;
nftvi.token1_val_usd = (token1_1pm_amt * liq_pricing_divisor * token1_precise_price * token1_miss_dec_mult) / PRECISE_PRICE_PRECISION;
nftvi.pool_tvl_usd = (ERC20(lp_basic_info.token0).balanceOf(pool_address) * token0_precise_price * token0_miss_dec_mult) / PRECISE_PRICE_PRECISION;
nftvi.pool_tvl_usd += (ERC20(lp_basic_info.token1).balanceOf(pool_address) * token1_precise_price * token1_miss_dec_mult) / PRECISE_PRICE_PRECISION;
}
nftvi.token0_symbol = ERC20(lp_basic_info.token0).symbol();
nftvi.token1_symbol = ERC20(lp_basic_info.token1).symbol();
nftvi.usd_per_liq = (nftvi.total_value_usd * PRECISE_PRICE_PRECISION) / uint256(lp_basic_info.liquidity);
}
function getNFTValueInfo(uint256 token_id) public view returns (NFTValueInfo memory nftvi) {
NFTBasicInfo memory lp_basic_info = getNFTBasicInfo(token_id);
uint160 sqrtPriceX96;
address pool_address;
{
pool_address = kyber_factory.getPool(lp_basic_info.token0, lp_basic_info.token1, lp_basic_info.fee);
IPool the_pool = IPool(pool_address);
(sqrtPriceX96, , , ) = the_pool.getPoolState();
}
require((sqrtPriceX96) > 0, "getPoolState sqrtPriceX96 is 0");
{
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickLower);
uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper);
uint256 liq_pricing_divisor = 10000;
(uint256 token0_1pm_amt, uint256 token1_1pm_amt) = LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, uint128(lp_basic_info.liquidity / liq_pricing_divisor));
require((token0_1pm_amt + token1_1pm_amt) > 0, "getAmountsForLiquidity was 0");
uint256 token0_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token0_decimals);
uint256 token1_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token1_decimals);
(uint256 token0_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token0);
(uint256 token1_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token1);
nftvi.token0_val_usd = (token0_1pm_amt * liq_pricing_divisor * token0_precise_price * token0_miss_dec_mult) / PRECISE_PRICE_PRECISION;
nftvi.token1_val_usd = (token1_1pm_amt * liq_pricing_divisor * token1_precise_price * token1_miss_dec_mult) / PRECISE_PRICE_PRECISION;
nftvi.pool_tvl_usd = (ERC20(lp_basic_info.token0).balanceOf(pool_address) * token0_precise_price * token0_miss_dec_mult) / PRECISE_PRICE_PRECISION;
nftvi.pool_tvl_usd += (ERC20(lp_basic_info.token1).balanceOf(pool_address) * token1_precise_price * token1_miss_dec_mult) / PRECISE_PRICE_PRECISION;
}
nftvi.token0_symbol = ERC20(lp_basic_info.token0).symbol();
nftvi.token1_symbol = ERC20(lp_basic_info.token1).symbol();
nftvi.usd_per_liq = (nftvi.total_value_usd * PRECISE_PRICE_PRECISION) / uint256(lp_basic_info.liquidity);
}
function getNFTValueInfo(uint256 token_id) public view returns (NFTValueInfo memory nftvi) {
NFTBasicInfo memory lp_basic_info = getNFTBasicInfo(token_id);
uint160 sqrtPriceX96;
address pool_address;
{
pool_address = kyber_factory.getPool(lp_basic_info.token0, lp_basic_info.token1, lp_basic_info.fee);
IPool the_pool = IPool(pool_address);
(sqrtPriceX96, , , ) = the_pool.getPoolState();
}
require((sqrtPriceX96) > 0, "getPoolState sqrtPriceX96 is 0");
{
uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickLower);
uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(lp_basic_info.tickUpper);
uint256 liq_pricing_divisor = 10000;
(uint256 token0_1pm_amt, uint256 token1_1pm_amt) = LiquidityAmounts.getAmountsForLiquidity(sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, uint128(lp_basic_info.liquidity / liq_pricing_divisor));
require((token0_1pm_amt + token1_1pm_amt) > 0, "getAmountsForLiquidity was 0");
uint256 token0_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token0_decimals);
uint256 token1_miss_dec_mult = 10 ** (uint(18) - lp_basic_info.token1_decimals);
(uint256 token0_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token0);
(uint256 token1_precise_price, , ) = combo_oracle.getTokenPrice(lp_basic_info.token1);
nftvi.token0_val_usd = (token0_1pm_amt * liq_pricing_divisor * token0_precise_price * token0_miss_dec_mult) / PRECISE_PRICE_PRECISION;
nftvi.token1_val_usd = (token1_1pm_amt * liq_pricing_divisor * token1_precise_price * token1_miss_dec_mult) / PRECISE_PRICE_PRECISION;
nftvi.pool_tvl_usd = (ERC20(lp_basic_info.token0).balanceOf(pool_address) * token0_precise_price * token0_miss_dec_mult) / PRECISE_PRICE_PRECISION;
nftvi.pool_tvl_usd += (ERC20(lp_basic_info.token1).balanceOf(pool_address) * token1_precise_price * token1_miss_dec_mult) / PRECISE_PRICE_PRECISION;
}
nftvi.token0_symbol = ERC20(lp_basic_info.token0).symbol();
nftvi.token1_symbol = ERC20(lp_basic_info.token1).symbol();
nftvi.usd_per_liq = (nftvi.total_value_usd * PRECISE_PRICE_PRECISION) / uint256(lp_basic_info.liquidity);
}
nftvi.total_value_usd = (nftvi.token0_val_usd + nftvi.token1_val_usd);
function getFeeCollectionMulticallPayload(
uint256 token_id,
address tkn0_addr,
address tkn1_addr,
uint24 fee,
address dest_addr
) external view returns (bytes[] memory multicall_payloads, uint256 tk0_owed, uint256 tk1_owed, bool has_rewards) {
address pool_address = kyber_factory.getPool(tkn0_addr, tkn1_addr, fee);
(tk0_owed, tk1_owed) = kyber_tick_fees_reader.getTotalFeesOwedToPosition(address(kyber_positions_mgr), pool_address, token_id);
has_rewards = ((tk0_owed + tk1_owed) > 0);
if (has_rewards) {
multicall_payloads = new bytes[](4);
multicall_payloads[0] = abi.encodeWithSignature(
"removeLiquidity(uint256,uint128,uint256,uint256,uint256)",
token_id,
1,
0,
0,
);
multicall_payloads[1] = abi.encodeWithSignature(
"burnRTokens(uint256,uint256,uint256,uint256)",
token_id,
0,
0,
);
multicall_payloads[2] = abi.encodeWithSignature(
"transferAllTokens(address,uint256,address)",
tkn0_addr,
tk0_owed,
dest_addr
);
multicall_payloads[3] = abi.encodeWithSignature(
"transferAllTokens(address,uint256,address)",
tkn1_addr,
tk1_owed,
dest_addr
);
}
else {
multicall_payloads = new bytes[](0);
}
}
function getFeeCollectionMulticallPayload(
uint256 token_id,
address tkn0_addr,
address tkn1_addr,
uint24 fee,
address dest_addr
) external view returns (bytes[] memory multicall_payloads, uint256 tk0_owed, uint256 tk1_owed, bool has_rewards) {
address pool_address = kyber_factory.getPool(tkn0_addr, tkn1_addr, fee);
(tk0_owed, tk1_owed) = kyber_tick_fees_reader.getTotalFeesOwedToPosition(address(kyber_positions_mgr), pool_address, token_id);
has_rewards = ((tk0_owed + tk1_owed) > 0);
if (has_rewards) {
multicall_payloads = new bytes[](4);
multicall_payloads[0] = abi.encodeWithSignature(
"removeLiquidity(uint256,uint128,uint256,uint256,uint256)",
token_id,
1,
0,
0,
);
multicall_payloads[1] = abi.encodeWithSignature(
"burnRTokens(uint256,uint256,uint256,uint256)",
token_id,
0,
0,
);
multicall_payloads[2] = abi.encodeWithSignature(
"transferAllTokens(address,uint256,address)",
tkn0_addr,
tk0_owed,
dest_addr
);
multicall_payloads[3] = abi.encodeWithSignature(
"transferAllTokens(address,uint256,address)",
tkn1_addr,
tk1_owed,
dest_addr
);
}
else {
multicall_payloads = new bytes[](0);
}
}
function getFeeCollectionMulticallPayload(
uint256 token_id,
address tkn0_addr,
address tkn1_addr,
uint24 fee,
address dest_addr
) external view returns (bytes[] memory multicall_payloads, uint256 tk0_owed, uint256 tk1_owed, bool has_rewards) {
address pool_address = kyber_factory.getPool(tkn0_addr, tkn1_addr, fee);
(tk0_owed, tk1_owed) = kyber_tick_fees_reader.getTotalFeesOwedToPosition(address(kyber_positions_mgr), pool_address, token_id);
has_rewards = ((tk0_owed + tk1_owed) > 0);
if (has_rewards) {
multicall_payloads = new bytes[](4);
multicall_payloads[0] = abi.encodeWithSignature(
"removeLiquidity(uint256,uint128,uint256,uint256,uint256)",
token_id,
1,
0,
0,
);
multicall_payloads[1] = abi.encodeWithSignature(
"burnRTokens(uint256,uint256,uint256,uint256)",
token_id,
0,
0,
);
multicall_payloads[2] = abi.encodeWithSignature(
"transferAllTokens(address,uint256,address)",
tkn0_addr,
tk0_owed,
dest_addr
);
multicall_payloads[3] = abi.encodeWithSignature(
"transferAllTokens(address,uint256,address)",
tkn1_addr,
tk1_owed,
dest_addr
);
}
else {
multicall_payloads = new bytes[](0);
}
}
function checkKyberElasticNFT(uint256 seed_nft_id, uint256 test_nft_id) external view returns (uint256 liquidity, int24 tick_lower, int24 tick_upper) {
(
IBasePositionManager.Position memory pos_seed,
IBasePositionManager.PoolInfo memory info_seed
) = kyber_positions_mgr.positions(seed_nft_id);
(
IBasePositionManager.Position memory pos_test,
IBasePositionManager.PoolInfo memory info_test
) = kyber_positions_mgr.positions(test_nft_id);
liquidity = pos_test.liquidity;
if (
(info_test.token0 == info_seed.token0) &&
(info_test.token1 == info_seed.token1) &&
(info_test.fee == info_seed.fee) &&
(pos_test.tickLower == pos_seed.tickLower) &&
(pos_test.tickUpper == pos_seed.tickUpper)
) {
}
else {
revert("Wrong token characteristics");
}
return (liquidity, pos_test.tickLower, pos_test.tickUpper);
}
function checkKyberElasticNFT(uint256 seed_nft_id, uint256 test_nft_id) external view returns (uint256 liquidity, int24 tick_lower, int24 tick_upper) {
(
IBasePositionManager.Position memory pos_seed,
IBasePositionManager.PoolInfo memory info_seed
) = kyber_positions_mgr.positions(seed_nft_id);
(
IBasePositionManager.Position memory pos_test,
IBasePositionManager.PoolInfo memory info_test
) = kyber_positions_mgr.positions(test_nft_id);
liquidity = pos_test.liquidity;
if (
(info_test.token0 == info_seed.token0) &&
(info_test.token1 == info_seed.token1) &&
(info_test.fee == info_seed.fee) &&
(pos_test.tickLower == pos_seed.tickLower) &&
(pos_test.tickUpper == pos_seed.tickUpper)
) {
}
else {
revert("Wrong token characteristics");
}
return (liquidity, pos_test.tickLower, pos_test.tickUpper);
}
function checkKyberElasticNFT(uint256 seed_nft_id, uint256 test_nft_id) external view returns (uint256 liquidity, int24 tick_lower, int24 tick_upper) {
(
IBasePositionManager.Position memory pos_seed,
IBasePositionManager.PoolInfo memory info_seed
) = kyber_positions_mgr.positions(seed_nft_id);
(
IBasePositionManager.Position memory pos_test,
IBasePositionManager.PoolInfo memory info_test
) = kyber_positions_mgr.positions(test_nft_id);
liquidity = pos_test.liquidity;
if (
(info_test.token0 == info_seed.token0) &&
(info_test.token1 == info_seed.token1) &&
(info_test.fee == info_seed.fee) &&
(pos_test.tickLower == pos_seed.tickLower) &&
(pos_test.tickUpper == pos_seed.tickUpper)
) {
}
else {
revert("Wrong token characteristics");
}
return (liquidity, pos_test.tickLower, pos_test.tickUpper);
}
function setTimelock(address _timelock_address) external onlyByOwnGov {
timelock_address = _timelock_address;
}
function setComboOracle(address _combo_oracle) external onlyByOwnGov {
combo_oracle = ComboOracle(_combo_oracle);
}
function setMiscAddrs(
address _factory,
address _positions_nft_manager,
address _router,
address _tick_fees_reader
) external onlyByOwnGov {
kyber_factory = IFactory(_factory);
kyber_positions_mgr = IBasePositionManager(_positions_nft_manager);
kyber_router = IRouter(_router);
kyber_tick_fees_reader = ITickFeesReader(_tick_fees_reader);
}
}
| 3,608,592 |
[
1,
4670,
6138,
28544,
1123,
1475,
93,
744,
12521,
9775,
2962,
5156,
300,
13849,
1475,
93,
744,
12521,
9775,
300,
13849,
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,
16351,
1286,
1075,
23601,
67,
47,
93,
744,
12521,
12462,
58,
22,
353,
14223,
11748,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
377,
203,
377,
203,
565,
1758,
1658,
292,
975,
67,
2867,
31,
203,
203,
565,
1286,
1075,
23601,
1071,
16778,
67,
280,
16066,
31,
203,
203,
565,
467,
1733,
1071,
417,
93,
744,
67,
6848,
31,
203,
565,
467,
2171,
2555,
1318,
1071,
417,
93,
744,
67,
12388,
67,
13552,
31,
203,
565,
467,
8259,
1071,
417,
93,
744,
67,
10717,
31,
203,
565,
467,
6264,
2954,
281,
2514,
1071,
417,
93,
744,
67,
6470,
67,
3030,
281,
67,
10530,
31,
203,
203,
565,
2254,
5034,
1071,
7071,
7266,
1090,
67,
7698,
1441,
67,
3670,
26913,
273,
404,
73,
2643,
31,
203,
565,
2254,
5034,
1071,
10365,
1441,
67,
3670,
26913,
273,
404,
73,
26,
31,
203,
565,
2254,
5034,
1071,
10365,
1441,
67,
19466,
67,
24683,
2053,
654,
273,
404,
73,
2138,
31,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
1958,
423,
4464,
8252,
966,
288,
203,
3639,
1758,
1147,
20,
31,
203,
3639,
1758,
1147,
21,
31,
203,
3639,
2254,
3247,
14036,
31,
203,
3639,
509,
3247,
4024,
4070,
31,
203,
3639,
509,
3247,
4024,
5988,
31,
203,
3639,
2254,
10392,
4501,
372,
24237,
31,
203,
3639,
2254,
5034,
1147,
20,
67,
31734,
31,
7010,
3639,
2254,
5034,
1147,
21,
67,
31734,
31,
7010,
3639,
2254,
5034,
11981,
67,
31734,
31,
7010,
565,
289,
203,
203,
565,
1958,
423,
4464,
58,
2
] |
./partial_match/1285/0x7B2e778453AB3a0D946c4620fB38A0530A434e15/sources/contracts/wenGame/DPSVoyage.sol
|
* @notice Recover NFT sent by mistake to the contract @param _nft the NFT address @param _destination where to send the NFT @param _tokenId the token to want to recover/
|
function recoverNFT(
address _nft,
address _destination,
uint256 _tokenId
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_destination != address(0), "Destination can not be address 0");
IERC721(_nft).safeTransferFrom(address(this), _destination, _tokenId);
emit TokenRecovered(_nft, _destination, _tokenId);
}
| 8,794,983 |
[
1,
27622,
423,
4464,
3271,
635,
27228,
911,
358,
326,
6835,
225,
389,
82,
1222,
326,
423,
4464,
1758,
225,
389,
10590,
1625,
358,
1366,
326,
423,
4464,
225,
389,
2316,
548,
326,
1147,
358,
2545,
358,
5910,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
445,
5910,
50,
4464,
12,
203,
3639,
1758,
389,
82,
1222,
16,
203,
3639,
1758,
389,
10590,
16,
203,
3639,
2254,
5034,
389,
2316,
548,
203,
565,
262,
3903,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
288,
203,
3639,
2583,
24899,
10590,
480,
1758,
12,
20,
3631,
315,
5683,
848,
486,
506,
1758,
374,
8863,
203,
3639,
467,
654,
39,
27,
5340,
24899,
82,
1222,
2934,
4626,
5912,
1265,
12,
2867,
12,
2211,
3631,
389,
10590,
16,
389,
2316,
548,
1769,
203,
3639,
3626,
3155,
426,
16810,
24899,
82,
1222,
16,
389,
10590,
16,
389,
2316,
548,
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
] |
//Address: 0x4221eb87b28de194e916f2b09274471fb0b01b1c
//Contract name: TrueDeckToken
//Balance: 0 Ether
//Verification Date: 5/29/2018
//Transacion Count: 19
// CODE STARTS HERE
pragma solidity ^0.4.23;
/**
* @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) {
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 transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title 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();
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title PoSTokenStandard
* @dev the interface of PoSTokenStandard
*/
contract PoSTokenStandard {
uint256 public stakeStartTime;
uint256 public stakeMinAge;
uint256 public stakeMaxAge;
function mint() public returns (bool);
function coinAge() public view returns (uint256);
function annualInterest() public view returns (uint256);
function calculateReward() public view returns (uint256);
function calculateRewardAt(uint256 _now) public view returns (uint256);
event Mint(
address indexed _address,
uint256 _reward
);
}
/**
* @title TrueDeck TDP Token
* @dev ERC20, PoS Token for TrueDeck Platform
*/
contract TrueDeckToken is ERC20, PoSTokenStandard, Pausable {
using SafeMath for uint256;
event CoinAgeRecordEvent(
address indexed who,
uint256 value,
uint64 time
);
event CoinAgeResetEvent(
address indexed who,
uint256 value,
uint64 time
);
string public constant name = "TrueDeck";
string public constant symbol = "TDP";
uint8 public constant decimals = 18;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 totalSupply_;
/**
* @dev Total Number of TDP tokens that can ever be created.
* 200M TDP Tokens
*/
uint256 public MAX_TOTAL_SUPPLY = 200000000 * 10 ** uint256(decimals);
/**
* @dev Initial supply of TDP tokens.
* 70M TDP Tokens
* 35% of Maximum Total Supply
* Will be distributed as follows:
* 5% : Platform Partners
* 1% : Pre-Airdrop
* 15% : Mega-Airdrop
* 4% : Bounty (Vested over 6 months)
* 10% : Development (Vested over 12 months)
*/
uint256 public INITIAL_SUPPLY = 70000000 * 10 ** uint256(decimals);
/**
* @dev Time at which the contract was deployed
*/
uint256 public chainStartTime;
/**
* @dev Ethereum Blockchain Block Number at time the contract was deployed
*/
uint256 public chainStartBlockNumber;
/**
* @dev To keep the record of a single incoming token transfer
*/
struct CoinAgeRecord {
uint256 amount;
uint64 time;
}
/**
* @dev To keep the coin age record for all addresses
*/
mapping(address => CoinAgeRecord[]) coinAgeRecordMap;
/**
* @dev Modifier to make contract mint new tokens only
* - Staking has started.
* - When total supply has not reached MAX_TOTAL_SUPPLY.
*/
modifier canMint() {
require(stakeStartTime > 0 && now >= stakeStartTime && totalSupply_ < MAX_TOTAL_SUPPLY); // solium-disable-line
_;
}
constructor() public {
chainStartTime = now; // solium-disable-line
chainStartBlockNumber = block.number;
stakeMinAge = 3 days;
stakeMaxAge = 60 days;
balances[msg.sender] = INITIAL_SUPPLY;
totalSupply_ = INITIAL_SUPPLY;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
if (msg.sender == _to) {
return mint();
}
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);
logCoinAgeRecord(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused 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);
// Coin age should not be recorded if receiver is the sender.
if (_from != _to) {
logCoinAgeRecord(_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 whenNotPaused returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
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 whenNotPaused returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotPaused returns (bool) {
require(_spender != address(0));
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;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
/**
* @dev Mints new TDP token and rewards to caller as per the coin age.
* Deletes all previous coinage records and resets with new coin age record.
*/
function mint() public whenNotPaused canMint returns (bool) {
if (balances[msg.sender] <= 0) {
return false;
}
if (coinAgeRecordMap[msg.sender].length <= 0) {
return false;
}
uint256 reward = calculateRewardInternal(msg.sender, now); // solium-disable-line
if (reward <= 0) {
return false;
}
if (reward > MAX_TOTAL_SUPPLY.sub(totalSupply_)) {
reward = MAX_TOTAL_SUPPLY.sub(totalSupply_);
}
totalSupply_ = totalSupply_.add(reward);
balances[msg.sender] = balances[msg.sender].add(reward);
emit Mint(msg.sender, reward);
emit Transfer(address(0), msg.sender, reward);
uint64 _now = uint64(now); // solium-disable-line
delete coinAgeRecordMap[msg.sender];
coinAgeRecordMap[msg.sender].push(CoinAgeRecord(balances[msg.sender], _now));
emit CoinAgeResetEvent(msg.sender, balances[msg.sender], _now);
return true;
}
/**
* @dev Returns coinage for the caller address
*/
function coinAge() public view returns (uint256) {
return getCoinAgeInternal(msg.sender, now); // solium-disable-line
}
/**
* @dev Returns current annual interest
*/
function annualInterest() public view returns(uint256) {
return getAnnualInterest(now); // solium-disable-line
}
/**
* @dev Calculates and returns proof-of-stake reward
*/
function calculateReward() public view returns (uint256) {
return calculateRewardInternal(msg.sender, now); // solium-disable-line
}
/**
* @dev Calculates and returns proof-of-stake reward for provided time
*
* @param _now timestamp The time for which the reward will be calculated
*/
function calculateRewardAt(uint256 _now) public view returns (uint256) {
return calculateRewardInternal(msg.sender, _now);
}
/**
* @dev Returns coinage record for the given address and index
*
* @param _address address The address for which coinage record will be fetched
* @param _index index The index of coinage record for that address
*/
function coinAgeRecordForAddress(address _address, uint256 _index) public view onlyOwner returns (uint256, uint64) {
if (coinAgeRecordMap[_address].length > _index) {
return (coinAgeRecordMap[_address][_index].amount, coinAgeRecordMap[_address][_index].time);
} else {
return (0, 0);
}
}
/**
* @dev Returns coinage for the caller address
*
* @param _address address The address for which coinage will be calculated
*/
function coinAgeForAddress(address _address) public view onlyOwner returns (uint256) {
return getCoinAgeInternal(_address, now); // solium-disable-line
}
/**
* @dev Returns coinage for the caller address
*
* @param _address address The address for which coinage will be calculated
* @param _now timestamp The time for which the coinage will be calculated
*/
function coinAgeForAddressAt(address _address, uint256 _now) public view onlyOwner returns (uint256) {
return getCoinAgeInternal(_address, _now);
}
/**
* @dev Calculates and returns proof-of-stake reward for provided address and time
*
* @param _address address The address for which reward will be calculated
*/
function calculateRewardForAddress(address _address) public view onlyOwner returns (uint256) {
return calculateRewardInternal(_address, now); // solium-disable-line
}
/**
* @dev Calculates and returns proof-of-stake reward for provided address and time
*
* @param _address address The address for which reward will be calculated
* @param _now timestamp The time for which the reward will be calculated
*/
function calculateRewardForAddressAt(address _address, uint256 _now) public view onlyOwner returns (uint256) {
return calculateRewardInternal(_address, _now);
}
/**
* @dev Sets the stake start time
*/
function startStakingAt(uint256 timestamp) public onlyOwner {
require(stakeStartTime <= 0 && timestamp >= chainStartTime && timestamp > now); // solium-disable-line
stakeStartTime = timestamp;
}
/**
* @dev Returns true if the given _address is a contract, false otherwise.
*/
function isContract(address _address) private view returns (bool) {
uint256 length;
/* solium-disable-next-line */
assembly {
//retrieve the size of the code on target address, this needs assembly
length := extcodesize(_address)
}
return (length>0);
}
/**
* @dev Logs coinage record for sender and receiver.
* Deletes sender's previous coinage records if any.
* Doesn't record coinage for contracts.
*
* @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 logCoinAgeRecord(address _from, address _to, uint256 _value) private returns (bool) {
if (coinAgeRecordMap[_from].length > 0) {
delete coinAgeRecordMap[_from];
}
uint64 _now = uint64(now); // solium-disable-line
if (balances[_from] != 0 && !isContract(_from)) {
coinAgeRecordMap[_from].push(CoinAgeRecord(balances[_from], _now));
emit CoinAgeResetEvent(_from, balances[_from], _now);
}
if (_value != 0 && !isContract(_to)) {
coinAgeRecordMap[_to].push(CoinAgeRecord(_value, _now));
emit CoinAgeRecordEvent(_to, _value, _now);
}
return true;
}
/**
* @dev Calculates and returns proof-of-stake reward for provided address
*
* @param _address address The address for which reward will be calculated
* @param _now timestamp The time for which the reward will be calculated
*/
function calculateRewardInternal(address _address, uint256 _now) private view returns (uint256) {
uint256 _coinAge = getCoinAgeInternal(_address, _now);
if (_coinAge <= 0) {
return 0;
}
uint256 interest = getAnnualInterest(_now);
return (_coinAge.mul(interest)).div(365 * 100);
}
/**
* @dev Calculates the coin age for given address and time.
*
* @param _address address The address for which coinage will be calculated
* @param _now timestamp The time for which the coinage will be calculated
*/
function getCoinAgeInternal(address _address, uint256 _now) private view returns (uint256 _coinAge) {
if (coinAgeRecordMap[_address].length <= 0) {
return 0;
}
for (uint256 i = 0; i < coinAgeRecordMap[_address].length; i++) {
if (_now < uint256(coinAgeRecordMap[_address][i].time).add(stakeMinAge)) {
continue;
}
uint256 secondsPassed = _now.sub(uint256(coinAgeRecordMap[_address][i].time));
if (secondsPassed > stakeMaxAge ) {
secondsPassed = stakeMaxAge;
}
_coinAge = _coinAge.add((coinAgeRecordMap[_address][i].amount).mul(secondsPassed.div(1 days)));
}
}
/**
* @dev Returns the annual interest rate for given time
*
* @param _now timestamp The time for which the annual interest will be calculated
*/
function getAnnualInterest(uint256 _now) private view returns(uint256 interest) {
if (stakeStartTime > 0 && _now >= stakeStartTime && totalSupply_ < MAX_TOTAL_SUPPLY) {
uint256 secondsPassed = _now.sub(stakeStartTime);
// 1st Year = 30% annually
if (secondsPassed <= 365 days) {
interest = 30;
} else if (secondsPassed <= 547 days) { // 2nd Year, 1st Half = 25% annually
interest = 25;
} else if (secondsPassed <= 730 days) { // 2nd Year, 2nd Half = 20% annually
interest = 20;
} else if (secondsPassed <= 911 days) { // 3rd Year, 1st Half = 15% annually
interest = 15;
} else if (secondsPassed <= 1094 days) { // 3rd Year, 2nd Half = 10% annually
interest = 10;
} else { // 4th Year Onwards = 5% annually
interest = 5;
}
} else {
interest = 0;
}
}
/**
* @dev Batch token transfer. Used by contract creator to distribute initial tokens.
* Does not record any coinage for the owner.
*
* @param _recipients Array of address
* @param _values Array of amount
*/
function batchTransfer(address[] _recipients, uint256[] _values) public onlyOwner returns (bool) {
require(_recipients.length > 0 && _recipients.length == _values.length);
uint256 total = 0;
for(uint256 i = 0; i < _values.length; i++) {
total = total.add(_values[i]);
}
require(total <= balances[msg.sender]);
uint64 _now = uint64(now); // solium-disable-line
for(uint256 j = 0; j < _recipients.length; j++){
balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]);
balances[msg.sender] = balances[msg.sender].sub(_values[j]);
emit Transfer(msg.sender, _recipients[j], _values[j]);
coinAgeRecordMap[_recipients[j]].push(CoinAgeRecord(_values[j], _now));
emit CoinAgeRecordEvent(_recipients[j], _values[j], _now);
}
return true;
}
}
|
solium-disable-line
|
return getCoinAgeInternal(msg.sender, now);
| 898,922 |
[
1,
18281,
5077,
17,
8394,
17,
1369,
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,
3639,
327,
1927,
885,
9692,
3061,
12,
3576,
18,
15330,
16,
2037,
1769,
4766,
12900,
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/1/0x381918ccf9d23d77dB78149BbD1dda74b68f160b/sources/GodOfFortune.sol
|
* @dev Returns the amount of tokens in existence./* @dev Returns the amount of tokens owned by `account`./* @dev Moves `amount` tokens from the caller's account to `recipient`. Returns a boolean value indicating whether the operation succeeded. Emits a {Transfer} event./* @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./* @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: Emits an {Approval} event./* @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./* @dev Emitted when `value` tokens are moved from one account (`from`) to another (`to`). Note that `value` may be zero./* @dev Emitted when the allowance of a `spender` for an `owner` is set by a call to {approve}. `value` is the new allowance./ 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 {
Casino-like game mechanics with fair algorithms and potentially more functionalities.
pragma solidity ^0.8.3;
}
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);
}
}
Casino-like game mechanics with fair algorithms and potentially more functionalities.
pragma solidity ^0.8.3;
}
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);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
| 3,038,693 |
[
1,
1356,
326,
3844,
434,
2430,
316,
15782,
18,
19,
225,
2860,
326,
3844,
434,
2430,
16199,
635,
1375,
4631,
8338,
19,
225,
490,
10829,
1375,
8949,
68,
2430,
628,
326,
4894,
1807,
2236,
358,
1375,
20367,
8338,
2860,
279,
1250,
460,
11193,
2856,
326,
1674,
15784,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
19,
225,
2860,
326,
4463,
1300,
434,
2430,
716,
1375,
87,
1302,
264,
68,
903,
506,
2935,
358,
17571,
603,
12433,
6186,
434,
1375,
8443,
68,
3059,
288,
13866,
1265,
5496,
1220,
353,
3634,
635,
805,
18,
1220,
460,
3478,
1347,
288,
12908,
537,
97,
578,
288,
13866,
1265,
97,
854,
2566,
18,
19,
225,
11511,
1375,
8949,
68,
487,
326,
1699,
1359,
434,
1375,
87,
1302,
264,
68,
1879,
326,
4894,
1807,
2430,
18,
2860,
279,
1250,
460,
11193,
2856,
326,
1674,
15784,
18,
21840,
6856,
30,
605,
359,
834,
716,
12770,
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,
12083,
14060,
10477,
288,
203,
39,
345,
15020,
17,
5625,
7920,
1791,
7472,
2102,
598,
284,
1826,
20032,
471,
13935,
1898,
18699,
1961,
18,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
23,
31,
203,
203,
97,
203,
203,
203,
565,
445,
775,
986,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
5411,
309,
261,
71,
411,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
276,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
39,
345,
15020,
17,
5625,
7920,
1791,
7472,
2102,
598,
284,
1826,
20032,
471,
13935,
1898,
18699,
1961,
18,
203,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
23,
31,
203,
203,
97,
203,
203,
203,
565,
445,
775,
986,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
5411,
309,
261,
71,
411,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
276,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
775,
1676,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
309,
261,
70,
405,
279,
13,
327,
261,
2
] |
// File: contracts/lib/math/SafeMath.sol
pragma solidity 0.5.12;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: contracts/lib/ownership/Ownable.sol
pragma solidity 0.5.12;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address public owner;
address public pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
owner = msg.sender;
emit OwnershipTransferred(address(0), owner);
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/lib/utils/ReentrancyGuard.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied 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.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
// File: contracts/Utils.sol
pragma solidity 0.5.12;
interface ERC20 {
function balanceOf(address account) external view returns (uint256);
}
interface MarketDapp {
// Returns the address to approve tokens for
function tokenReceiver(address[] calldata assetIds, uint256[] calldata dataValues, address[] calldata addresses) external view returns(address);
function trade(address[] calldata assetIds, uint256[] calldata dataValues, address[] calldata addresses, address payable recipient) external payable;
}
/// @title Util functions for the BrokerV2 contract for Switcheo Exchange
/// @author Switcheo Network
/// @notice Functions were moved from the BrokerV2 contract into this contract
/// so that the BrokerV2 contract would not exceed the maximum contract size of
/// 24 KB.
library Utils {
using SafeMath for uint256;
// The constants for EIP-712 are precompiled to reduce contract size,
// the original values are left here for reference and verification.
//
// bytes32 public constant EIP712_DOMAIN_TYPEHASH = keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract,",
// "bytes32 salt",
// ")"
// ));
// bytes32 public constant EIP712_DOMAIN_TYPEHASH = 0xd87cd6ef79d4e2b95e15ce8abf732db51ec771f1ca2edccf22a46c729ac56472;
//
// bytes32 public constant CONTRACT_NAME = keccak256("Switcheo Exchange");
// bytes32 public constant CONTRACT_VERSION = keccak256("2");
// uint256 public constant CHAIN_ID = 1;
// address public constant VERIFYING_CONTRACT = 0x7ee7Ca6E75dE79e618e88bDf80d0B1DB136b22D0;
// bytes32 public constant SALT = keccak256("switcheo-eth-salt");
// bytes32 public constant DOMAIN_SEPARATOR = keccak256(abi.encode(
// EIP712_DOMAIN_TYPEHASH,
// CONTRACT_NAME,
// CONTRACT_VERSION,
// CHAIN_ID,
// VERIFYING_CONTRACT,
// SALT
// ));
bytes32 public constant DOMAIN_SEPARATOR = 0x256c0713d13c6a01bd319a2f7edabde771b6c167d37c01778290d60b362ccc7d;
// bytes32 public constant OFFER_TYPEHASH = keccak256(abi.encodePacked(
// "Offer(",
// "address maker,",
// "address offerAssetId,",
// "uint256 offerAmount,",
// "address wantAssetId,",
// "uint256 wantAmount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant OFFER_TYPEHASH = 0xf845c83a8f7964bc8dd1a092d28b83573b35be97630a5b8a3b8ae2ae79cd9260;
// bytes32 public constant CANCEL_TYPEHASH = keccak256(abi.encodePacked(
// "Cancel(",
// "bytes32 offerHash,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// ")"
// ));
bytes32 public constant CANCEL_TYPEHASH = 0x46f6d088b1f0ff5a05c3f232c4567f2df96958e05457e6c0e1221dcee7d69c18;
// bytes32 public constant FILL_TYPEHASH = keccak256(abi.encodePacked(
// "Fill(",
// "address filler,",
// "address offerAssetId,",
// "uint256 offerAmount,",
// "address wantAssetId,",
// "uint256 wantAmount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant FILL_TYPEHASH = 0x5f59dbc3412a4575afed909d028055a91a4250ce92235f6790c155a4b2669e99;
// The Ether token address is set as the constant 0x00 for backwards
// compatibility
address private constant ETHER_ADDR = address(0);
uint256 private constant mask8 = ~(~uint256(0) << 8);
uint256 private constant mask16 = ~(~uint256(0) << 16);
uint256 private constant mask24 = ~(~uint256(0) << 24);
uint256 private constant mask32 = ~(~uint256(0) << 32);
uint256 private constant mask40 = ~(~uint256(0) << 40);
uint256 private constant mask48 = ~(~uint256(0) << 48);
uint256 private constant mask56 = ~(~uint256(0) << 56);
uint256 private constant mask120 = ~(~uint256(0) << 120);
uint256 private constant mask128 = ~(~uint256(0) << 128);
uint256 private constant mask136 = ~(~uint256(0) << 136);
uint256 private constant mask144 = ~(~uint256(0) << 144);
event Trade(
address maker,
address taker,
address makerGiveAsset,
uint256 makerGiveAmount,
address fillerGiveAsset,
uint256 fillerGiveAmount
);
/// @dev Calculates the balance increments for a set of trades
/// @param _values The _values param from the trade method
/// @param _incrementsLength Should match the value of _addresses.length / 2
/// from the trade method
/// @return An array of increments
function calculateTradeIncrements(
uint256[] memory _values,
uint256 _incrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory increments = new uint256[](_incrementsLength);
_creditFillBalances(increments, _values);
_creditMakerBalances(increments, _values);
_creditMakerFeeBalances(increments, _values);
return increments;
}
/// @dev Calculates the balance decrements for a set of trades
/// @param _values The _values param from the trade method
/// @param _decrementsLength Should match the value of _addresses.length / 2
/// from the trade method
/// @return An array of decrements
function calculateTradeDecrements(
uint256[] memory _values,
uint256 _decrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory decrements = new uint256[](_decrementsLength);
_deductFillBalances(decrements, _values);
_deductMakerBalances(decrements, _values);
return decrements;
}
/// @dev Calculates the balance increments for a set of network trades
/// @param _values The _values param from the networkTrade method
/// @param _incrementsLength Should match the value of _addresses.length / 2
/// from the networkTrade method
/// @return An array of increments
function calculateNetworkTradeIncrements(
uint256[] memory _values,
uint256 _incrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory increments = new uint256[](_incrementsLength);
_creditMakerBalances(increments, _values);
_creditMakerFeeBalances(increments, _values);
return increments;
}
/// @dev Calculates the balance decrements for a set of network trades
/// @param _values The _values param from the trade method
/// @param _decrementsLength Should match the value of _addresses.length / 2
/// from the networkTrade method
/// @return An array of decrements
function calculateNetworkTradeDecrements(
uint256[] memory _values,
uint256 _decrementsLength
)
public
pure
returns (uint256[] memory)
{
uint256[] memory decrements = new uint256[](_decrementsLength);
_deductMakerBalances(decrements, _values);
return decrements;
}
/// @dev Validates `BrokerV2.trade` parameters to ensure trade fairness,
/// see `BrokerV2.trade` for param details.
/// @param _values Values from `trade`
/// @param _hashes Hashes from `trade`
/// @param _addresses Addresses from `trade`
function validateTrades(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses,
address _operator
)
public
returns (bytes32[] memory)
{
_validateTradeInputLengths(_values, _hashes);
_validateUniqueOffers(_values);
_validateMatches(_values, _addresses);
_validateFillAmounts(_values);
_validateTradeData(_values, _addresses, _operator);
// validate signatures of all offers
_validateTradeSignatures(
_values,
_hashes,
_addresses,
OFFER_TYPEHASH,
0,
_values[0] & mask8 // numOffers
);
// validate signatures of all fills
_validateTradeSignatures(
_values,
_hashes,
_addresses,
FILL_TYPEHASH,
_values[0] & mask8, // numOffers
(_values[0] & mask8) + ((_values[0] & mask16) >> 8) // numOffers + numFills
);
_emitTradeEvents(_values, _addresses, new address[](0), false);
return _hashes;
}
/// @dev Validates `BrokerV2.networkTrade` parameters to ensure trade fairness,
/// see `BrokerV2.networkTrade` for param details.
/// @param _values Values from `networkTrade`
/// @param _hashes Hashes from `networkTrade`
/// @param _addresses Addresses from `networkTrade`
/// @param _operator Address of the `BrokerV2.operator`
function validateNetworkTrades(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses,
address _operator
)
public
pure
returns (bytes32[] memory)
{
_validateNetworkTradeInputLengths(_values, _hashes);
_validateUniqueOffers(_values);
_validateNetworkMatches(_values, _addresses, _operator);
_validateTradeData(_values, _addresses, _operator);
// validate signatures of all offers
_validateTradeSignatures(
_values,
_hashes,
_addresses,
OFFER_TYPEHASH,
0,
_values[0] & mask8 // numOffers
);
return _hashes;
}
/// @dev Executes trades against external markets,
/// see `BrokerV2.networkTrade` for param details.
/// @param _values Values from `networkTrade`
/// @param _addresses Addresses from `networkTrade`
/// @param _marketDapps See `BrokerV2.marketDapps`
function performNetworkTrades(
uint256[] memory _values,
address[] memory _addresses,
address[] memory _marketDapps
)
public
returns (uint256[] memory)
{
uint256[] memory increments = new uint256[](_addresses.length / 2);
// i = 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
uint256 end = _values.length;
// loop matches
for(i; i < end; i++) {
uint256[] memory data = new uint256[](9);
data[0] = _values[i]; // match data
data[1] = data[0] & mask8; // offerIndex
data[2] = (data[0] & mask24) >> 16; // operator.surplusAssetIndex
data[3] = _values[data[1] * 2 + 1]; // offer.dataA
data[4] = _values[data[1] * 2 + 2]; // offer.dataB
data[5] = ((data[3] & mask16) >> 8); // maker.offerAssetIndex
data[6] = ((data[3] & mask24) >> 16); // maker.wantAssetIndex
// amount of offerAssetId to take from the offer is equal to the match.takeAmount
data[7] = data[0] >> 128;
// expected amount to receive is: matchData.takeAmount * offer.wantAmount / offer.offerAmount
data[8] = data[7].mul(data[4] >> 128).div(data[4] & mask128);
address[] memory assetIds = new address[](3);
assetIds[0] = _addresses[data[5] * 2 + 1]; // offer.offerAssetId
assetIds[1] = _addresses[data[6] * 2 + 1]; // offer.wantAssetId
assetIds[2] = _addresses[data[2] * 2 + 1]; // surplusAssetId
uint256[] memory dataValues = new uint256[](3);
dataValues[0] = data[7]; // the proportion of offerAmount to offer
dataValues[1] = data[8]; // the proportion of wantAmount to receive for the offer
dataValues[2] = data[0]; // match data
increments[data[2]] = _performNetworkTrade(
assetIds,
dataValues,
_marketDapps,
_addresses
);
}
_emitTradeEvents(_values, _addresses, _marketDapps, true);
return increments;
}
/// @dev Validates the signature of a cancel invocation
/// @param _values The _values param from the cancel method
/// @param _hashes The _hashes param from the cancel method
/// @param _addresses The _addresses param from the cancel method
function validateCancel(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses
)
public
pure
{
bytes32 offerHash = hashOffer(_values, _addresses);
bytes32 cancelHash = keccak256(abi.encode(
CANCEL_TYPEHASH,
offerHash,
_addresses[4],
_values[1] >> 128
));
validateSignature(
cancelHash,
_addresses[0], // maker
uint8((_values[2] & mask144) >> 136), // v
_hashes[0], // r
_hashes[1], // s
((_values[2] & mask136) >> 128) != 0 // prefixedSignature
);
}
/// @dev Hashes an offer for the cancel method
/// @param _values The _values param from the cancel method
/// @param _addresses THe _addresses param from the cancel method
/// @return The hash of the offer
function hashOffer(
uint256[] memory _values,
address[] memory _addresses
)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(
OFFER_TYPEHASH,
_addresses[0], // maker
_addresses[1], // offerAssetId
_values[0] & mask128, // offerAmount
_addresses[2], // wantAssetId
_values[0] >> 128, // wantAmount
_addresses[3], // feeAssetId
_values[1] & mask128, // feeAmount
_values[2] >> 144 // offerNonce
));
}
/// @notice Approves a token transfer
/// @param _assetId The address of the token to approve
/// @param _spender The address of the spender to approve
/// @param _amount The number of tokens to approve
function approveTokenTransfer(
address _assetId,
address _spender,
uint256 _amount
)
public
{
_validateContractAddress(_assetId);
// Some tokens have an `approve` which returns a boolean and some do not.
// The ERC20 interface cannot be used here because it requires specifying
// an explicit return value, and an EVM exception would be raised when calling
// a token with the mismatched return value.
bytes memory payload = abi.encodeWithSignature(
"approve(address,uint256)",
_spender,
_amount
);
bytes memory returnData = _callContract(_assetId, payload);
// Ensure that the asset transfer succeeded
_validateContractCallResult(returnData);
}
/// @notice Transfers tokens into the contract
/// @param _user The address to transfer the tokens from
/// @param _assetId The address of the token to transfer
/// @param _amount The number of tokens to transfer
/// @param _expectedAmount The number of tokens expected to be received,
/// this may not match `_amount`, for example, tokens which have a
/// proportion burnt on transfer will have a different amount received.
function transferTokensIn(
address _user,
address _assetId,
uint256 _amount,
uint256 _expectedAmount
)
public
{
_validateContractAddress(_assetId);
uint256 initialBalance = tokenBalance(_assetId);
// Some tokens have a `transferFrom` which returns a boolean and some do not.
// The ERC20 interface cannot be used here because it requires specifying
// an explicit return value, and an EVM exception would be raised when calling
// a token with the mismatched return value.
bytes memory payload = abi.encodeWithSignature(
"transferFrom(address,address,uint256)",
_user,
address(this),
_amount
);
bytes memory returnData = _callContract(_assetId, payload);
// Ensure that the asset transfer succeeded
_validateContractCallResult(returnData);
uint256 finalBalance = tokenBalance(_assetId);
uint256 transferredAmount = finalBalance.sub(initialBalance);
require(transferredAmount == _expectedAmount, "Invalid transfer");
}
/// @notice Transfers tokens from the contract to a user
/// @param _receivingAddress The address to transfer the tokens to
/// @param _assetId The address of the token to transfer
/// @param _amount The number of tokens to transfer
function transferTokensOut(
address _receivingAddress,
address _assetId,
uint256 _amount
)
public
{
_validateContractAddress(_assetId);
// Some tokens have a `transfer` which returns a boolean and some do not.
// The ERC20 interface cannot be used here because it requires specifying
// an explicit return value, and an EVM exception would be raised when calling
// a token with the mismatched return value.
bytes memory payload = abi.encodeWithSignature(
"transfer(address,uint256)",
_receivingAddress,
_amount
);
bytes memory returnData = _callContract(_assetId, payload);
// Ensure that the asset transfer succeeded
_validateContractCallResult(returnData);
}
/// @notice Returns the number of tokens owned by this contract
/// @param _assetId The address of the token to query
function externalBalance(address _assetId) public view returns (uint256) {
if (_assetId == ETHER_ADDR) {
return address(this).balance;
}
return tokenBalance(_assetId);
}
/// @notice Returns the number of tokens owned by this contract.
/// @dev This will not work for Ether tokens, use `externalBalance` for
/// Ether tokens.
/// @param _assetId The address of the token to query
function tokenBalance(address _assetId) public view returns (uint256) {
return ERC20(_assetId).balanceOf(address(this));
}
/// @dev Validates that the specified `_hash` was signed by the specified `_user`.
/// This method supports the EIP712 specification, the older Ethereum
/// signed message specification is also supported for backwards compatibility.
/// @param _hash The original hash that was signed by the user
/// @param _user The user who signed the hash
/// @param _v The `v` component of the `_user`'s signature
/// @param _r The `r` component of the `_user`'s signature
/// @param _s The `s` component of the `_user`'s signature
/// @param _prefixed If true, the signature will be verified
/// against the Ethereum signed message specification instead of the
/// EIP712 specification
function validateSignature(
bytes32 _hash,
address _user,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool _prefixed
)
public
pure
{
bytes32 eip712Hash = keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
_hash
));
if (_prefixed) {
bytes32 prefixedHash = keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
eip712Hash
));
require(_user == ecrecover(prefixedHash, _v, _r, _s), "Invalid signature");
} else {
require(_user == ecrecover(eip712Hash, _v, _r, _s), "Invalid signature");
}
}
/// @dev Ensures that `_address` is not the zero address
/// @param _address The address to check
function validateAddress(address _address) public pure {
require(_address != address(0), "Invalid address");
}
/// @dev Credit fillers for each fill.wantAmount,and credit the operator
/// for each fill.feeAmount. See the `trade` method for param details.
/// @param _values Values from `trade`
function _creditFillBalances(
uint256[] memory _increments,
uint256[] memory _values
)
private
pure
{
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
// i + numFills * 2
uint256 end = i + ((_values[0] & mask16) >> 8) * 2;
// loop fills
for(i; i < end; i += 2) {
uint256 fillerWantAssetIndex = (_values[i] & mask24) >> 16;
uint256 wantAmount = _values[i + 1] >> 128;
// credit fill.wantAmount to filler
_increments[fillerWantAssetIndex] = _increments[fillerWantAssetIndex].add(wantAmount);
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
uint256 operatorFeeAssetIndex = ((_values[i] & mask40) >> 32);
// credit fill.feeAmount to operator
_increments[operatorFeeAssetIndex] = _increments[operatorFeeAssetIndex].add(feeAmount);
}
}
/// @dev Credit makers for each amount received through a matched fill.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _creditMakerBalances(
uint256[] memory _increments,
uint256[] memory _values
)
private
pure
{
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for(i; i < end; i++) {
// match.offerIndex
uint256 offerIndex = _values[i] & mask8;
// maker.wantAssetIndex
uint256 makerWantAssetIndex = (_values[1 + offerIndex * 2] & mask24) >> 16;
// match.takeAmount
uint256 amount = _values[i] >> 128;
// receiveAmount = match.takeAmount * offer.wantAmount / offer.offerAmount
amount = amount.mul(_values[2 + offerIndex * 2] >> 128)
.div(_values[2 + offerIndex * 2] & mask128);
// credit maker for the amount received from the match
_increments[makerWantAssetIndex] = _increments[makerWantAssetIndex].add(amount);
}
}
/// @dev Credit the operator for each offer.feeAmount if the offer has not
/// been recorded through a previous `trade` call.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _creditMakerFeeBalances(
uint256[] memory _increments,
uint256[] memory _values
)
private
pure
{
uint256 i = 1;
// i + numOffers * 2
uint256 end = i + (_values[0] & mask8) * 2;
// loop offers
for(i; i < end; i += 2) {
bool nonceTaken = ((_values[i] & mask128) >> 120) == 1;
if (nonceTaken) { continue; }
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
uint256 operatorFeeAssetIndex = (_values[i] & mask40) >> 32;
// credit make.feeAmount to operator
_increments[operatorFeeAssetIndex] = _increments[operatorFeeAssetIndex].add(feeAmount);
}
}
/// @dev Deduct tokens from fillers for each fill.offerAmount
/// and each fill.feeAmount.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _deductFillBalances(
uint256[] memory _decrements,
uint256[] memory _values
)
private
pure
{
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
// i + numFills * 2
uint256 end = i + ((_values[0] & mask16) >> 8) * 2;
// loop fills
for(i; i < end; i += 2) {
uint256 fillerOfferAssetIndex = (_values[i] & mask16) >> 8;
uint256 offerAmount = _values[i + 1] & mask128;
// deduct fill.offerAmount from filler
_decrements[fillerOfferAssetIndex] = _decrements[fillerOfferAssetIndex].add(offerAmount);
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
// deduct fill.feeAmount from filler
uint256 fillerFeeAssetIndex = (_values[i] & mask32) >> 24;
_decrements[fillerFeeAssetIndex] = _decrements[fillerFeeAssetIndex].add(feeAmount);
}
}
/// @dev Deduct tokens from makers for each offer.offerAmount
/// and each offer.feeAmount if the offer has not been recorded
/// through a previous `trade` call.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _deductMakerBalances(
uint256[] memory _decrements,
uint256[] memory _values
)
private
pure
{
uint256 i = 1;
// i + numOffers * 2
uint256 end = i + (_values[0] & mask8) * 2;
// loop offers
for(i; i < end; i += 2) {
bool nonceTaken = ((_values[i] & mask128) >> 120) == 1;
if (nonceTaken) { continue; }
uint256 makerOfferAssetIndex = (_values[i] & mask16) >> 8;
uint256 offerAmount = _values[i + 1] & mask128;
// deduct make.offerAmount from maker
_decrements[makerOfferAssetIndex] = _decrements[makerOfferAssetIndex].add(offerAmount);
uint256 feeAmount = _values[i] >> 128;
if (feeAmount == 0) { continue; }
// deduct make.feeAmount from maker
uint256 makerFeeAssetIndex = (_values[i] & mask32) >> 24;
_decrements[makerFeeAssetIndex] = _decrements[makerFeeAssetIndex].add(feeAmount);
}
}
/// @dev Emits trade events for easier tracking
/// @param _values The _values param from the trade / networkTrade method
/// @param _addresses The _addresses param from the trade / networkTrade method
/// @param _marketDapps The _marketDapps from BrokerV2
/// @param _forNetworkTrade Whether this is called from the networkTrade method
function _emitTradeEvents(
uint256[] memory _values,
address[] memory _addresses,
address[] memory _marketDapps,
bool _forNetworkTrade
)
private
{
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for(i; i < end; i++) {
uint256[] memory data = new uint256[](7);
data[0] = _values[i] & mask8; // match.offerIndex
data[1] = _values[1 + data[0] * 2] & mask8; // makerIndex
data[2] = (_values[1 + data[0] * 2] & mask16) >> 8; // makerOfferAssetIndex
data[3] = (_values[1 + data[0] * 2] & mask24) >> 16; // makerWantAssetIndex
data[4] = _values[i] >> 128; // match.takeAmount
// receiveAmount = match.takeAmount * offer.wantAmount / offer.offerAmount
data[5] = data[4].mul(_values[2 + data[0] * 2] >> 128)
.div(_values[2 + data[0] * 2] & mask128);
// match.fillIndex for `trade`, marketDappIndex for `networkTrade`
data[6] = (_values[i] & mask16) >> 8;
address filler;
if (_forNetworkTrade) {
filler = _marketDapps[data[6]];
} else {
uint256 fillerIndex = (_values[1 + data[6] * 2] & mask8);
filler = _addresses[fillerIndex * 2];
}
emit Trade(
_addresses[data[1] * 2], // maker
filler,
_addresses[data[2] * 2 + 1], // makerGiveAsset
data[4], // makerGiveAmount
_addresses[data[3] * 2 + 1], // fillerGiveAsset
data[5] // fillerGiveAmount
);
}
}
/// @notice Executes a trade against an external market.
/// @dev The initial Ether or token balance is compared with the
/// balance after the trade to ensure that the appropriate amounts of
/// tokens were taken and an appropriate amount received.
/// The trade will fail if the number of tokens received is less than
/// expected. If the number of tokens received is more than expected than
/// the excess tokens are transferred to the `BrokerV2.operator`.
/// @param _assetIds[0] The offerAssetId of the offer
/// @param _assetIds[1] The wantAssetId of the offer
/// @param _assetIds[2] The surplusAssetId
/// @param _dataValues[0] The number of tokens offerred
/// @param _dataValues[1] The number of tokens expected to be received
/// @param _dataValues[2] Match data
/// @param _marketDapps See `BrokerV2.marketDapps`
/// @param _addresses Addresses from `networkTrade`
function _performNetworkTrade(
address[] memory _assetIds,
uint256[] memory _dataValues,
address[] memory _marketDapps,
address[] memory _addresses
)
private
returns (uint256)
{
uint256 dappIndex = (_dataValues[2] & mask16) >> 8;
validateAddress(_marketDapps[dappIndex]);
MarketDapp marketDapp = MarketDapp(_marketDapps[dappIndex]);
uint256[] memory funds = new uint256[](6);
funds[0] = externalBalance(_assetIds[0]); // initialOfferTokenBalance
funds[1] = externalBalance(_assetIds[1]); // initialWantTokenBalance
if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) {
funds[2] = externalBalance(_assetIds[2]); // initialSurplusTokenBalance
}
uint256 ethValue = 0;
address tokenReceiver;
if (_assetIds[0] == ETHER_ADDR) {
ethValue = _dataValues[0]; // offerAmount
} else {
tokenReceiver = marketDapp.tokenReceiver(_assetIds, _dataValues, _addresses);
approveTokenTransfer(
_assetIds[0], // offerAssetId
tokenReceiver,
_dataValues[0] // offerAmount
);
}
marketDapp.trade.value(ethValue)(
_assetIds,
_dataValues,
_addresses,
// use uint160 to cast `address` to `address payable`
address(uint160(address(this))) // destAddress
);
funds[3] = externalBalance(_assetIds[0]); // finalOfferTokenBalance
funds[4] = externalBalance(_assetIds[1]); // finalWantTokenBalance
if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) {
funds[5] = externalBalance(_assetIds[2]); // finalSurplusTokenBalance
}
uint256 surplusAmount = 0;
// validate that the appropriate offerAmount was deducted
// surplusAssetId == offerAssetId
if (_assetIds[2] == _assetIds[0]) {
// surplusAmount = finalOfferTokenBalance - (initialOfferTokenBalance - offerAmount)
surplusAmount = funds[3].sub(funds[0].sub(_dataValues[0]));
} else {
// finalOfferTokenBalance == initialOfferTokenBalance - offerAmount
require(funds[3] == funds[0].sub(_dataValues[0]), "Invalid offer asset balance");
}
// validate that the appropriate wantAmount was credited
// surplusAssetId == wantAssetId
if (_assetIds[2] == _assetIds[1]) {
// surplusAmount = finalWantTokenBalance - (initialWantTokenBalance + wantAmount)
surplusAmount = funds[4].sub(funds[1].add(_dataValues[1]));
} else {
// finalWantTokenBalance == initialWantTokenBalance + wantAmount
require(funds[4] == funds[1].add(_dataValues[1]), "Invalid want asset balance");
}
// surplusAssetId != offerAssetId && surplusAssetId != wantAssetId
if (_assetIds[2] != _assetIds[0] && _assetIds[2] != _assetIds[1]) {
// surplusAmount = finalSurplusTokenBalance - initialSurplusTokenBalance
surplusAmount = funds[5].sub(funds[2]);
}
// set the approved token amount back to zero
if (_assetIds[0] != ETHER_ADDR) {
approveTokenTransfer(
_assetIds[0],
tokenReceiver,
0
);
}
return surplusAmount;
}
/// @dev Validates input lengths based on the expected format
/// detailed in the `trade` method.
/// @param _values Values from `trade`
/// @param _hashes Hashes from `trade`
function _validateTradeInputLengths(
uint256[] memory _values,
bytes32[] memory _hashes
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
uint256 numFills = (_values[0] & mask16) >> 8;
uint256 numMatches = (_values[0] & mask24) >> 16;
// Validate that bits(24..256) are zero
require(_values[0] >> 24 == 0, "Invalid trade input");
// It is enforced by other checks that if a fill is present
// then it must be completely filled so there must be at least one offer
// and at least one match in this case.
// It is possible to have one offer with no matches and no fills
// but that is blocked by this check as there is no foreseeable use
// case for it.
require(
numOffers > 0 && numFills > 0 && numMatches > 0,
"Invalid trade input"
);
require(
_values.length == 1 + numOffers * 2 + numFills * 2 + numMatches,
"Invalid _values.length"
);
require(
_hashes.length == (numOffers + numFills) * 2,
"Invalid _hashes.length"
);
}
/// @dev Validates input lengths based on the expected format
/// detailed in the `networkTrade` method.
/// @param _values Values from `networkTrade`
/// @param _hashes Hashes from `networkTrade`
function _validateNetworkTradeInputLengths(
uint256[] memory _values,
bytes32[] memory _hashes
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
uint256 numFills = (_values[0] & mask16) >> 8;
uint256 numMatches = (_values[0] & mask24) >> 16;
// Validate that bits(24..256) are zero
require(_values[0] >> 24 == 0, "Invalid networkTrade input");
// Validate that numFills is zero because the offers
// should be filled against external orders
require(
numOffers > 0 && numMatches > 0 && numFills == 0,
"Invalid networkTrade input"
);
require(
_values.length == 1 + numOffers * 2 + numMatches,
"Invalid _values.length"
);
require(
_hashes.length == numOffers * 2,
"Invalid _hashes.length"
);
}
/// @dev See the `BrokerV2.trade` method for an explanation of why offer
/// uniquness is required.
/// The set of offers in `_values` must be sorted such that offer nonces'
/// are arranged in a strictly ascending order.
/// This allows the validation of offer uniqueness to be done in O(N) time,
/// with N being the number of offers.
/// @param _values Values from `trade`
function _validateUniqueOffers(uint256[] memory _values) private pure {
uint256 numOffers = _values[0] & mask8;
uint256 prevNonce;
for(uint256 i = 0; i < numOffers; i++) {
uint256 nonce = (_values[i * 2 + 1] & mask120) >> 56;
if (i == 0) {
// Set the value of the first nonce
prevNonce = nonce;
continue;
}
require(nonce > prevNonce, "Invalid offer nonces");
prevNonce = nonce;
}
}
/// @dev Validate that for every match:
/// 1. offerIndexes fall within the range of offers
/// 2. fillIndexes falls within the range of fills
/// 3. offer.offerAssetId == fill.wantAssetId
/// 4. offer.wantAssetId == fill.offerAssetId
/// 5. takeAmount > 0
/// 6. (offer.wantAmount * takeAmount) % offer.offerAmount == 0
/// @param _values Values from `trade`
/// @param _addresses Addresses from `trade`
function _validateMatches(
uint256[] memory _values,
address[] memory _addresses
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
uint256 numFills = (_values[0] & mask16) >> 8;
uint256 i = 1 + numOffers * 2 + numFills * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 fillIndex = (_values[i] & mask16) >> 8;
require(offerIndex < numOffers, "Invalid match.offerIndex");
require(fillIndex >= numOffers && fillIndex < numOffers + numFills, "Invalid match.fillIndex");
require(
_addresses[_values[1 + offerIndex * 2] & mask8] !=
_addresses[_values[1 + fillIndex * 2] & mask8],
"offer.maker cannot be the same as fill.filler"
);
uint256 makerOfferAssetIndex = (_values[1 + offerIndex * 2] & mask16) >> 8;
uint256 makerWantAssetIndex = (_values[1 + offerIndex * 2] & mask24) >> 16;
uint256 fillerOfferAssetIndex = (_values[1 + fillIndex * 2] & mask16) >> 8;
uint256 fillerWantAssetIndex = (_values[1 + fillIndex * 2] & mask24) >> 16;
require(
_addresses[makerOfferAssetIndex * 2 + 1] ==
_addresses[fillerWantAssetIndex * 2 + 1],
"offer.offerAssetId does not match fill.wantAssetId"
);
require(
_addresses[makerWantAssetIndex * 2 + 1] ==
_addresses[fillerOfferAssetIndex * 2 + 1],
"offer.wantAssetId does not match fill.offerAssetId"
);
// require that bits(16..128) are all zero for every match
require((_values[i] & mask128) >> 16 == uint256(0), "Invalid match data");
uint256 takeAmount = _values[i] >> 128;
require(takeAmount > 0, "Invalid match.takeAmount");
uint256 offerDataB = _values[2 + offerIndex * 2];
// (offer.wantAmount * takeAmount) % offer.offerAmount == 0
require(
(offerDataB >> 128).mul(takeAmount).mod(offerDataB & mask128) == 0,
"Invalid amounts"
);
}
}
/// @dev Validate that for every match:
/// 1. offerIndexes fall within the range of offers
/// 2. _addresses[surplusAssetIndexes * 2] matches the operator address
/// 3. takeAmount > 0
/// 4. (offer.wantAmount * takeAmount) % offer.offerAmount == 0
/// @param _values Values from `trade`
/// @param _addresses Addresses from `trade`
/// @param _operator Address of the `BrokerV2.operator`
function _validateNetworkMatches(
uint256[] memory _values,
address[] memory _addresses,
address _operator
)
private
pure
{
uint256 numOffers = _values[0] & mask8;
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 surplusAssetIndex = (_values[i] & mask24) >> 16;
require(offerIndex < numOffers, "Invalid match.offerIndex");
require(_addresses[surplusAssetIndex * 2] == _operator, "Invalid operator address");
uint256 takeAmount = _values[i] >> 128;
require(takeAmount > 0, "Invalid match.takeAmount");
uint256 offerDataB = _values[2 + offerIndex * 2];
// (offer.wantAmount * takeAmount) % offer.offerAmount == 0
require(
(offerDataB >> 128).mul(takeAmount).mod(offerDataB & mask128) == 0,
"Invalid amounts"
);
}
}
/// @dev Validate that all fills will be completely filled by the specified
/// matches. See the `BrokerV2.trade` method for an explanation of why
/// fills must be completely filled.
/// @param _values Values from `trade`
function _validateFillAmounts(uint256[] memory _values) private pure {
// "filled" is used to store the sum of `takeAmount`s and `giveAmount`s.
// While a fill's `offerAmount` and `wantAmount` are combined to share
// a single uint256 value, each sum of `takeAmount`s and `giveAmount`s
// for a fill is tracked with an individual uint256 value.
// This is to prevent the verification from being vulnerable to overflow
// issues.
uint256[] memory filled = new uint256[](_values.length);
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 fillIndex = (_values[i] & mask16) >> 8;
uint256 takeAmount = _values[i] >> 128;
uint256 wantAmount = _values[2 + offerIndex * 2] >> 128;
uint256 offerAmount = _values[2 + offerIndex * 2] & mask128;
// giveAmount = takeAmount * wantAmount / offerAmount
uint256 giveAmount = takeAmount.mul(wantAmount).div(offerAmount);
// (1 + fillIndex * 2) would give the index of the first part
// of the data for the fill at fillIndex within `_values`,
// and (2 + fillIndex * 2) would give the index of the second part
filled[1 + fillIndex * 2] = filled[1 + fillIndex * 2].add(giveAmount);
filled[2 + fillIndex * 2] = filled[2 + fillIndex * 2].add(takeAmount);
}
// numOffers
i = _values[0] & mask8;
// i + numFills
end = i + ((_values[0] & mask16) >> 8);
// loop fills
for(i; i < end; i++) {
require(
// fill.offerAmount == (sum of given amounts for fill)
_values[i * 2 + 2] & mask128 == filled[i * 2 + 1] &&
// fill.wantAmount == (sum of taken amounts for fill)
_values[i * 2 + 2] >> 128 == filled[i * 2 + 2],
"Invalid fills"
);
}
}
/// @dev Validates that for every offer / fill
/// 1. user address matches address referenced by user.offerAssetIndex
/// 2. user address matches address referenced by user.wantAssetIndex
/// 3. user address matches address referenced by user.feeAssetIndex
/// 4. offerAssetId != wantAssetId
/// 5. offerAmount > 0 && wantAmount > 0
/// 6. Specified `operator` address matches the expected `operator` address,
/// 7. Specified `operator.feeAssetId` matches the offer's feeAssetId
/// @param _values Values from `trade`
/// @param _addresses Addresses from `trade`
function _validateTradeData(
uint256[] memory _values,
address[] memory _addresses,
address _operator
)
private
pure
{
// numOffers + numFills
uint256 end = (_values[0] & mask8) +
((_values[0] & mask16) >> 8);
for (uint256 i = 0; i < end; i++) {
uint256 dataA = _values[i * 2 + 1];
uint256 dataB = _values[i * 2 + 2];
uint256 feeAssetIndex = ((dataA & mask40) >> 32) * 2;
require(
// user address == user in user.offerAssetIndex pair
_addresses[(dataA & mask8) * 2] ==
_addresses[((dataA & mask16) >> 8) * 2],
"Invalid user in user.offerAssetIndex"
);
require(
// user address == user in user.wantAssetIndex pair
_addresses[(dataA & mask8) * 2] ==
_addresses[((dataA & mask24) >> 16) * 2],
"Invalid user in user.wantAssetIndex"
);
require(
// user address == user in user.feeAssetIndex pair
_addresses[(dataA & mask8) * 2] ==
_addresses[((dataA & mask32) >> 24) * 2],
"Invalid user in user.feeAssetIndex"
);
require(
// offerAssetId != wantAssetId
_addresses[((dataA & mask16) >> 8) * 2 + 1] !=
_addresses[((dataA & mask24) >> 16) * 2 + 1],
"Invalid trade assets"
);
require(
// offerAmount > 0 && wantAmount > 0
(dataB & mask128) > 0 && (dataB >> 128) > 0,
"Invalid trade amounts"
);
require(
_addresses[feeAssetIndex] == _operator,
"Invalid operator address"
);
require(
_addresses[feeAssetIndex + 1] ==
_addresses[((dataA & mask32) >> 24) * 2 + 1],
"Invalid operator fee asset ID"
);
}
}
/// @dev Validates signatures for a set of offers or fills
/// Note that the r value of the offer / fill in _hashes will be
/// overwritten by the hash of that offer / fill
/// @param _values Values from `trade`
/// @param _hashes Hashes from `trade`
/// @param _addresses Addresses from `trade`
/// @param _typehash The typehash used to construct the signed hash
/// @param _i The starting index to verify
/// @param _end The ending index to verify
/// @return An array of hash keys if _i started as 0, because only
/// the hash keys of offers are needed
function _validateTradeSignatures(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses,
bytes32 _typehash,
uint256 _i,
uint256 _end
)
private
pure
{
for (_i; _i < _end; _i++) {
uint256 dataA = _values[_i * 2 + 1];
uint256 dataB = _values[_i * 2 + 2];
bytes32 hashKey = keccak256(abi.encode(
_typehash,
_addresses[(dataA & mask8) * 2], // user
_addresses[((dataA & mask16) >> 8) * 2 + 1], // offerAssetId
dataB & mask128, // offerAmount
_addresses[((dataA & mask24) >> 16) * 2 + 1], // wantAssetId
dataB >> 128, // wantAmount
_addresses[((dataA & mask32) >> 24) * 2 + 1], // feeAssetId
dataA >> 128, // feeAmount
(dataA & mask120) >> 56 // nonce
));
bool prefixedSignature = ((dataA & mask56) >> 48) != 0;
validateSignature(
hashKey,
_addresses[(dataA & mask8) * 2], // user
uint8((dataA & mask48) >> 40), // The `v` component of the user's signature
_hashes[_i * 2], // The `r` component of the user's signature
_hashes[_i * 2 + 1], // The `s` component of the user's signature
prefixedSignature
);
_hashes[_i * 2] = hashKey;
}
}
/// @dev Ensure that the address is a deployed contract
/// @param _contract The address to check
function _validateContractAddress(address _contract) private view {
assembly {
if iszero(extcodesize(_contract)) { revert(0, 0) }
}
}
/// @dev A thin wrapper around the native `call` function, to
/// validate that the contract `call` must be successful.
/// See https://solidity.readthedocs.io/en/v0.5.1/050-breaking-changes.html
/// for details on constructing the `_payload`
/// @param _contract Address of the contract to call
/// @param _payload The data to call the contract with
/// @return The data returned from the contract call
function _callContract(
address _contract,
bytes memory _payload
)
private
returns (bytes memory)
{
bool success;
bytes memory returnData;
(success, returnData) = _contract.call(_payload);
require(success, "Contract call failed");
return returnData;
}
/// @dev Fix for ERC-20 tokens that do not have proper return type
/// See: https://github.com/ethereum/solidity/issues/4116
/// https://medium.com/loopring-protocol/an-incompatibility-in-smart-contract-threatening-dapp-ecosystem-72b8ca5db4da
/// https://github.com/sec-bit/badERC20Fix/blob/master/badERC20Fix.sol
/// @param _data The data returned from a transfer call
function _validateContractCallResult(bytes memory _data) private pure {
require(
_data.length == 0 ||
(_data.length == 32 && _getUint256FromBytes(_data) != 0),
"Invalid contract call result"
);
}
/// @dev Converts data of type `bytes` into its corresponding `uint256` value
/// @param _data The data in bytes
/// @return The corresponding `uint256` value
function _getUint256FromBytes(
bytes memory _data
)
private
pure
returns (uint256)
{
uint256 parsed;
assembly { parsed := mload(add(_data, 32)) }
return parsed;
}
}
// File: contracts/BrokerV2.sol
pragma solidity 0.5.12;
interface IERC1820Registry {
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
}
interface TokenList {
function validateToken(address assetId) external view;
}
interface SpenderList {
function validateSpender(address spender) external view;
function validateSpenderAuthorization(address user, address spender) external view;
}
/// @title The BrokerV2 contract for Switcheo Exchange
/// @author Switcheo Network
/// @notice This contract faciliates Ethereum and Ethereum token trades
/// between users.
/// Users can trade with each other by making and taking offers without
/// giving up custody of their tokens.
/// Users should first deposit tokens, then communicate off-chain
/// with the exchange coordinator, in order to place orders.
/// This allows trades to be confirmed immediately by the coordinator,
/// and settled on-chain through this contract at a later time.
///
/// @dev Bit compacting is used in the contract to reduce gas costs, when
/// it is used, params are documented as bits(n..m).
/// This means that the documented value is represented by bits starting
/// from and including `n`, up to and excluding `m`.
/// For example, bits(8..16), indicates that the value is represented by bits:
/// [8, 9, 10, 11, 12, 13, 14, 15].
///
/// Bit manipulation of the form (data & ~(~uint(0) << m)) >> n is frequently
/// used to recover the value at the specified bits.
/// For example, to recover bits(2..7) from a uint8 value, we can use
/// (data & ~(~uint8(0) << 7)) >> 2.
/// Given a `data` value of `1101,0111`, bits(2..7) should give "10101".
/// ~uint8(0): "1111,1111" (8 ones)
/// (~uint8(0) << 7): "1000,0000" (1 followed by 7 zeros)
/// ~(~uint8(0) << 7): "0111,1111" (0 followed by 7 ones)
/// (data & ~(~uint8(0) << 7)): "0101,0111" (bits after the 7th bit is zeroed)
/// (data & ~(~uint8(0) << 7)) >> 2: "0001,0101" (matching the expected "10101")
///
/// Additionally, bit manipulation of the form data >> n is used to recover
/// bits(n..e), where e is equal to the number of bits in the data.
/// For example, to recover bits(4..8) from a uint8 value, we can use data >> 4.
/// Given a data value of "1111,1111", bits(4..8) should give "1111".
/// data >> 4: "0000,1111" (matching the expected "1111")
///
/// There is frequent reference and usage of asset IDs, this is a unique
/// identifier used within the contract to represent individual assets.
/// For all tokens, the asset ID is identical to the contract address
/// of the token, this is so that additional mappings are not needed to
/// identify tokens during deposits and withdrawals.
/// The only exception is the Ethereum token, which does not have a contract
/// address, for this reason, the zero address is used to represent the
/// Ethereum token's ID.
contract BrokerV2 is Ownable, ReentrancyGuard {
using SafeMath for uint256;
struct WithdrawalAnnouncement {
uint256 amount;
uint256 withdrawableAt;
}
// Exchange states
enum State { Active, Inactive }
// Exchange admin states
enum AdminState { Normal, Escalated }
// The constants for EIP-712 are precompiled to reduce contract size,
// the original values are left here for reference and verification.
//
// bytes32 public constant WITHDRAW_TYPEHASH = keccak256(abi.encodePacked(
// "Withdraw(",
// "address withdrawer,",
// "address receivingAddress,",
// "address assetId,",
// "uint256 amount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant WITHDRAW_TYPEHASH = 0xbe2f4292252fbb88b129dc7717b2f3f74a9afb5b13a2283cac5c056117b002eb;
// bytes32 public constant OFFER_TYPEHASH = keccak256(abi.encodePacked(
// "Offer(",
// "address maker,",
// "address offerAssetId,",
// "uint256 offerAmount,",
// "address wantAssetId,",
// "uint256 wantAmount,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant OFFER_TYPEHASH = 0xf845c83a8f7964bc8dd1a092d28b83573b35be97630a5b8a3b8ae2ae79cd9260;
// bytes32 public constant SWAP_TYPEHASH = keccak256(abi.encodePacked(
// "Swap(",
// "address maker,",
// "address taker,",
// "address assetId,",
// "uint256 amount,",
// "bytes32 hashedSecret,",
// "uint256 expiryTime,",
// "address feeAssetId,",
// "uint256 feeAmount,",
// "uint256 nonce",
// ")"
// ));
bytes32 public constant SWAP_TYPEHASH = 0x6ba9001457a287c210b728198a424a4222098d7fac48f8c5fb5ab10ef907d3ef;
// The Ether token address is set as the constant 0x00 for backwards
// compatibility
address private constant ETHER_ADDR = address(0);
// The maximum length of swap secret values
uint256 private constant MAX_SWAP_SECRET_LENGTH = 64;
// Reason codes are used by the off-chain coordinator to track balance changes
uint256 private constant REASON_DEPOSIT = 0x01;
uint256 private constant REASON_WITHDRAW = 0x09;
uint256 private constant REASON_WITHDRAW_FEE_GIVE = 0x14;
uint256 private constant REASON_WITHDRAW_FEE_RECEIVE = 0x15;
uint256 private constant REASON_CANCEL = 0x08;
uint256 private constant REASON_CANCEL_FEE_GIVE = 0x12;
uint256 private constant REASON_CANCEL_FEE_RECEIVE = 0x13;
uint256 private constant REASON_SWAP_GIVE = 0x30;
uint256 private constant REASON_SWAP_FEE_GIVE = 0x32;
uint256 private constant REASON_SWAP_RECEIVE = 0x35;
uint256 private constant REASON_SWAP_FEE_RECEIVE = 0x37;
uint256 private constant REASON_SWAP_CANCEL_RECEIVE = 0x38;
uint256 private constant REASON_SWAP_CANCEL_FEE_RECEIVE = 0x3B;
uint256 private constant REASON_SWAP_CANCEL_FEE_REFUND = 0x3D;
// 7 days * 24 hours * 60 mins * 60 seconds: 604800
uint256 private constant MAX_SLOW_WITHDRAW_DELAY = 604800;
uint256 private constant MAX_SLOW_CANCEL_DELAY = 604800;
uint256 private constant mask8 = ~(~uint256(0) << 8);
uint256 private constant mask16 = ~(~uint256(0) << 16);
uint256 private constant mask24 = ~(~uint256(0) << 24);
uint256 private constant mask32 = ~(~uint256(0) << 32);
uint256 private constant mask40 = ~(~uint256(0) << 40);
uint256 private constant mask120 = ~(~uint256(0) << 120);
uint256 private constant mask128 = ~(~uint256(0) << 128);
uint256 private constant mask136 = ~(~uint256(0) << 136);
uint256 private constant mask144 = ~(~uint256(0) << 144);
State public state;
AdminState public adminState;
// All fees will be transferred to the operator address
address public operator;
TokenList public tokenList;
SpenderList public spenderList;
// The delay in seconds to complete the respective escape hatch (`slowCancel` / `slowWithdraw`).
// This gives the off-chain service time to update the off-chain state
// before the state is separately updated by the user.
uint256 public slowCancelDelay;
uint256 public slowWithdrawDelay;
// A mapping of remaining offer amounts: offerHash => availableAmount
mapping(bytes32 => uint256) public offers;
// A mapping of used nonces: nonceIndex => nonceData
// The storing of nonces is used to ensure that transactions signed by
// the user can only be used once.
// For space and gas cost efficiency, one nonceData is used to store the
// state of 256 nonces.
// This reduces the average cost of storing a new nonce from 20,000 gas
// to 5000 + 20,000 / 256 = 5078.125 gas
// See _markNonce and _nonceTaken for more details.
mapping(uint256 => uint256) public usedNonces;
// A mapping of user balances: userAddress => assetId => balance
mapping(address => mapping(address => uint256)) public balances;
// A mapping of atomic swap states: swapHash => isSwapActive
mapping(bytes32 => bool) public atomicSwaps;
// A record of admin addresses: userAddress => isAdmin
mapping(address => bool) public adminAddresses;
// A record of market DApp addresses
address[] public marketDapps;
// A mapping of cancellation announcements for the cancel escape hatch: offerHash => cancellableAt
mapping(bytes32 => uint256) public cancellationAnnouncements;
// A mapping of withdrawal announcements: userAddress => assetId => { amount, withdrawableAt }
mapping(address => mapping(address => WithdrawalAnnouncement)) public withdrawalAnnouncements;
// Emitted on positive balance state transitions
event BalanceIncrease(
address indexed user,
address indexed assetId,
uint256 amount,
uint256 reason,
uint256 nonce
);
// Emitted on negative balance state transitions
event BalanceDecrease(
address indexed user,
address indexed assetId,
uint256 amount,
uint256 reason,
uint256 nonce
);
// Compacted versions of the `BalanceIncrease` and `BalanceDecrease` events.
// These are used in the `trade` method, they are compacted to save gas costs.
event Increment(uint256 data);
event Decrement(uint256 data);
event TokenFallback(
address indexed user,
address indexed assetId,
uint256 amount
);
event TokensReceived(
address indexed user,
address indexed assetId,
uint256 amount
);
event AnnounceCancel(
bytes32 indexed offerHash,
uint256 cancellableAt
);
event SlowCancel(
bytes32 indexed offerHash,
uint256 amount
);
event AnnounceWithdraw(
address indexed withdrawer,
address indexed assetId,
uint256 amount,
uint256 withdrawableAt
);
event SlowWithdraw(
address indexed withdrawer,
address indexed assetId,
uint256 amount
);
/// @notice Initializes the Broker contract
/// @dev The coordinator, operator and owner (through Ownable) is initialized
/// to be the address of the sender.
/// The Broker is put into an active state, with maximum exit delays set.
/// The Broker is also registered as an implementer of ERC777TokensRecipient
/// through the ERC1820 registry.
constructor(address _tokenListAddress, address _spenderListAddress) public {
adminAddresses[msg.sender] = true;
operator = msg.sender;
tokenList = TokenList(_tokenListAddress);
spenderList = SpenderList(_spenderListAddress);
slowWithdrawDelay = MAX_SLOW_WITHDRAW_DELAY;
slowCancelDelay = MAX_SLOW_CANCEL_DELAY;
state = State.Active;
IERC1820Registry erc1820 = IERC1820Registry(
0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24
);
erc1820.setInterfaceImplementer(
address(this),
keccak256("ERC777TokensRecipient"),
address(this)
);
}
modifier onlyAdmin() {
// Error code 1: onlyAdmin, address is not an admin address
require(adminAddresses[msg.sender], "1");
_;
}
modifier onlyActiveState() {
// Error code 2: onlyActiveState, state is not 'Active'
require(state == State.Active, "2");
_;
}
modifier onlyEscalatedAdminState() {
// Error code 3: onlyEscalatedAdminState, adminState is not 'Escalated'
require(adminState == AdminState.Escalated, "3");
_;
}
/// @notice Checks whether an address is appointed as an admin user
/// @param _user The address to check
/// @return Whether the address is appointed as an admin user
function isAdmin(address _user) external view returns(bool) {
return adminAddresses[_user];
}
/// @notice Sets tbe Broker's state.
/// @dev The two available states are `Active` and `Inactive`.
/// The `Active` state allows for regular exchange activity,
/// while the `Inactive` state prevents the invocation of deposit
/// and trading functions.
/// The `Inactive` state is intended as a means to cease contract operation
/// in the case of an upgrade or in an emergency.
/// @param _state The state to transition the contract into
function setState(State _state) external onlyOwner nonReentrant { state = _state; }
/// @notice Sets the Broker's admin state.
/// @dev The two available states are `Normal` and `Escalated`.
/// In the `Normal` admin state, the admin methods `adminCancel` and `adminWithdraw`
/// are not invocable.
/// The admin state must be set to `Escalated` by the contract owner for these
/// methods to become usable.
/// In an `Escalated` admin state, admin addresses would be able to cancel offers
/// and withdraw balances to the respective user's wallet on behalf of users.
/// The escalated state is intended to be used in the case of a contract upgrade or
/// in an emergency.
/// It is set separately from the `Inactive` state so that it is possible
/// to use admin functions without affecting regular operations.
/// @param _state The admin state to transition the contract into
function setAdminState(AdminState _state) external onlyOwner nonReentrant { adminState = _state; }
/// @notice Sets the operator address.
/// @dev All fees will be transferred to the operator address.
/// @param _operator The address to set as the operator
function setOperator(address _operator) external onlyOwner nonReentrant {
_validateAddress(operator);
operator = _operator;
}
/// @notice Sets the minimum delay between an `announceCancel` call and
/// when the cancellation can actually be executed through `slowCancel`.
/// @dev This gives the off-chain service time to update the off-chain state
/// before the state is separately updated by the user.
/// This differs from the regular `cancel` operation, which does not involve a delay.
/// @param _delay The delay in seconds
function setSlowCancelDelay(uint256 _delay) external onlyOwner nonReentrant {
// Error code 4: setSlowCancelDelay, slow cancel delay exceeds max allowable delay
require(_delay <= MAX_SLOW_CANCEL_DELAY, "4");
slowCancelDelay = _delay;
}
/// @notice Sets the delay between an `announceWithdraw` call and
/// when the withdrawal can actually be executed through `slowWithdraw`.
/// @dev This gives the off-chain service time to update the off-chain state
/// before the state is separately updated by the user.
/// This differs from the regular `withdraw` operation, which does not involve a delay.
/// @param _delay The delay in seconds
function setSlowWithdrawDelay(uint256 _delay) external onlyOwner nonReentrant {
// Error code 5: setSlowWithdrawDelay, slow withdraw delay exceeds max allowable delay
require(_delay <= MAX_SLOW_WITHDRAW_DELAY, "5");
slowWithdrawDelay = _delay;
}
/// @notice Gives admin permissons to the specified address.
/// @dev Admin addresses are intended to coordinate the regular operation
/// of the Broker contract, and to perform special functions such as
/// `adminCancel` and `adminWithdraw`.
/// @param _admin The address to give admin permissions to
function addAdmin(address _admin) external onlyOwner nonReentrant {
_validateAddress(_admin);
// Error code 6: addAdmin, address is already an admin address
require(!adminAddresses[_admin], "6");
adminAddresses[_admin] = true;
}
/// @notice Removes admin permissons for the specified address.
/// @param _admin The admin address to remove admin permissions from
function removeAdmin(address _admin) external onlyOwner nonReentrant {
_validateAddress(_admin);
// Error code 7: removeAdmin, address is not an admin address
require(adminAddresses[_admin], "7");
delete adminAddresses[_admin];
}
/// @notice Adds a market DApp to be used in `networkTrade`
/// @param _dapp Address of the market DApp
function addMarketDapp(address _dapp) external onlyOwner nonReentrant {
_validateAddress(_dapp);
marketDapps.push(_dapp);
}
/// @notice Updates a market DApp to be used in `networkTrade`
/// @param _index Index of the market DApp to update
/// @param _dapp The new address of the market DApp
function updateMarketDapp(uint256 _index, address _dapp) external onlyOwner nonReentrant {
_validateAddress(_dapp);
// Error code 8: updateMarketDapp, _index does not refer to an existing non-zero address
require(marketDapps[_index] != address(0), "8");
marketDapps[_index] = _dapp;
}
/// @notice Removes a market DApp
/// @param _index Index of the market DApp to remove
function removeMarketDapp(uint256 _index) external onlyOwner nonReentrant {
// Error code 9: removeMarketDapp, _index does not refer to a DApp address
require(marketDapps[_index] != address(0), "9");
delete marketDapps[_index];
}
/// @notice Performs a balance transfer from one address to another
/// @dev This method is intended to be invoked by spender contracts.
/// To invoke this method, a spender contract must have been
/// previously whitelisted and also authorized by the address from which
/// funds will be deducted.
/// Balance events are not emitted by this method, they should be separately
/// emitted by the spender contract.
/// @param _from The address to deduct from
/// @param _to The address to credit
/// @param _assetId The asset to transfer
/// @param _amount The amount to transfer
function spendFrom(
address _from,
address _to,
address _assetId,
uint256 _amount
)
external
nonReentrant
{
spenderList.validateSpenderAuthorization(_from, msg.sender);
_validateAddress(_to);
balances[_from][_assetId] = balances[_from][_assetId].sub(_amount);
balances[_to][_assetId] = balances[_to][_assetId].add(_amount);
}
/// @notice Allows a whitelisted contract to mark nonces
/// @dev If the whitelisted contract is malicious or vulnerable then there is
/// a possibility of a DoS attack. However, since this attack requires cooperation
/// of the contract owner, the risk is similar to the contract owner withholding
/// transactions, so there is no violation of the contract's trust model.
/// In the case that nonces are misused, users will still be able to cancel their offers
/// and withdraw all their funds using the escape hatch methods.
/// @param _nonce The nonce to mark
function markNonce(uint256 _nonce) external nonReentrant {
spenderList.validateSpender(msg.sender);
_markNonce(_nonce);
}
/// @notice Returns whether a nonce has been taken
/// @param _nonce The nonce to check
/// @return Whether the nonce has been taken
function nonceTaken(uint256 _nonce) external view returns (bool) {
return _nonceTaken(_nonce);
}
/// @notice Deposits ETH into the sender's contract balance
/// @dev This operation is only usable in an `Active` state
/// to prevent this contract from receiving ETH in the case that its
/// operation has been terminated.
function deposit() external payable onlyActiveState nonReentrant {
// Error code 10: deposit, msg.value is 0
require(msg.value > 0, "10");
_increaseBalance(msg.sender, ETHER_ADDR, msg.value, REASON_DEPOSIT, 0);
}
/// @dev This function is needed as market DApps generally send ETH
/// using the `<address>.transfer` method.
/// It is left empty to avoid issues with the function call running out
/// of gas, as some callers set a small limit on how much gas can be
/// used by the ETH receiver.
function() payable external {}
/// @notice Deposits ERC20 tokens under the `_user`'s balance
/// @dev Transfers token into the Broker contract using the
/// token's `transferFrom` method.
/// The user must have previously authorized the token transfer
/// through the token's `approve` method.
/// This method has separate `_amount` and `_expectedAmount` values
/// to support unconventional token transfers, e.g. tokens which have a
/// proportion burnt on transfer.
/// @param _user The address of the user depositing the tokens
/// @param _assetId The address of the token contract
/// @param _amount The value to invoke the token's `transferFrom` with
/// @param _expectedAmount The final amount expected to be received by this contract
/// @param _nonce A nonce for balance tracking, emitted in the BalanceIncrease event
function depositToken(
address _user,
address _assetId,
uint256 _amount,
uint256 _expectedAmount,
uint256 _nonce
)
external
onlyAdmin
onlyActiveState
nonReentrant
{
_increaseBalance(
_user,
_assetId,
_expectedAmount,
REASON_DEPOSIT,
_nonce
);
Utils.transferTokensIn(
_user,
_assetId,
_amount,
_expectedAmount
);
}
/// @notice Deposits ERC223 tokens under the `_user`'s balance
/// @dev ERC223 tokens should invoke this method when tokens are
/// sent to the Broker contract.
/// The invocation will fail unless the token has been previously
/// whitelisted through the `whitelistToken` method.
/// @param _user The address of the user sending the tokens
/// @param _amount The amount of tokens transferred to the Broker
function tokenFallback(
address _user,
uint _amount,
bytes calldata /* _data */
)
external
onlyActiveState
nonReentrant
{
address assetId = msg.sender;
tokenList.validateToken(assetId);
_increaseBalance(_user, assetId, _amount, REASON_DEPOSIT, 0);
emit TokenFallback(_user, assetId, _amount);
}
/// @notice Deposits ERC777 tokens under the `_user`'s balance
/// @dev ERC777 tokens should invoke this method when tokens are
/// sent to the Broker contract.
/// The invocation will fail unless the token has been previously
/// whitelisted through the `whitelistToken` method.
/// @param _user The address of the user sending the tokens
/// @param _to The address receiving the tokens
/// @param _amount The amount of tokens transferred to the Broker
function tokensReceived(
address /* _operator */,
address _user,
address _to,
uint _amount,
bytes calldata /* _userData */,
bytes calldata /* _operatorData */
)
external
onlyActiveState
nonReentrant
{
if (_to != address(this)) { return; }
address assetId = msg.sender;
tokenList.validateToken(assetId);
_increaseBalance(_user, assetId, _amount, REASON_DEPOSIT, 0);
emit TokensReceived(_user, assetId, _amount);
}
/// @notice Executes an array of offers and fills
/// @dev This method accepts an array of "offers" and "fills" together with
/// an array of "matches" to specify the matching between the "offers" and "fills".
/// The data is bit compacted for ease of index referencing and to reduce gas costs,
/// i.e. data representing different types of information is stored within one 256 bit value.
///
/// For efficient balance updates, the `_addresses` array is meant to contain a
/// unique set of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
/// This allows combining multiple balance updates for a user asset pair
/// into a single update by first calculating the total balance update for
/// a pair at a specified index, then looping through the sums to perform
/// the balance update.
///
/// The added benefit is further gas cost reduction because repeated
/// user asset pairs do not need to be duplicated for the calldata.
///
/// The operator address is enforced to be the contract's current operator
/// address, and the operator fee asset ID is enforced to be identical to
/// the maker's / filler's feeAssetId.
///
/// A tradeoff of compacting the bits is that there is a lower maximum value
/// for offer and fill data, however the limits remain generally practical.
///
/// For `offerAmount`, `wantAmount`, `feeAmount` values, the maximum value
/// is 2^128. For a token with 18 decimals, this allows support for tokens
/// with a maximum supply of 1000 million billion billion (33 zeros).
/// In the case where the maximum value needs to be exceeded, a single
/// offer / fill can be split into multiple offers / fills by the off-chain
/// service.
///
/// For nonces the maximum value is 2^64, or more than a billion billion (19 zeros).
///
/// Offers and fills both encompass information about how much (offerAmount)
/// of a specified token (offerAssetId) the user wants to offer and
/// how much (wantAmount) of another token (wantAssetId) they want
/// in return.
///
/// Each match specifies how much of the match's `offer.offerAmount` should
/// be transferred to the filler, in return, the offer's maker receives:
/// `offer.wantAmount * match.takeAmount / offer.offerAmount` of the
/// `offer.wantAssetId` from the filler.
///
/// A few restirctions are enforced to ensure fairness and security of trades:
/// 1. To prevent unfairness due to rounding issues, it is required that:
/// `offer.wantAmount * match.takeAmount % offer.offerAmount == 0`.
///
/// 2. Fills can be filled by offers which do not individually match
/// the `fill.offerAmount` and `fill.wantAmount` ratio. As such, it is
/// required that:
/// fill.offerAmount == total amount deducted from filler for the fill's
/// associated matches (excluding fees)
/// fill.wantAmount == total amount credited to filler for the fill's
/// associated matches (excluding fees)
///
/// 3. The offer array must not consist of repeated offers. For efficient
/// balance updates, a loop through each offer in the offer array is used
/// to deduct the offer.offerAmount from the respective maker
/// if the offer has not been recorded by a previos `trade` call.
/// If an offer is repeated in the offers array, then there would be
/// duplicate deductions from the maker.
/// To enforce uniqueness, it is required that offers for a trade transaction
/// are sorted such that their nonces are in a strictly ascending order.
///
/// 4. The fill array must not consist of repeated fills, for the same
/// reason why there cannot be repeated offers. Additionally, to prevent
/// replay attacks, all fill nonces are required to be unused.
///
/// @param _values[0] Number of offers, fills, matches
/// bits(0..8): number of offers (numOffers)
/// bits(8..16): number of fills (numFills)
/// bits(16..24): number of matches (numMatches)
/// bits(24..256): must be zero
///
/// @param _values[1 + i * 2] First part of offer data for the i'th offer
/// bits(0..8): Index of the maker's address in _addresses
/// bits(8..16): Index of the maker offerAssetId pair in _addresses
/// bits(16..24): Index of the maker wantAssetId pair in _addresses
/// bits(24..32): Index of the maker feeAssetId pair in _addresses
/// bits(32..40): Index of the operator feeAssetId pair in _addresses
/// bits(40..48): The `v` component of the maker's signature for this offer
/// bits(48..56): Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
/// bits(56..120): The offer nonce to prevent replay attacks
/// bits(120..128): Space to indicate whether the offer nonce has been marked before
/// bits(128..256): The number of tokens to be paid to the operator as fees for this offer
///
/// @param _values[2 + i * 2] Second part of offer data for the i'th offer
/// bits(0..128): offer.offerAmount, i.e. the number of tokens to offer
/// bits(128..256): offer.wantAmount, i.e. the number of tokens to ask for in return
///
/// @param _values[1 + numOffers * 2 + i * 2] First part of fill data for the i'th fill
/// bits(0..8): Index of the filler's address in _addresses
/// bits(8..16): Index of the filler offerAssetId pair in _addresses
/// bits(16..24): Index of the filler wantAssetId pair in _addresses
/// bits(24..32): Index of the filler feeAssetId pair in _addresses
/// bits(32..40): Index of the operator feeAssetId pair in _addresses
/// bits(40..48): The `v` component of the filler's signature for this fill
/// bits(48..56): Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
/// bits(56..120): The fill nonce to prevent replay attacks
/// bits(120..128): Left empty to match the offer values format
/// bits(128..256): The number of tokens to be paid to the operator as fees for this fill
///
/// @param _values[2 + numOffers * 2 + i * 2] Second part of fill data for the i'th fill
/// bits(0..128): fill.offerAmount, i.e. the number of tokens to offer
/// bits(128..256): fill.wantAmount, i.e. the number of tokens to ask for in return
///
/// @param _values[1 + numOffers * 2 + numFills * 2 + i] Data for the i'th match
/// bits(0..8): Index of the offerIndex for this match
/// bits(8..16): Index of the fillIndex for this match
/// bits(128..256): The number of tokens to take from the matched offer's offerAmount
///
/// @param _hashes[i * 2] The `r` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _hashes[i * 2 + 1] The `s` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
function trade(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses
)
public
onlyAdmin
onlyActiveState
nonReentrant
{
// Cache the operator address to reduce gas costs from storage reads
address operatorAddress = operator;
// An array variable to store balance increments / decrements
uint256[] memory statements;
// Cache whether offer nonces are taken in the offer's nonce space
_cacheOfferNonceStates(_values);
// `validateTrades` needs to calculate the hash keys of offers and fills
// to verify the signature of the offer / fill.
// The calculated hash keys are returned to reduce repeated computation.
_hashes = Utils.validateTrades(
_values,
_hashes,
_addresses,
operatorAddress
);
statements = Utils.calculateTradeIncrements(_values, _addresses.length / 2);
_incrementBalances(statements, _addresses, 1);
statements = Utils.calculateTradeDecrements(_values, _addresses.length / 2);
_decrementBalances(statements, _addresses);
// Reduce available offer amounts of offers and store the remaining
// offer amount in the `offers` mapping.
// Offer nonces will also be marked as taken.
_storeOfferData(_values, _hashes);
// Mark all fill nonces as taken in the `usedNonces` mapping.
_storeFillNonces(_values);
}
/// @notice Executes an array of offers against external orders.
/// @dev This method accepts an array of "offers" together with
/// an array of "matches" to specify the matching between the "offers" and
/// external orders.
/// The data is bit compacted and formatted in the same way as the `trade` function.
///
/// @param _values[0] Number of offers, fills, matches
/// bits(0..8): number of offers (numOffers)
/// bits(8..16): number of fills, must be zero
/// bits(16..24): number of matches (numMatches)
/// bits(24..256): must be zero
///
/// @param _values[1 + i * 2] First part of offer data for the i'th offer
/// bits(0..8): Index of the maker's address in _addresses
/// bits(8..16): Index of the maker offerAssetId pair in _addresses
/// bits(16..24): Index of the maker wantAssetId pair in _addresses
/// bits(24..32): Index of the maker feeAssetId pair in _addresses
/// bits(32..40): Index of the operator feeAssetId pair in _addresses
/// bits(40..48): The `v` component of the maker's signature for this offer
/// bits(48..56): Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
/// bits(56..120): The offer nonce to prevent replay attacks
/// bits(120..128): Space to indicate whether the offer nonce has been marked before
/// bits(128..256): The number of tokens to be paid to the operator as fees for this offer
///
/// @param _values[2 + i * 2] Second part of offer data for the i'th offer
/// bits(0..128): offer.offerAmount, i.e. the number of tokens to offer
/// bits(128..256): offer.wantAmount, i.e. the number of tokens to ask for in return
///
/// @param _values[1 + numOffers * 2 + i] Data for the i'th match
/// bits(0..8): Index of the offerIndex for this match
/// bits(8..16): Index of the marketDapp for this match
/// bits(16..24): Index of the surplus receiver and surplus asset ID for this
/// match, for any excess tokens resulting from the trade
/// bits(24..128): Additional DApp specific data
/// bits(128..256): The number of tokens to take from the matched offer's offerAmount
///
/// @param _hashes[i * 2] The `r` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _hashes[i * 2 + 1] The `s` component of the maker's / filler's signature
/// for the i'th offer / fill
///
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
function networkTrade(
uint256[] memory _values,
bytes32[] memory _hashes,
address[] memory _addresses
)
public
onlyAdmin
onlyActiveState
nonReentrant
{
// Cache the operator address to reduce gas costs from storage reads
address operatorAddress = operator;
// An array variable to store balance increments / decrements
uint256[] memory statements;
// Cache whether offer nonces are taken in the offer's nonce space
_cacheOfferNonceStates(_values);
// `validateNetworkTrades` needs to calculate the hash keys of offers
// to verify the signature of the offer.
// The calculated hash keys for each offer is return to reduce repeated
// computation.
_hashes = Utils.validateNetworkTrades(
_values,
_hashes,
_addresses,
operatorAddress
);
statements = Utils.calculateNetworkTradeIncrements(_values, _addresses.length / 2);
_incrementBalances(statements, _addresses, 1);
statements = Utils.calculateNetworkTradeDecrements(_values, _addresses.length / 2);
_decrementBalances(statements, _addresses);
// Reduce available offer amounts of offers and store the remaining
// offer amount in the `offers` mapping.
// Offer nonces will also be marked as taken.
_storeOfferData(_values, _hashes);
// There may be excess tokens resulting from a trade
// Any excess tokens are returned and recorded in `increments`
statements = Utils.performNetworkTrades(
_values,
_addresses,
marketDapps
);
_incrementBalances(statements, _addresses, 0);
}
/// @notice Cancels a perviously made offer and refunds the remaining offer
/// amount to the offer maker.
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// The `_expectedavailableamount` is required to help prevent accidental
/// cancellation of an offer ahead of time, for example, if there is
/// a pending fill in the off-chain state.
///
/// @param _values[0] The offerAmount and wantAmount of the offer
/// bits(0..128): offer.offerAmount
/// bits(128..256): offer.wantAmount
///
/// @param _values[1] The fee amounts
/// bits(0..128): offer.feeAmount
/// bits(128..256): cancelFeeAmount
///
/// @param _values[2] Additional offer and cancellation data
/// bits(0..128): expectedAvailableAmount
/// bits(128..136): prefixedSignature
/// bits(136..144): The `v` component of the maker's signature for the cancellation
/// bits(144..256): offer.nonce
///
/// @param _hashes[0] The `r` component of the maker's signature for the cancellation
/// @param _hashes[1] The `s` component of the maker's signature for the cancellation
///
/// @param _addresses[0] offer.maker
/// @param _addresses[1] offer.offerAssetId
/// @param _addresses[2] offer.wantAssetId
/// @param _addresses[3] offer.feeAssetId
/// @param _addresses[4] offer.cancelFeeAssetId
function cancel(
uint256[] calldata _values,
bytes32[] calldata _hashes,
address[] calldata _addresses
)
external
onlyAdmin
nonReentrant
{
Utils.validateCancel(_values, _hashes, _addresses);
bytes32 offerHash = Utils.hashOffer(_values, _addresses);
_cancel(
_addresses[0], // maker
offerHash,
_values[2] & mask128, // expectedAvailableAmount
_addresses[1], // offerAssetId
_values[2] >> 144, // offerNonce
_addresses[4], // cancelFeeAssetId
_values[1] >> 128 // cancelFeeAmount
);
}
/// @notice Cancels an offer without requiring the maker's signature
/// @dev This method is intended to be used in the case of a contract
/// upgrade or in an emergency. It can only be invoked by an admin and only
/// after the admin state has been set to `Escalated` by the contract owner.
///
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// The `_expectedavailableamount` is required to help prevent accidental
/// cancellation of an offer ahead of time, for example, if there is
/// a pending fill in the off-chain state.
/// @param _maker The address of the offer's maker
/// @param _offerAssetId The contract address of the offerred asset
/// @param _offerAmount The number of tokens offerred
/// @param _wantAssetId The contract address of the asset asked in return
/// @param _wantAmount The number of tokens asked for in return
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _offerNonce The nonce of the original offer
/// @param _expectedAvailableAmount The offer amount remaining
function adminCancel(
address _maker,
address _offerAssetId,
uint256 _offerAmount,
address _wantAssetId,
uint256 _wantAmount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _offerNonce,
uint256 _expectedAvailableAmount
)
external
onlyAdmin
onlyEscalatedAdminState
nonReentrant
{
bytes32 offerHash = keccak256(abi.encode(
OFFER_TYPEHASH,
_maker,
_offerAssetId,
_offerAmount,
_wantAssetId,
_wantAmount,
_feeAssetId,
_feeAmount,
_offerNonce
));
_cancel(
_maker,
offerHash,
_expectedAvailableAmount,
_offerAssetId,
_offerNonce,
address(0),
0
);
}
/// @notice Announces a user's intention to cancel their offer
/// @dev This method allows a user to cancel their offer without requiring
/// admin permissions.
/// An announcement followed by a delay is needed so that the off-chain
/// service has time to update the off-chain state.
///
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _maker The address of the offer's maker
/// @param _offerAssetId The contract address of the offerred asset
/// @param _offerAmount The number of tokens offerred
/// @param _wantAssetId The contract address of the asset asked in return
/// @param _wantAmount The number of tokens asked for in return
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _offerNonce The nonce of the original offer
function announceCancel(
address _maker,
address _offerAssetId,
uint256 _offerAmount,
address _wantAssetId,
uint256 _wantAmount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _offerNonce
)
external
nonReentrant
{
// Error code 11: announceCancel, invalid msg.sender
require(_maker == msg.sender, "11");
bytes32 offerHash = keccak256(abi.encode(
OFFER_TYPEHASH,
_maker,
_offerAssetId,
_offerAmount,
_wantAssetId,
_wantAmount,
_feeAssetId,
_feeAmount,
_offerNonce
));
// Error code 12: announceCancel, nothing left to cancel
require(offers[offerHash] > 0, "12");
uint256 cancellableAt = now.add(slowCancelDelay);
cancellationAnnouncements[offerHash] = cancellableAt;
emit AnnounceCancel(offerHash, cancellableAt);
}
/// @notice Executes an offer cancellation previously announced in `announceCancel`
/// @dev This method allows a user to cancel their offer without requiring
/// admin permissions.
/// An announcement followed by a delay is needed so that the off-chain
/// service has time to update the off-chain state.
///
/// To reduce gas costs, the original parameters of the offer are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _maker The address of the offer's maker
/// @param _offerAssetId The contract address of the offerred asset
/// @param _offerAmount The number of tokens offerred
/// @param _wantAssetId The contract address of the asset asked in return
/// @param _wantAmount The number of tokens asked for in return
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _offerNonce The nonce of the original offer
function slowCancel(
address _maker,
address _offerAssetId,
uint256 _offerAmount,
address _wantAssetId,
uint256 _wantAmount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _offerNonce
)
external
nonReentrant
{
bytes32 offerHash = keccak256(abi.encode(
OFFER_TYPEHASH,
_maker,
_offerAssetId,
_offerAmount,
_wantAssetId,
_wantAmount,
_feeAssetId,
_feeAmount,
_offerNonce
));
uint256 cancellableAt = cancellationAnnouncements[offerHash];
// Error code 13: slowCancel, cancellation was not announced
require(cancellableAt != 0, "13");
// Error code 14: slowCancel, cancellation delay not yet reached
require(now >= cancellableAt, "14");
uint256 availableAmount = offers[offerHash];
// Error code 15: slowCancel, nothing left to cancel
require(availableAmount > 0, "15");
delete cancellationAnnouncements[offerHash];
_cancel(
_maker,
offerHash,
availableAmount,
_offerAssetId,
_offerNonce,
address(0),
0
);
emit SlowCancel(offerHash, availableAmount);
}
/// @notice Withdraws tokens from the Broker contract to a user's wallet balance
/// @dev The user's internal balance is decreased, and the tokens are transferred
/// to the `_receivingAddress` signed by the user.
/// @param _withdrawer The user address whose balance will be reduced
/// @param _receivingAddress The address to tranfer the tokens to
/// @param _assetId The contract address of the token to withdraw
/// @param _amount The number of tokens to withdraw
/// @param _feeAssetId The contract address of the fee asset
/// @param _feeAmount The number of tokens to pay as fees to the operator
/// @param _nonce An unused nonce to prevent replay attacks
/// @param _v The `v` component of the `_user`'s signature
/// @param _r The `r` component of the `_user`'s signature
/// @param _s The `s` component of the `_user`'s signature
/// @param _prefixedSignature Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
function withdraw(
address _withdrawer,
address payable _receivingAddress,
address _assetId,
uint256 _amount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _nonce,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool _prefixedSignature
)
external
onlyAdmin
nonReentrant
{
_markNonce(_nonce);
_validateSignature(
keccak256(abi.encode(
WITHDRAW_TYPEHASH,
_withdrawer,
_receivingAddress,
_assetId,
_amount,
_feeAssetId,
_feeAmount,
_nonce
)),
_withdrawer,
_v,
_r,
_s,
_prefixedSignature
);
_withdraw(
_withdrawer,
_receivingAddress,
_assetId,
_amount,
_feeAssetId,
_feeAmount,
_nonce
);
}
/// @notice Withdraws tokens without requiring the withdrawer's signature
/// @dev This method is intended to be used in the case of a contract
/// upgrade or in an emergency. It can only be invoked by an admin and only
/// after the admin state has been set to `Escalated` by the contract owner.
/// Unlike `withdraw`, tokens can only be withdrawn to the `_withdrawer`'s
/// address.
/// @param _withdrawer The user address whose balance will be reduced
/// @param _assetId The contract address of the token to withdraw
/// @param _amount The number of tokens to withdraw
/// @param _nonce An unused nonce for balance tracking
function adminWithdraw(
address payable _withdrawer,
address _assetId,
uint256 _amount,
uint256 _nonce
)
external
onlyAdmin
onlyEscalatedAdminState
nonReentrant
{
_markNonce(_nonce);
_withdraw(
_withdrawer,
_withdrawer,
_assetId,
_amount,
address(0),
0,
_nonce
);
}
/// @notice Announces a user's intention to withdraw their funds
/// @dev This method allows a user to withdraw their funds without requiring
/// admin permissions.
/// An announcement followed by a delay before execution is needed so that
/// the off-chain service has time to update the off-chain state.
/// @param _assetId The contract address of the token to withdraw
/// @param _amount The number of tokens to withdraw
function announceWithdraw(
address _assetId,
uint256 _amount
)
external
nonReentrant
{
// Error code 16: announceWithdraw, invalid withdrawal amount
require(_amount > 0 && _amount <= balances[msg.sender][_assetId], "16");
WithdrawalAnnouncement storage announcement = withdrawalAnnouncements[msg.sender][_assetId];
announcement.withdrawableAt = now.add(slowWithdrawDelay);
announcement.amount = _amount;
emit AnnounceWithdraw(msg.sender, _assetId, _amount, announcement.withdrawableAt);
}
/// @notice Executes a withdrawal previously announced in `announceWithdraw`
/// @dev This method allows a user to withdraw their funds without requiring
/// admin permissions.
/// An announcement followed by a delay before execution is needed so that
/// the off-chain service has time to update the off-chain state.
/// @param _withdrawer The user address whose balance will be reduced
/// @param _assetId The contract address of the token to withdraw
function slowWithdraw(
address payable _withdrawer,
address _assetId,
uint256 _amount
)
external
nonReentrant
{
WithdrawalAnnouncement memory announcement = withdrawalAnnouncements[_withdrawer][_assetId];
// Error code 17: slowWithdraw, withdrawal was not announced
require(announcement.withdrawableAt != 0, "17");
// Error code 18: slowWithdraw, withdrawal delay not yet reached
require(now >= announcement.withdrawableAt, "18");
// Error code 19: slowWithdraw, withdrawal amount does not match announced amount
require(announcement.amount == _amount, "19");
delete withdrawalAnnouncements[_withdrawer][_assetId];
_withdraw(
_withdrawer,
_withdrawer,
_assetId,
_amount,
address(0),
0,
0
);
emit SlowWithdraw(_withdrawer, _assetId, _amount);
}
/// @notice Locks a user's balances for the first part of an atomic swap
/// @param _addresses[0] maker: the address of the user to deduct the swap tokens from
/// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens
/// if the swap is completed through `executeSwap`
/// @param _addresses[2] assetId: the contract address of the token to swap
/// @param _addresses[3] feeAssetId: the contract address of the token to use as fees
/// @param _values[0] amount: the number of tokens to lock and to transfer if the swap
/// is completed through `executeSwap`
/// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable
/// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees
/// @param _values[3] nonce: an unused nonce to prevent replay attacks
/// @param _hashes[0] hashedSecret: the hash of the secret decided by the maker
/// @param _hashes[1] The `r` component of the user's signature
/// @param _hashes[2] The `s` component of the user's signature
/// @param _v The `v` component of the user's signature
/// @param _prefixedSignature Indicates whether the Ethereum signed message
/// prefix should be prepended during signature verification
function createSwap(
address[4] calldata _addresses,
uint256[4] calldata _values,
bytes32[3] calldata _hashes,
uint8 _v,
bool _prefixedSignature
)
external
onlyAdmin
onlyActiveState
nonReentrant
{
// Error code 20: createSwap, invalid swap amount
require(_values[0] > 0, "20");
// Error code 21: createSwap, expiry time has already passed
require(_values[1] > now, "21");
_validateAddress(_addresses[1]);
// Error code 39: createSwap, swap maker cannot be the swap taker
require(_addresses[0] != _addresses[1], "39");
bytes32 swapHash = _hashSwap(_addresses, _values, _hashes[0]);
// Error code 22: createSwap, the swap is already active
require(!atomicSwaps[swapHash], "22");
_markNonce(_values[3]);
_validateSignature(
swapHash,
_addresses[0], // swap.maker
_v,
_hashes[1], // r
_hashes[2], // s
_prefixedSignature
);
if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId
// Error code 23: createSwap, swap.feeAmount exceeds swap.amount
require(_values[2] < _values[0], "23"); // feeAmount < amount
} else {
_decreaseBalance(
_addresses[0], // maker
_addresses[3], // feeAssetId
_values[2], // feeAmount
REASON_SWAP_FEE_GIVE,
_values[3] // nonce
);
}
_decreaseBalance(
_addresses[0], // maker
_addresses[2], // assetId
_values[0], // amount
REASON_SWAP_GIVE,
_values[3] // nonce
);
atomicSwaps[swapHash] = true;
}
/// @notice Executes a swap by transferring the tokens previously locked through
/// a `createSwap` call to the swap taker.
///
/// @dev To reduce gas costs, the original parameters of the swap are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _addresses[0] maker: the address of the user to deduct the swap tokens from
/// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens
/// @param _addresses[2] assetId: the contract address of the token to swap
/// @param _addresses[3] feeAssetId: the contract address of the token to use as fees
/// @param _values[0] amount: the number of tokens previously locked
/// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable
/// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees
/// @param _values[3] nonce: an unused nonce to prevent replay attacks
/// @param _hashedSecret The hash of the secret decided by the maker
/// @param _preimage The preimage of the `_hashedSecret`
function executeSwap(
address[4] calldata _addresses,
uint256[4] calldata _values,
bytes32 _hashedSecret,
bytes calldata _preimage
)
external
nonReentrant
{
// Error code 37: swap secret length exceeded
require(_preimage.length <= MAX_SWAP_SECRET_LENGTH, "37");
bytes32 swapHash = _hashSwap(_addresses, _values, _hashedSecret);
// Error code 24: executeSwap, swap is not active
require(atomicSwaps[swapHash], "24");
// Error code 25: executeSwap, hash of preimage does not match hashedSecret
require(sha256(abi.encodePacked(sha256(_preimage))) == _hashedSecret, "25");
uint256 takeAmount = _values[0];
if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId
takeAmount = takeAmount.sub(_values[2]);
}
delete atomicSwaps[swapHash];
_increaseBalance(
_addresses[1], // taker
_addresses[2], // assetId
takeAmount,
REASON_SWAP_RECEIVE,
_values[3] // nonce
);
_increaseBalance(
operator,
_addresses[3], // feeAssetId
_values[2], // feeAmount
REASON_SWAP_FEE_RECEIVE,
_values[3] // nonce
);
}
/// @notice Cancels a swap and refunds the previously locked tokens to
/// the swap maker.
///
/// @dev To reduce gas costs, the original parameters of the swap are not stored
/// in the contract's storage, only the hash of the parameters is stored for
/// verification, so the original parameters need to be re-specified here.
///
/// @param _addresses[0] maker: the address of the user to deduct the swap tokens from
/// @param _addresses[1] taker: the address of the swap taker who will receive the swap tokens
/// @param _addresses[2] assetId: the contract address of the token to swap
/// @param _addresses[3] feeAssetId: the contract address of the token to use as fees
/// @param _values[0] amount: the number of tokens previously locked
/// @param _values[1] expiryTime: the time in epoch seconds after which the swap will become cancellable
/// @param _values[2] feeAmount: the number of tokens to be paid to the operator as fees
/// @param _values[3] nonce: an unused nonce to prevent replay attacks
/// @param _hashedSecret The hash of the secret decided by the maker
/// @param _cancelFeeAmount The number of tokens to be paid to the operator as the cancellation fee
function cancelSwap(
address[4] calldata _addresses,
uint256[4] calldata _values,
bytes32 _hashedSecret,
uint256 _cancelFeeAmount
)
external
nonReentrant
{
// Error code 26: cancelSwap, expiry time has not been reached
require(_values[1] <= now, "26");
bytes32 swapHash = _hashSwap(_addresses, _values, _hashedSecret);
// Error code 27: cancelSwap, swap is not active
require(atomicSwaps[swapHash], "27");
uint256 cancelFeeAmount = _cancelFeeAmount;
if (!adminAddresses[msg.sender]) { cancelFeeAmount = _values[2]; }
// cancelFeeAmount <= feeAmount
// Error code 28: cancelSwap, cancelFeeAmount exceeds swap.feeAmount
require(cancelFeeAmount <= _values[2], "28");
uint256 refundAmount = _values[0];
if (_addresses[3] == _addresses[2]) { // feeAssetId == assetId
refundAmount = refundAmount.sub(cancelFeeAmount);
}
delete atomicSwaps[swapHash];
_increaseBalance(
_addresses[0], // maker
_addresses[2], // assetId
refundAmount,
REASON_SWAP_CANCEL_RECEIVE,
_values[3] // nonce
);
_increaseBalance(
operator,
_addresses[3], // feeAssetId
cancelFeeAmount,
REASON_SWAP_CANCEL_FEE_RECEIVE,
_values[3] // nonce
);
if (_addresses[3] != _addresses[2]) { // feeAssetId != assetId
uint256 refundFeeAmount = _values[2].sub(cancelFeeAmount);
_increaseBalance(
_addresses[0], // maker
_addresses[3], // feeAssetId
refundFeeAmount,
REASON_SWAP_CANCEL_FEE_REFUND,
_values[3] // nonce
);
}
}
/// @dev Cache whether offer nonces are taken in the offer's nonce space
/// @param _values The _values param from the trade / networkTrade method
function _cacheOfferNonceStates(uint256[] memory _values) private view {
uint256 i = 1;
// i + numOffers * 2
uint256 end = i + (_values[0] & mask8) * 2;
// loop offers
for(i; i < end; i += 2) {
// Error code 38: Invalid nonce space
require(((_values[i] & mask128) >> 120) == 0, "38");
uint256 nonce = (_values[i] & mask120) >> 56;
if (_nonceTaken(nonce)) {
_values[i] = _values[i] | (uint256(1) << 120);
}
}
}
/// @dev Reduce available offer amounts of offers and store the remaining
/// offer amount in the `offers` mapping.
/// Offer nonces will also be marked as taken.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
/// @param _hashes An array of offer hash keys
function _storeOfferData(
uint256[] memory _values,
bytes32[] memory _hashes
)
private
{
// takenAmounts with same size as numOffers
uint256[] memory takenAmounts = new uint256[](_values[0] & mask8);
uint256 i = 1;
// i += numOffers * 2
i += (_values[0] & mask8) * 2;
// i += numFills * 2
i += ((_values[0] & mask16) >> 8) * 2;
uint256 end = _values.length;
// loop matches
for (i; i < end; i++) {
uint256 offerIndex = _values[i] & mask8;
uint256 takeAmount = _values[i] >> 128;
takenAmounts[offerIndex] = takenAmounts[offerIndex].add(takeAmount);
}
i = 0;
end = _values[0] & mask8; // numOffers
// loop offers
for (i; i < end; i++) {
// we can use the cached nonce taken value here because offers have been
// validated to be unique
bool existingOffer = ((_values[i * 2 + 1] & mask128) >> 120) == 1;
bytes32 hashKey = _hashes[i * 2];
uint256 availableAmount = existingOffer ? offers[hashKey] : (_values[i * 2 + 2] & mask128);
// Error code 31: _storeOfferData, offer's available amount is zero
require(availableAmount > 0, "31");
uint256 remainingAmount = availableAmount.sub(takenAmounts[i]);
if (remainingAmount > 0) { offers[hashKey] = remainingAmount; }
if (existingOffer && remainingAmount == 0) { delete offers[hashKey]; }
if (!existingOffer) {
uint256 nonce = (_values[i * 2 + 1] & mask120) >> 56;
_markNonce(nonce);
}
}
}
/// @dev Mark all fill nonces as taken in the `usedNonces` mapping.
/// This also validates fill uniquness within the set of fills in `_values`,
/// since fill nonces are marked one at a time with validation that the
/// nonce to be marked has not been marked before.
/// See the `trade` method for param details.
/// @param _values Values from `trade`
function _storeFillNonces(uint256[] memory _values) private {
// 1 + numOffers * 2
uint256 i = 1 + (_values[0] & mask8) * 2;
// i + numFills * 2
uint256 end = i + ((_values[0] & mask16) >> 8) * 2;
// loop fills
for(i; i < end; i += 2) {
uint256 nonce = (_values[i] & mask120) >> 56;
_markNonce(nonce);
}
}
/// @dev The actual cancellation logic shared by `cancel`, `adminCancel`,
/// `slowCancel`.
/// The remaining offer amount is refunded back to the offer's maker, and
/// the specified cancellation fee will be deducted from the maker's balances.
function _cancel(
address _maker,
bytes32 _offerHash,
uint256 _expectedAvailableAmount,
address _offerAssetId,
uint256 _offerNonce,
address _cancelFeeAssetId,
uint256 _cancelFeeAmount
)
private
{
uint256 refundAmount = offers[_offerHash];
// Error code 32: _cancel, there is no offer amount left to cancel
require(refundAmount > 0, "32");
// Error code 33: _cancel, the remaining offer amount does not match
// the expectedAvailableAmount
require(refundAmount == _expectedAvailableAmount, "33");
delete offers[_offerHash];
if (_cancelFeeAssetId == _offerAssetId) {
refundAmount = refundAmount.sub(_cancelFeeAmount);
} else {
_decreaseBalance(
_maker,
_cancelFeeAssetId,
_cancelFeeAmount,
REASON_CANCEL_FEE_GIVE,
_offerNonce
);
}
_increaseBalance(
_maker,
_offerAssetId,
refundAmount,
REASON_CANCEL,
_offerNonce
);
_increaseBalance(
operator,
_cancelFeeAssetId,
_cancelFeeAmount,
REASON_CANCEL_FEE_RECEIVE,
_offerNonce // offer nonce
);
}
/// @dev The actual withdrawal logic shared by `withdraw`, `adminWithdraw`,
/// `slowWithdraw`. The specified amount is deducted from the `_withdrawer`'s
/// contract balance and transferred to the external `_receivingAddress`,
/// and the specified withdrawal fee will be deducted from the `_withdrawer`'s
/// balance.
function _withdraw(
address _withdrawer,
address payable _receivingAddress,
address _assetId,
uint256 _amount,
address _feeAssetId,
uint256 _feeAmount,
uint256 _nonce
)
private
{
// Error code 34: _withdraw, invalid withdrawal amount
require(_amount > 0, "34");
_validateAddress(_receivingAddress);
_decreaseBalance(
_withdrawer,
_assetId,
_amount,
REASON_WITHDRAW,
_nonce
);
_increaseBalance(
operator,
_feeAssetId,
_feeAmount,
REASON_WITHDRAW_FEE_RECEIVE,
_nonce
);
uint256 withdrawAmount;
if (_feeAssetId == _assetId) {
withdrawAmount = _amount.sub(_feeAmount);
} else {
_decreaseBalance(
_withdrawer,
_feeAssetId,
_feeAmount,
REASON_WITHDRAW_FEE_GIVE,
_nonce
);
withdrawAmount = _amount;
}
if (_assetId == ETHER_ADDR) {
_receivingAddress.transfer(withdrawAmount);
return;
}
Utils.transferTokensOut(
_receivingAddress,
_assetId,
withdrawAmount
);
}
/// @dev Creates a hash key for a swap using the swap's parameters
/// @param _addresses[0] Address of the user making the swap
/// @param _addresses[1] Address of the user taking the swap
/// @param _addresses[2] Contract address of the asset to swap
/// @param _addresses[3] Contract address of the fee asset
/// @param _values[0] The number of tokens to be transferred
/// @param _values[1] The time in epoch seconds after which the swap will become cancellable
/// @param _values[2] The number of tokens to pay as fees to the operator
/// @param _values[3] The swap nonce to prevent replay attacks
/// @param _hashedSecret The hash of the secret decided by the maker
/// @return The hash key of the swap
function _hashSwap(
address[4] memory _addresses,
uint256[4] memory _values,
bytes32 _hashedSecret
)
private
pure
returns (bytes32)
{
return keccak256(abi.encode(
SWAP_TYPEHASH,
_addresses[0], // maker
_addresses[1], // taker
_addresses[2], // assetId
_values[0], // amount
_hashedSecret, // hashedSecret
_values[1], // expiryTime
_addresses[3], // feeAssetId
_values[2], // feeAmount
_values[3] // nonce
));
}
/// @dev Checks if the `_nonce` had been previously taken.
/// To reduce gas costs, a single `usedNonces` value is used to
/// store the state of 256 nonces, using the formula:
/// nonceTaken = "usedNonces[_nonce / 256] bit (_nonce % 256)" != 0
/// For example:
/// nonce 0 taken: "usedNonces[0] bit 0" != 0 (0 / 256 = 0, 0 % 256 = 0)
/// nonce 1 taken: "usedNonces[0] bit 1" != 0 (1 / 256 = 0, 1 % 256 = 1)
/// nonce 2 taken: "usedNonces[0] bit 2" != 0 (2 / 256 = 0, 2 % 256 = 2)
/// nonce 255 taken: "usedNonces[0] bit 255" != 0 (255 / 256 = 0, 255 % 256 = 255)
/// nonce 256 taken: "usedNonces[1] bit 0" != 0 (256 / 256 = 1, 256 % 256 = 0)
/// nonce 257 taken: "usedNonces[1] bit 1" != 0 (257 / 256 = 1, 257 % 256 = 1)
/// @param _nonce The nonce to check
/// @return Whether the nonce has been taken
function _nonceTaken(uint256 _nonce) private view returns (bool) {
uint256 slotData = _nonce.div(256);
uint256 shiftedBit = uint256(1) << _nonce.mod(256);
uint256 bits = usedNonces[slotData];
// The check is for "!= 0" instead of "== 1" because the shiftedBit is
// not at the zero'th position, so it would require an additional
// shift to compare it with "== 1"
return bits & shiftedBit != 0;
}
/// @dev Sets the corresponding `_nonce` bit to 1.
/// An error will be raised if the corresponding `_nonce` bit was
/// previously set to 1.
/// See `_nonceTaken` for details on calculating the corresponding `_nonce` bit.
/// @param _nonce The nonce to mark
function _markNonce(uint256 _nonce) private {
// Error code 35: _markNonce, nonce cannot be zero
require(_nonce != 0, "35");
uint256 slotData = _nonce.div(256);
uint256 shiftedBit = 1 << _nonce.mod(256);
uint256 bits = usedNonces[slotData];
// Error code 36: _markNonce, nonce has already been marked
require(bits & shiftedBit == 0, "36");
usedNonces[slotData] = bits | shiftedBit;
}
/// @dev Validates that the specified `_hash` was signed by the specified `_user`.
/// This method supports the EIP712 specification, the older Ethereum
/// signed message specification is also supported for backwards compatibility.
/// @param _hash The original hash that was signed by the user
/// @param _user The user who signed the hash
/// @param _v The `v` component of the `_user`'s signature
/// @param _r The `r` component of the `_user`'s signature
/// @param _s The `s` component of the `_user`'s signature
/// @param _prefixed If true, the signature will be verified
/// against the Ethereum signed message specification instead of the
/// EIP712 specification
function _validateSignature(
bytes32 _hash,
address _user,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool _prefixed
)
private
pure
{
Utils.validateSignature(
_hash,
_user,
_v,
_r,
_s,
_prefixed
);
}
/// @dev A utility method to increase the balance of a user.
/// A corressponding `BalanceIncrease` event will also be emitted.
/// @param _user The address to increase balance for
/// @param _assetId The asset's contract address
/// @param _amount The number of tokens to increase the balance by
/// @param _reasonCode The reason code for the `BalanceIncrease` event
/// @param _nonce The nonce for the `BalanceIncrease` event
function _increaseBalance(
address _user,
address _assetId,
uint256 _amount,
uint256 _reasonCode,
uint256 _nonce
)
private
{
if (_amount == 0) { return; }
balances[_user][_assetId] = balances[_user][_assetId].add(_amount);
emit BalanceIncrease(
_user,
_assetId,
_amount,
_reasonCode,
_nonce
);
}
/// @dev A utility method to decrease the balance of a user.
/// A corressponding `BalanceDecrease` event will also be emitted.
/// @param _user The address to decrease balance for
/// @param _assetId The asset's contract address
/// @param _amount The number of tokens to decrease the balance by
/// @param _reasonCode The reason code for the `BalanceDecrease` event
/// @param _nonce The nonce for the `BalanceDecrease` event
function _decreaseBalance(
address _user,
address _assetId,
uint256 _amount,
uint256 _reasonCode,
uint256 _nonce
)
private
{
if (_amount == 0) { return; }
balances[_user][_assetId] = balances[_user][_assetId].sub(_amount);
emit BalanceDecrease(
_user,
_assetId,
_amount,
_reasonCode,
_nonce
);
}
/// @dev Ensures that `_address` is not the zero address
/// @param _address The address to check
function _validateAddress(address _address) private pure {
Utils.validateAddress(_address);
}
/// @dev A utility method to increase balances of multiple addresses.
/// A corressponding `Increment` event will also be emitted.
/// @param _increments An array of amounts to increase a user's balance by,
/// the corresponding user and assetId is referenced by
/// _addresses[index * 2] and _addresses[index * 2 + 1] respectively
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
/// @param _static Indicates if the amount was pre-calculated or only known
/// at the time the transaction was executed
function _incrementBalances(
uint256[] memory _increments,
address[] memory _addresses,
uint256 _static
)
private
{
uint256 end = _increments.length;
for(uint256 i = 0; i < end; i++) {
uint256 increment = _increments[i];
if (increment == 0) { continue; }
balances[_addresses[i * 2]][_addresses[i * 2 + 1]] =
balances[_addresses[i * 2]][_addresses[i * 2 + 1]].add(increment);
emit Increment((i << 248) | (_static << 240) | increment);
}
}
/// @dev A utility method to decrease balances of multiple addresses.
/// A corressponding `Decrement` event will also be emitted.
/// @param _decrements An array of amounts to decrease a user's balance by,
/// the corresponding user and assetId is referenced by
/// _addresses[index * 2] and _addresses[index * 2 + 1] respectively
/// @param _addresses An array of user asset pairs in the form of:
/// [
/// user_1_address,
/// asset_1_address,
/// user_1_address,
/// asset_2_address,
/// user_2_address,
/// asset_1_address,
/// ...
/// ]
function _decrementBalances(
uint256[] memory _decrements,
address[] memory _addresses
)
private
{
uint256 end = _decrements.length;
for(uint256 i = 0; i < end; i++) {
uint256 decrement = _decrements[i];
if (decrement == 0) { continue; }
balances[_addresses[i * 2]][_addresses[i * 2 + 1]] =
balances[_addresses[i * 2]][_addresses[i * 2 + 1]].sub(decrement);
emit Decrement(i << 248 | decrement);
}
}
}
|
@dev Validates that the specified `_hash` was signed by the specified `_user`. This method supports the EIP712 specification, the older Ethereum signed message specification is also supported for backwards compatibility. @param _hash The original hash that was signed by the user @param _user The user who signed the hash @param _v The `v` component of the `_user`'s signature @param _r The `r` component of the `_user`'s signature @param _s The `s` component of the `_user`'s signature @param _prefixed If true, the signature will be verified against the Ethereum signed message specification instead of the EIP712 specification
|
{
Utils.validateSignature(
_hash,
_user,
_v,
_r,
_s,
_prefixed
);
}
| 13,110,370 |
[
1,
9594,
716,
326,
1269,
1375,
67,
2816,
68,
1703,
6726,
635,
326,
1269,
1375,
67,
1355,
8338,
1220,
707,
6146,
326,
512,
2579,
27,
2138,
7490,
16,
326,
12156,
512,
18664,
379,
6726,
883,
7490,
353,
2546,
3260,
364,
12727,
8926,
18,
225,
389,
2816,
1021,
2282,
1651,
716,
1703,
6726,
635,
326,
729,
225,
389,
1355,
1021,
729,
10354,
6726,
326,
1651,
225,
389,
90,
1021,
1375,
90,
68,
1794,
434,
326,
1375,
67,
1355,
11294,
87,
3372,
225,
389,
86,
1021,
1375,
86,
68,
1794,
434,
326,
1375,
67,
1355,
11294,
87,
3372,
225,
389,
87,
1021,
1375,
87,
68,
1794,
434,
326,
1375,
67,
1355,
11294,
87,
3372,
225,
389,
3239,
329,
971,
638,
16,
326,
3372,
903,
506,
13808,
5314,
326,
512,
18664,
379,
6726,
883,
7490,
3560,
434,
326,
512,
2579,
27,
2138,
7490,
2,
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,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
565,
288,
203,
3639,
6091,
18,
5662,
5374,
12,
203,
5411,
389,
2816,
16,
203,
5411,
389,
1355,
16,
203,
5411,
389,
90,
16,
203,
5411,
389,
86,
16,
203,
5411,
389,
87,
16,
203,
5411,
389,
3239,
329,
203,
3639,
11272,
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
] |
./full_match/1/0x4361b1B8aE2E4f96bFB7A2BC95D6aB748882fdbB/sources/src/FiefdomArchetype.sol
|
@notice Symbol of collection @return Symbol
|
function symbol() public view virtual override(ERC721) returns (string memory) {
return _symbol;
}
| 4,962,795 |
[
1,
5335,
434,
1849,
327,
8565,
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,
225,
445,
3273,
1435,
1071,
1476,
5024,
3849,
12,
654,
39,
27,
5340,
13,
1135,
261,
1080,
3778,
13,
288,
203,
565,
327,
389,
7175,
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
] |
pragma solidity 0.4.19;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
uint256 public rate;
// Amount of wei raised
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);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
TokenPurchase(msg.sender, _beneficiary, weiAmount, tokens);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statemens to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
address public tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
function AllowanceCrowdsale(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokens() public view returns (uint256) {
return token.allowance(tokenWallet, this);
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
}
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract WhitelistedCrowdsale is Crowdsale, Ownable {
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 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;
}
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal isWhitelisted(_beneficiary) {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_openingTime >= now);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, 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(hasClosed());
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 ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title 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));
}
}
/**
* @title RTEBonusTokenVault
* @dev Token holder contract that releases tokens to the respective addresses
* and _lockedReleaseTime
*/
contract RTEBonusTokenVault is Ownable {
using SafeERC20 for ERC20Basic;
using SafeMath for uint256;
// ERC20 basic token contract being held
ERC20Basic public token;
bool public vaultUnlocked;
bool public vaultSecondaryUnlocked;
// How much we have allocated to the investors invested
mapping(address => uint256) public balances;
mapping(address => uint256) public lockedBalances;
/**
* @dev Allocation event
* @param _investor Investor address
* @param _value Tokens allocated
*/
event Allocated(address _investor, uint256 _value);
/**
* @dev Distribution event
* @param _investor Investor address
* @param _value Tokens distributed
*/
event Distributed(address _investor, uint256 _value);
function RTEBonusTokenVault(
ERC20Basic _token
)
public
{
token = _token;
vaultUnlocked = false;
vaultSecondaryUnlocked = false;
}
/**
* @dev Unlocks vault
*/
function unlock() public onlyOwner {
require(!vaultUnlocked);
vaultUnlocked = true;
}
/**
* @dev Unlocks secondary vault
*/
function unlockSecondary() public onlyOwner {
require(vaultUnlocked);
require(!vaultSecondaryUnlocked);
vaultSecondaryUnlocked = true;
}
/**
* @dev Add allocation amount to investor addresses
* Only the owner of this contract - the crowdsale can call this function
* Split half to be locked by timelock in vault, the other half to be released on vault unlock
* @param _investor Investor address
* @param _amount Amount of tokens to add
*/
function allocateInvestorBonusToken(address _investor, uint256 _amount) public onlyOwner {
require(!vaultUnlocked);
require(!vaultSecondaryUnlocked);
uint256 bonusTokenAmount = _amount.div(2);
uint256 bonusLockedTokenAmount = _amount.sub(bonusTokenAmount);
balances[_investor] = balances[_investor].add(bonusTokenAmount);
lockedBalances[_investor] = lockedBalances[_investor].add(bonusLockedTokenAmount);
Allocated(_investor, _amount);
}
/**
* @dev Transfers bonus tokens held to investor
* @param _investor Investor address making the claim
*/
function claim(address _investor) public onlyOwner {
// _investor is the original initiator
// msg.sender is the contract that called this.
require(vaultUnlocked);
uint256 claimAmount = balances[_investor];
require(claimAmount > 0);
uint256 tokenAmount = token.balanceOf(this);
require(tokenAmount > 0);
// Empty token balance
balances[_investor] = 0;
token.safeTransfer(_investor, claimAmount);
Distributed(_investor, claimAmount);
}
/**
* @dev Transfers secondary bonus tokens held to investor
* @param _investor Investor address making the claim
*/
function claimLocked(address _investor) public onlyOwner {
// _investor is the original initiator
// msg.sender is the contract that called this.
require(vaultUnlocked);
require(vaultSecondaryUnlocked);
uint256 claimAmount = lockedBalances[_investor];
require(claimAmount > 0);
uint256 tokenAmount = token.balanceOf(this);
require(tokenAmount > 0);
// Empty token balance
lockedBalances[_investor] = 0;
token.safeTransfer(_investor, claimAmount);
Distributed(_investor, claimAmount);
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Whitelisted Pausable token
* @dev StandardToken modified with pausable transfers. Enables a whitelist to enable transfers
* only for certain addresses such as crowdsale contract, issuing account etc.
**/
contract WhitelistedPausableToken is StandardToken, Pausable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if the message sender requesting for transfer is not whitelisted when token
* transfers are paused
* @param _sender check transaction sender address
*/
modifier whenNotPausedOrWhitelisted(address _sender) {
require(whitelist[_sender] || !paused);
_;
}
/**
* @dev Adds single address to whitelist.
* @param _whitelistAddress Address to be added to the whitelist
*/
function addToWhitelist(address _whitelistAddress) external onlyOwner {
whitelist[_whitelistAddress] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _whitelistAddresses Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _whitelistAddresses) external onlyOwner {
for (uint256 i = 0; i < _whitelistAddresses.length; i++) {
whitelist[_whitelistAddresses[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _whitelistAddress Address to be removed to the whitelist
*/
function removeFromWhitelist(address _whitelistAddress) external onlyOwner {
whitelist[_whitelistAddress] = false;
}
// Adding modifier to transfer/approval functions
function transfer(address _to, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPausedOrWhitelisted(msg.sender) returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPausedOrWhitelisted(msg.sender) returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPausedOrWhitelisted(msg.sender) returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title RTEToken
* @dev ERC20 token implementation
* Pausable
*/
contract RTEToken is WhitelistedPausableToken {
string public constant name = "Rate3";
string public constant symbol = "RTE";
uint8 public constant decimals = 18;
// 1 billion initial supply of RTE tokens
// Taking into account 18 decimals
uint256 public constant INITIAL_SUPPLY = (10 ** 9) * (10 ** 18);
/**
* @dev RTEToken Constructor
* Mints the initial supply of tokens, this is the hard cap, no more tokens will be minted.
* Allocate the tokens to the foundation wallet, issuing wallet etc.
*/
function RTEToken() public {
// Mint initial supply of tokens. All further minting of tokens is disabled
totalSupply_ = INITIAL_SUPPLY;
// Transfer all initial tokens to msg.sender
balances[msg.sender] = INITIAL_SUPPLY;
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
/**
* @title RTECrowdsale
* @dev test
*/
contract RTECrowdsale is AllowanceCrowdsale, WhitelistedCrowdsale, FinalizableCrowdsale {
using SafeERC20 for ERC20;
uint256 public constant minimumInvestmentInWei = 0.5 ether;
uint256 public allTokensSold;
uint256 public bonusTokensSold;
uint256 public cap;
mapping (address => uint256) public tokenInvestments;
mapping (address => uint256) public bonusTokenInvestments;
RTEBonusTokenVault public bonusTokenVault;
/**
* @dev Contract initialization parameters
* @param _openingTime Public crowdsale opening time
* @param _closingTime Public crowdsale closing time
* @param _rate Initial rate (Maybe remove, put as constant)
* @param _cap RTE token issue cap (Should be the same amount as approved allowance from issueWallet)
* @param _wallet Multisig wallet to send ether raised to
* @param _issueWallet Wallet that approves allowance of tokens to be issued
* @param _token RTE token address deployed seperately
*/
function RTECrowdsale(
uint256 _openingTime,
uint256 _closingTime,
uint256 _rate,
uint256 _cap,
address _wallet,
address _issueWallet,
RTEToken _token
)
AllowanceCrowdsale(_issueWallet)
TimedCrowdsale(_openingTime, _closingTime)
Crowdsale(_rate, _wallet, _token)
public
{
require(_cap > 0);
cap = _cap;
bonusTokenVault = new RTEBonusTokenVault(_token);
}
/**
* @dev Checks whether the cap for RTE has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return allTokensSold >= cap;
}
/**
* @dev Calculate bonus RTE percentage to be allocated based on time rules
* time is calculated by now = block.timestamp, will be consistent across transaction if called
* multiple times in same transaction
* @return Bonus percentage in percent value
*/
function _calculateBonusPercentage() internal view returns (uint256) {
return 20;
}
/**
* @dev Get current RTE balance of bonus token vault
*/
function getRTEBonusTokenVaultBalance() public view returns (uint256) {
return token.balanceOf(address(bonusTokenVault));
}
/**
* @dev Extend parent behavior requiring purchase to respect minimum investment per transaction.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(msg.value >= minimumInvestmentInWei);
}
/**
* @dev Keep track of tokens purchased extension functionality
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Value in amount of token purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
uint256 bonusPercentage = _calculateBonusPercentage();
uint256 additionalBonusTokens = _tokenAmount.mul(bonusPercentage).div(100);
uint256 tokensSold = _tokenAmount;
// Check if exceed token sale cap
uint256 newAllTokensSold = allTokensSold.add(tokensSold).add(additionalBonusTokens);
require(newAllTokensSold <= cap);
// Process purchase
super._processPurchase(_beneficiary, tokensSold);
allTokensSold = allTokensSold.add(tokensSold);
tokenInvestments[_beneficiary] = tokenInvestments[_beneficiary].add(tokensSold);
if (additionalBonusTokens > 0) {
// Record bonus tokens allocated and transfer it to RTEBonusTokenVault
allTokensSold = allTokensSold.add(additionalBonusTokens);
bonusTokensSold = bonusTokensSold.add(additionalBonusTokens);
bonusTokenVault.allocateInvestorBonusToken(_beneficiary, additionalBonusTokens);
bonusTokenInvestments[_beneficiary] = bonusTokenInvestments[_beneficiary].add(additionalBonusTokens);
}
}
/**
* @dev Unlock secondary tokens, can only be done by owner of contract
*/
function unlockSecondaryTokens() public onlyOwner {
require(isFinalized);
bonusTokenVault.unlockSecondary();
}
/**
* @dev Claim bonus tokens from vault after bonus tokens are released
* @param _beneficiary Address receiving the tokens
*/
function claimBonusTokens(address _beneficiary) public {
require(isFinalized);
bonusTokenVault.claim(_beneficiary);
}
/**
* @dev Claim timelocked bonus tokens from vault after bonus tokens are released
* @param _beneficiary Address receiving the tokens
*/
function claimLockedBonusTokens(address _beneficiary) public {
require(isFinalized);
bonusTokenVault.claimLocked(_beneficiary);
}
/**
* @dev Called manually when token sale has ended with finalize()
*/
function finalization() internal {
// Credit bonus tokens sold to bonusTokenVault
token.transferFrom(tokenWallet, bonusTokenVault, bonusTokensSold);
// Unlock bonusTokenVault for non-timelocked tokens to be claimed
bonusTokenVault.unlock();
super.finalization();
}
}
|
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing. @param _whitelistAddresses Addresses to be added to the whitelist/
|
function addManyToWhitelist(address[] _whitelistAddresses) external onlyOwner {
for (uint256 i = 0; i < _whitelistAddresses.length; i++) {
whitelist[_whitelistAddresses[i]] = true;
}
}
| 1,836,659 |
[
1,
3655,
666,
434,
6138,
358,
10734,
18,
2288,
1879,
4230,
6541,
358,
31810,
598,
433,
10148,
7769,
18,
225,
389,
20409,
7148,
23443,
358,
506,
3096,
358,
326,
10734,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
225,
445,
527,
5594,
774,
18927,
12,
2867,
8526,
389,
20409,
7148,
13,
3903,
1338,
5541,
288,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
20409,
7148,
18,
2469,
31,
277,
27245,
288,
203,
1377,
10734,
63,
67,
20409,
7148,
63,
77,
13563,
273,
638,
31,
203,
565,
289,
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
] |
pragma solidity >0.4.0 <0.7.0;
pragma experimental ABIEncoderV2;
//SPDX-License-Identifier: UNLICENSED
import { Documents, Document } from '../libraries/Documents.sol';
/**
* Padlock v0.1.0 Documents Library Testing
* Author: Blox Consulting LLC
* Last Updated: 07.17.2020
*
* Testing for Documents storage
*/
contract TestDocuments {
/// LIBRARIES ///
using Documents for Document;
/// EVENTS ///
event DocumentAdded(address _by, uint256 _index);
// Documents //
uint256 public documentIndex;
mapping(uint256 => Document) public documents;
/// MUTABLE FUNCTIONS ///
/**
* Ensure that new documents can be initalized containing the correct info
* @param _title bytes a sha3 hash of the file title
* @param _hash a sha3 hash of the file
* --base64 encoded
* @return _index uint the index of the document within the testing contract
*/
function testInit(bytes memory _title, bytes memory _hash) public returns (uint256 _index) {
documents[++documentIndex].initialize(_title, _hash);
_index = documentIndex;
Document memory document = documents[_index];
require(keccak256(document.title) == keccak256(_title), 'Title incorrectly set!');
require(keccak256(document.docHash) == keccak256(_hash), 'Body incorrectly set!');
require(document.op == msg.sender, 'Original Poster incorrectly set!');
require(document.init, 'Initialization status incorrectly set!');
require(document.timestamp != 0, 'Timestamp incorrectly set!');
emit DocumentAdded(msg.sender, _index);
return documentIndex;
}
}
|
MUTABLE FUNCTIONS * Ensure that new documents can be initalized containing the correct info @param _title bytes a sha3 hash of the file title @param _hash a sha3 hash of the file --base64 encoded @return _index uint the index of the document within the testing contract/
|
function testInit(bytes memory _title, bytes memory _hash) public returns (uint256 _index) {
documents[++documentIndex].initialize(_title, _hash);
_index = documentIndex;
Document memory document = documents[_index];
require(keccak256(document.title) == keccak256(_title), 'Title incorrectly set!');
require(keccak256(document.docHash) == keccak256(_hash), 'Body incorrectly set!');
require(document.op == msg.sender, 'Original Poster incorrectly set!');
require(document.init, 'Initialization status incorrectly set!');
require(document.timestamp != 0, 'Timestamp incorrectly set!');
emit DocumentAdded(msg.sender, _index);
return documentIndex;
}
| 974,607 |
[
1,
49,
1693,
2782,
13690,
55,
225,
7693,
716,
394,
7429,
848,
506,
1208,
287,
1235,
4191,
326,
3434,
1123,
225,
389,
2649,
1731,
279,
6056,
23,
1651,
434,
326,
585,
2077,
225,
389,
2816,
279,
6056,
23,
1651,
434,
326,
585,
1493,
1969,
1105,
3749,
327,
389,
1615,
2254,
326,
770,
434,
326,
1668,
3470,
326,
7769,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
225,
445,
1842,
2570,
12,
3890,
3778,
389,
2649,
16,
1731,
3778,
389,
2816,
13,
1071,
1135,
261,
11890,
5034,
389,
1615,
13,
288,
203,
565,
7429,
63,
9904,
5457,
1016,
8009,
11160,
24899,
2649,
16,
389,
2816,
1769,
203,
565,
389,
1615,
273,
1668,
1016,
31,
203,
565,
4319,
3778,
1668,
273,
7429,
63,
67,
1615,
15533,
203,
565,
2583,
12,
79,
24410,
581,
5034,
12,
5457,
18,
2649,
13,
422,
417,
24410,
581,
5034,
24899,
2649,
3631,
296,
4247,
25621,
444,
5124,
1769,
203,
565,
2583,
12,
79,
24410,
581,
5034,
12,
5457,
18,
2434,
2310,
13,
422,
417,
24410,
581,
5034,
24899,
2816,
3631,
296,
2250,
25621,
444,
5124,
1769,
203,
565,
2583,
12,
5457,
18,
556,
422,
1234,
18,
15330,
16,
296,
8176,
5616,
264,
25621,
444,
5124,
1769,
203,
565,
2583,
12,
5457,
18,
2738,
16,
296,
17701,
1267,
25621,
444,
5124,
1769,
203,
565,
2583,
12,
5457,
18,
5508,
480,
374,
16,
296,
4921,
25621,
444,
5124,
1769,
203,
565,
3626,
4319,
8602,
12,
3576,
18,
15330,
16,
389,
1615,
1769,
203,
565,
327,
1668,
1016,
31,
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
] |
./full_match/80001/0xFe244Bbd340cbA81F4106F2B0B936453D1B1E2B6/sources/project_/contracts/agreements/GeneralDistributionAgreementV1.sol
|
* @title General Distribution Agreement @author Superfluid @notice Storage Layout Notes Agreement State Universal Index Data slotId = _UNIVERSAL_INDEX_STATE_SLOT_ID or 0 msg.sender = address of GDAv1 account = context.msgSender Universal Index Data stores a Basic Particle for an account as well as the total buffer and whether the account is a pool or not. SlotsBitmap Data slotId = _POOL_SUBS_BITMAP_STATE_SLOT_ID or 1 msg.sender = address of GDAv1 account = context.msgSender Slots Bitmap Data Slot stores a bitmap of the slots that are "enabled" for a pool member. Pool Connections Data Slot Id Start slotId (start) = _POOL_CONNECTIONS_DATA_STATE_SLOT_ID_START or 1 << 128 or 340282366920938463463374607431768211456 msg.sender = address of GDAv1 account = context.msgSender Pool Connections Data Slot Id Start indicates the starting slot for where we begin to store the pools that a pool member is a part of. Agreement Data NOTE The Agreement Data slot is calculated with the following function: keccak256(abi.encode("AgreementData", agreementClass, agreementId)) agreementClass = address of GDAv1 agreementId = DistributionFlowId | PoolMemberId DistributionFlowId = keccak256(abi.encode(block.chainid, "distributionFlow", from, pool)) DistributionFlowId stores FlowDistributionData between a sender (from) and pool. PoolMemberId = keccak256(abi.encode(block.chainid, "poolMember", member, pool)) PoolMemberId stores PoolMemberData for a member at a pool./
|
contract GeneralDistributionAgreementV1 is AgreementBase, TokenMonad, IGeneralDistributionAgreementV1 {
using SafeCast for uint256;
using SafeCast for int256;
using SemanticMoney for BasicParticle;
address public constant SLOTS_BITMAP_LIBRARY_ADDRESS = address(SlotsBitmapLibrary);
address public constant SUPERFLUID_POOL_DEPLOYER_ADDRESS = address(SuperfluidPoolDeployerLibrary);
uint256 private constant _UNIVERSAL_INDEX_STATE_SLOT_ID = 0;
uint256 private constant _POOL_SUBS_BITMAP_STATE_SLOT_ID = 1;
uint256 private constant _POOL_CONNECTIONS_DATA_STATE_SLOT_ID_START = 1 << 128;
bytes32 private constant CFAV1_PPP_CONFIG_KEY =
keccak256("org.superfluid-finance.agreements.ConstantFlowAgreement.v1.PPPConfiguration");
bytes32 private constant SUPERTOKEN_MINIMUM_DEPOSIT_KEY =
keccak256("org.superfluid-finance.superfluid.superTokenMinimumDeposit");
import { TokenMonad } from "@superfluid-finance/solidity-semantic-money/src/TokenMonad.sol";
import { SuperfluidPool } from "../superfluid/SuperfluidPool.sol";
import { SuperfluidPoolDeployerLibrary } from "../libs/SuperfluidPoolDeployerLibrary.sol";
import { IGeneralDistributionAgreementV1 } from "../interfaces/agreements/IGeneralDistributionAgreementV1.sol";
import { ISuperfluidToken } from "../interfaces/superfluid/ISuperfluidToken.sol";
import { IConstantOutflowNFT } from "../interfaces/superfluid/IConstantOutflowNFT.sol";
import { ISuperToken } from "../interfaces/superfluid/ISuperToken.sol";
import { IPoolAdminNFT } from "../interfaces/superfluid/IPoolAdminNFT.sol";
import { ISuperfluidPool } from "../interfaces/superfluid/ISuperfluidPool.sol";
import { SlotsBitmapLibrary } from "../libs/SlotsBitmapLibrary.sol";
import { SafeGasLibrary } from "../libs/SafeGasLibrary.sol";
import { AgreementBase } from "./AgreementBase.sol";
import { AgreementLibrary } from "./AgreementLibrary.sol";
struct UniversalIndexData {
int96 flowRate;
uint32 settledAt;
uint256 totalBuffer;
bool isPool;
int256 settledValue;
}
struct FlowDistributionData {
uint32 lastUpdated;
int96 flowRate;
}
struct PoolMemberData {
address pool;
}
struct _StackVars_Liquidation {
ISuperfluidToken token;
int256 availableBalance;
address sender;
bytes32 distributionFlowHash;
int256 signedTotalGDADeposit;
address liquidator;
}
IBeacon public superfluidPoolBeacon;
constructor(ISuperfluid host) AgreementBase(address(host)) { }
function initialize(IBeacon superfluidPoolBeacon_) external initializer {
superfluidPoolBeacon = superfluidPoolBeacon_;
}
function realtimeBalanceVectorAt(ISuperfluidToken token, address account, uint256 time)
public
view
returns (int256 own, int256 fromPools, int256 buffer)
{
UniversalIndexData memory universalIndexData = _getUIndexData(abi.encode(token), account);
BasicParticle memory uIndexParticle = _getBasicParticleFromUIndex(universalIndexData);
if (_isPool(token, account)) {
own = ISuperfluidPool(account).getDisconnectedBalance(uint32(time));
own = Value.unwrap(uIndexParticle.rtb(Time.wrap(uint32(time))));
}
{
(uint32[] memory slotIds, bytes32[] memory pidList) = _listPoolConnectionIds(token, account);
for (uint256 i = 0; i < slotIds.length; ++i) {
address pool = address(uint160(uint256(pidList[i])));
(bool exist, PoolMemberData memory poolMemberData) =
_getPoolMemberData(token, account, ISuperfluidPool(pool));
assert(exist);
assert(poolMemberData.pool == pool);
fromPools = fromPools + ISuperfluidPool(pool).getClaimable(account, uint32(time));
}
}
buffer = universalIndexData.totalBuffer.toInt256();
}
function realtimeBalanceVectorAt(ISuperfluidToken token, address account, uint256 time)
public
view
returns (int256 own, int256 fromPools, int256 buffer)
{
UniversalIndexData memory universalIndexData = _getUIndexData(abi.encode(token), account);
BasicParticle memory uIndexParticle = _getBasicParticleFromUIndex(universalIndexData);
if (_isPool(token, account)) {
own = ISuperfluidPool(account).getDisconnectedBalance(uint32(time));
own = Value.unwrap(uIndexParticle.rtb(Time.wrap(uint32(time))));
}
{
(uint32[] memory slotIds, bytes32[] memory pidList) = _listPoolConnectionIds(token, account);
for (uint256 i = 0; i < slotIds.length; ++i) {
address pool = address(uint160(uint256(pidList[i])));
(bool exist, PoolMemberData memory poolMemberData) =
_getPoolMemberData(token, account, ISuperfluidPool(pool));
assert(exist);
assert(poolMemberData.pool == pool);
fromPools = fromPools + ISuperfluidPool(pool).getClaimable(account, uint32(time));
}
}
buffer = universalIndexData.totalBuffer.toInt256();
}
} else {
function realtimeBalanceVectorAt(ISuperfluidToken token, address account, uint256 time)
public
view
returns (int256 own, int256 fromPools, int256 buffer)
{
UniversalIndexData memory universalIndexData = _getUIndexData(abi.encode(token), account);
BasicParticle memory uIndexParticle = _getBasicParticleFromUIndex(universalIndexData);
if (_isPool(token, account)) {
own = ISuperfluidPool(account).getDisconnectedBalance(uint32(time));
own = Value.unwrap(uIndexParticle.rtb(Time.wrap(uint32(time))));
}
{
(uint32[] memory slotIds, bytes32[] memory pidList) = _listPoolConnectionIds(token, account);
for (uint256 i = 0; i < slotIds.length; ++i) {
address pool = address(uint160(uint256(pidList[i])));
(bool exist, PoolMemberData memory poolMemberData) =
_getPoolMemberData(token, account, ISuperfluidPool(pool));
assert(exist);
assert(poolMemberData.pool == pool);
fromPools = fromPools + ISuperfluidPool(pool).getClaimable(account, uint32(time));
}
}
buffer = universalIndexData.totalBuffer.toInt256();
}
function realtimeBalanceVectorAt(ISuperfluidToken token, address account, uint256 time)
public
view
returns (int256 own, int256 fromPools, int256 buffer)
{
UniversalIndexData memory universalIndexData = _getUIndexData(abi.encode(token), account);
BasicParticle memory uIndexParticle = _getBasicParticleFromUIndex(universalIndexData);
if (_isPool(token, account)) {
own = ISuperfluidPool(account).getDisconnectedBalance(uint32(time));
own = Value.unwrap(uIndexParticle.rtb(Time.wrap(uint32(time))));
}
{
(uint32[] memory slotIds, bytes32[] memory pidList) = _listPoolConnectionIds(token, account);
for (uint256 i = 0; i < slotIds.length; ++i) {
address pool = address(uint160(uint256(pidList[i])));
(bool exist, PoolMemberData memory poolMemberData) =
_getPoolMemberData(token, account, ISuperfluidPool(pool));
assert(exist);
assert(poolMemberData.pool == pool);
fromPools = fromPools + ISuperfluidPool(pool).getClaimable(account, uint32(time));
}
}
buffer = universalIndexData.totalBuffer.toInt256();
}
function realtimeBalanceOf(ISuperfluidToken token, address account, uint256 time)
public
view
override
returns (int256 rtb, uint256 buf, uint256 owedBuffer)
{
(int256 available, int256 fromPools, int256 buffer) = realtimeBalanceVectorAt(token, account, time);
rtb = available + fromPools - buffer;
owedBuffer = 0;
}
function realtimeBalanceOfNow(ISuperfluidToken token, address account)
external
view
returns (int256 availableBalance, uint256 buffer, uint256 owedBuffer, uint256 timestamp)
{
(availableBalance, buffer, owedBuffer) = realtimeBalanceOf(token, account, block.timestamp);
timestamp = block.timestamp;
}
function getNetFlowRate(ISuperfluidToken token, address account)
external
view
override
returns (int96 netFlowRate)
{
netFlowRate = int256(FlowRate.unwrap(_getUIndex(abi.encode(token), account).flow_rate())).toInt96();
if (_isPool(token, account)) {
netFlowRate += ISuperfluidPool(account).getTotalDisconnectedFlowRate();
}
{
(uint32[] memory slotIds, bytes32[] memory pidList) = _listPoolConnectionIds(token, account);
for (uint256 i = 0; i < slotIds.length; ++i) {
ISuperfluidPool pool = ISuperfluidPool(address(uint160(uint256(pidList[i]))));
netFlowRate += pool.getMemberFlowRate(account);
}
}
}
function getNetFlowRate(ISuperfluidToken token, address account)
external
view
override
returns (int96 netFlowRate)
{
netFlowRate = int256(FlowRate.unwrap(_getUIndex(abi.encode(token), account).flow_rate())).toInt96();
if (_isPool(token, account)) {
netFlowRate += ISuperfluidPool(account).getTotalDisconnectedFlowRate();
}
{
(uint32[] memory slotIds, bytes32[] memory pidList) = _listPoolConnectionIds(token, account);
for (uint256 i = 0; i < slotIds.length; ++i) {
ISuperfluidPool pool = ISuperfluidPool(address(uint160(uint256(pidList[i]))));
netFlowRate += pool.getMemberFlowRate(account);
}
}
}
function getNetFlowRate(ISuperfluidToken token, address account)
external
view
override
returns (int96 netFlowRate)
{
netFlowRate = int256(FlowRate.unwrap(_getUIndex(abi.encode(token), account).flow_rate())).toInt96();
if (_isPool(token, account)) {
netFlowRate += ISuperfluidPool(account).getTotalDisconnectedFlowRate();
}
{
(uint32[] memory slotIds, bytes32[] memory pidList) = _listPoolConnectionIds(token, account);
for (uint256 i = 0; i < slotIds.length; ++i) {
ISuperfluidPool pool = ISuperfluidPool(address(uint160(uint256(pidList[i]))));
netFlowRate += pool.getMemberFlowRate(account);
}
}
}
function getNetFlowRate(ISuperfluidToken token, address account)
external
view
override
returns (int96 netFlowRate)
{
netFlowRate = int256(FlowRate.unwrap(_getUIndex(abi.encode(token), account).flow_rate())).toInt96();
if (_isPool(token, account)) {
netFlowRate += ISuperfluidPool(account).getTotalDisconnectedFlowRate();
}
{
(uint32[] memory slotIds, bytes32[] memory pidList) = _listPoolConnectionIds(token, account);
for (uint256 i = 0; i < slotIds.length; ++i) {
ISuperfluidPool pool = ISuperfluidPool(address(uint160(uint256(pidList[i]))));
netFlowRate += pool.getMemberFlowRate(account);
}
}
}
function getFlowRate(ISuperfluidToken token, address from, address to) external view override returns (int96) {
bytes32 distributionFlowHash = _getFlowDistributionHash(from, to);
(, FlowDistributionData memory data) = _getFlowDistributionData(token, distributionFlowHash);
return data.flowRate;
}
function estimateFlowDistributionActualFlowRate(
ISuperfluidToken token,
address from,
ISuperfluidPool to,
int96 requestedFlowRate
) external view override returns (int96 actualFlowRate, int96 totalDistributionFlowRate) {
bytes memory eff = abi.encode(token);
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(to));
BasicParticle memory fromUIndexData = _getUIndex(eff, from);
PDPoolIndex memory pdpIndex = _getPDPIndex("", address(to));
FlowRate oldFlowRate = _getFlowRate(eff, distributionFlowHash);
FlowRate newActualFlowRate;
FlowRate oldDistributionFlowRate = pdpIndex.flow_rate();
FlowRate newDistributionFlowRate;
FlowRate flowRateDelta = FlowRate.wrap(requestedFlowRate) - oldFlowRate;
FlowRate currentAdjustmentFlowRate = _getPoolAdjustmentFlowRate(eff, address(to));
Time t = Time.wrap(uint32(block.timestamp));
(fromUIndexData, pdpIndex, newDistributionFlowRate) =
fromUIndexData.shift_flow2b(pdpIndex, flowRateDelta + currentAdjustmentFlowRate, t);
newActualFlowRate =
oldFlowRate + (newDistributionFlowRate - oldDistributionFlowRate) - currentAdjustmentFlowRate;
actualFlowRate = int256(FlowRate.unwrap(newActualFlowRate)).toInt96();
totalDistributionFlowRate = int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96();
}
function estimateDistributionActualAmount(
ISuperfluidToken token,
address from,
ISuperfluidPool to,
uint256 requestedAmount
) external view override returns (uint256 actualAmount) {
bytes memory eff = abi.encode(token);
BasicParticle memory fromUIndexData = _getUIndex(eff, from);
PDPoolIndex memory pdpIndex = _getPDPIndex("", address(to));
Value actualDistributionAmount;
(fromUIndexData, pdpIndex, actualDistributionAmount) =
fromUIndexData.shift2b(pdpIndex, Value.wrap(requestedAmount.toInt256()));
actualAmount = uint256(Value.unwrap(actualDistributionAmount));
}
function createPool(address admin, ISuperfluidToken token) external override returns (ISuperfluidPool pool) {
if (admin == address(0)) revert GDA_NO_ZERO_ADDRESS_ADMIN();
pool =
ISuperfluidPool(address(SuperfluidPoolDeployerLibrary.deploy(address(superfluidPoolBeacon), admin, token)));
bytes32[] memory data = new bytes32[](1);
data[0] = bytes32(uint256(1));
token.updateAgreementStateSlot(address(pool), _UNIVERSAL_INDEX_STATE_SLOT_ID, data);
ISuperToken(address(token)).POOL_ADMIN_NFT().mint(address(pool));
emit PoolCreated(token, admin, pool);
}
function connectPool(ISuperfluidPool pool, bytes calldata ctx) external override returns (bytes memory newCtx) {
return connectPool(pool, true, ctx);
}
function disconnectPool(ISuperfluidPool pool, bytes calldata ctx) external override returns (bytes memory newCtx) {
return connectPool(pool, false, ctx);
}
function connectPool(ISuperfluidPool pool, bool doConnect, bytes calldata ctx)
public
returns (bytes memory newCtx)
{
ISuperfluidToken token = pool.superToken();
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
address msgSender = currentContext.msgSender;
newCtx = ctx;
if (doConnect) {
if (!isMemberConnected(token, address(pool), msgSender)) {
assert(SuperfluidPool(address(pool)).operatorConnectMember(msgSender, true, uint32(block.timestamp)));
uint32 poolSlotID =
_findAndFillPoolConnectionsBitmap(token, msgSender, bytes32(uint256(uint160(address(pool)))));
token.createAgreement(
_getPoolMemberHash(msgSender, pool),
);
}
if (isMemberConnected(token, address(pool), msgSender)) {
assert(SuperfluidPool(address(pool)).operatorConnectMember(msgSender, false, uint32(block.timestamp)));
(, PoolMemberData memory poolMemberData) = _getPoolMemberData(token, msgSender, pool);
token.terminateAgreement(_getPoolMemberHash(msgSender, pool), 1);
_clearPoolConnectionsBitmap(token, msgSender, poolMemberData.poolID);
}
}
emit PoolConnectionUpdated(token, pool, msgSender, doConnect);
}
function connectPool(ISuperfluidPool pool, bool doConnect, bytes calldata ctx)
public
returns (bytes memory newCtx)
{
ISuperfluidToken token = pool.superToken();
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
address msgSender = currentContext.msgSender;
newCtx = ctx;
if (doConnect) {
if (!isMemberConnected(token, address(pool), msgSender)) {
assert(SuperfluidPool(address(pool)).operatorConnectMember(msgSender, true, uint32(block.timestamp)));
uint32 poolSlotID =
_findAndFillPoolConnectionsBitmap(token, msgSender, bytes32(uint256(uint160(address(pool)))));
token.createAgreement(
_getPoolMemberHash(msgSender, pool),
);
}
if (isMemberConnected(token, address(pool), msgSender)) {
assert(SuperfluidPool(address(pool)).operatorConnectMember(msgSender, false, uint32(block.timestamp)));
(, PoolMemberData memory poolMemberData) = _getPoolMemberData(token, msgSender, pool);
token.terminateAgreement(_getPoolMemberHash(msgSender, pool), 1);
_clearPoolConnectionsBitmap(token, msgSender, poolMemberData.poolID);
}
}
emit PoolConnectionUpdated(token, pool, msgSender, doConnect);
}
function connectPool(ISuperfluidPool pool, bool doConnect, bytes calldata ctx)
public
returns (bytes memory newCtx)
{
ISuperfluidToken token = pool.superToken();
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
address msgSender = currentContext.msgSender;
newCtx = ctx;
if (doConnect) {
if (!isMemberConnected(token, address(pool), msgSender)) {
assert(SuperfluidPool(address(pool)).operatorConnectMember(msgSender, true, uint32(block.timestamp)));
uint32 poolSlotID =
_findAndFillPoolConnectionsBitmap(token, msgSender, bytes32(uint256(uint160(address(pool)))));
token.createAgreement(
_getPoolMemberHash(msgSender, pool),
);
}
if (isMemberConnected(token, address(pool), msgSender)) {
assert(SuperfluidPool(address(pool)).operatorConnectMember(msgSender, false, uint32(block.timestamp)));
(, PoolMemberData memory poolMemberData) = _getPoolMemberData(token, msgSender, pool);
token.terminateAgreement(_getPoolMemberHash(msgSender, pool), 1);
_clearPoolConnectionsBitmap(token, msgSender, poolMemberData.poolID);
}
}
emit PoolConnectionUpdated(token, pool, msgSender, doConnect);
}
_encodePoolMemberData(PoolMemberData({ poolID: poolSlotID, pool: address(pool) }))
} else {
function connectPool(ISuperfluidPool pool, bool doConnect, bytes calldata ctx)
public
returns (bytes memory newCtx)
{
ISuperfluidToken token = pool.superToken();
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
address msgSender = currentContext.msgSender;
newCtx = ctx;
if (doConnect) {
if (!isMemberConnected(token, address(pool), msgSender)) {
assert(SuperfluidPool(address(pool)).operatorConnectMember(msgSender, true, uint32(block.timestamp)));
uint32 poolSlotID =
_findAndFillPoolConnectionsBitmap(token, msgSender, bytes32(uint256(uint160(address(pool)))));
token.createAgreement(
_getPoolMemberHash(msgSender, pool),
);
}
if (isMemberConnected(token, address(pool), msgSender)) {
assert(SuperfluidPool(address(pool)).operatorConnectMember(msgSender, false, uint32(block.timestamp)));
(, PoolMemberData memory poolMemberData) = _getPoolMemberData(token, msgSender, pool);
token.terminateAgreement(_getPoolMemberHash(msgSender, pool), 1);
_clearPoolConnectionsBitmap(token, msgSender, poolMemberData.poolID);
}
}
emit PoolConnectionUpdated(token, pool, msgSender, doConnect);
}
function isMemberConnected(ISuperfluidToken token, address pool, address member)
public
view
override
returns (bool)
{
(bool exist,) = _getPoolMemberData(token, member, ISuperfluidPool(pool));
return exist;
}
function isMemberConnected(ISuperfluidPool pool, address member) public view override returns (bool) {
ISuperfluidToken token = pool.superToken();
return isMemberConnected(token, address(pool), member);
}
function appendIndexUpdateByPool(ISuperfluidToken token, BasicParticle memory p, Time t) external returns (bool) {
_appendIndexUpdateByPool(abi.encode(token), msg.sender, p, t);
return true;
}
function _appendIndexUpdateByPool(bytes memory eff, address pool, BasicParticle memory p, Time t) internal {
address token = abi.decode(eff, (address));
if (_isPool(ISuperfluidToken(token), msg.sender) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
_setUIndex(eff, pool, _getUIndex(eff, pool).mappend(p));
_setPoolAdjustmentFlowRate(eff, pool, true, /* doShift? */ p.flow_rate(), t);
}
function _appendIndexUpdateByPool(bytes memory eff, address pool, BasicParticle memory p, Time t) internal {
address token = abi.decode(eff, (address));
if (_isPool(ISuperfluidToken(token), msg.sender) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
_setUIndex(eff, pool, _getUIndex(eff, pool).mappend(p));
_setPoolAdjustmentFlowRate(eff, pool, true, /* doShift? */ p.flow_rate(), t);
}
function _poolSettleClaim(bytes memory eff, address claimRecipient, Value amount) internal {
address token = abi.decode(eff, (address));
if (_isPool(ISuperfluidToken(token), msg.sender) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
_doShift(eff, msg.sender, claimRecipient, amount);
}
function _poolSettleClaim(bytes memory eff, address claimRecipient, Value amount) internal {
address token = abi.decode(eff, (address));
if (_isPool(ISuperfluidToken(token), msg.sender) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
_doShift(eff, msg.sender, claimRecipient, amount);
}
function poolSettleClaim(ISuperfluidToken superToken, address claimRecipient, int256 amount)
external
returns (bool)
{
bytes memory eff = abi.encode(superToken);
_poolSettleClaim(eff, claimRecipient, Value.wrap(amount));
return true;
}
function distribute(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
uint256 requestedAmount,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (from != currentContext.msgSender) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
}
(, Value actualAmount) = _doDistributeViaPool(
abi.encode(token), currentContext.msgSender, address(pool), Value.wrap(requestedAmount.toInt256())
);
if (token.isAccountCriticalNow(from)) {
revert GDA_INSUFFICIENT_BALANCE();
}
emit InstantDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
requestedAmount,
);
}
function distribute(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
uint256 requestedAmount,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (from != currentContext.msgSender) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
}
(, Value actualAmount) = _doDistributeViaPool(
abi.encode(token), currentContext.msgSender, address(pool), Value.wrap(requestedAmount.toInt256())
);
if (token.isAccountCriticalNow(from)) {
revert GDA_INSUFFICIENT_BALANCE();
}
emit InstantDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
requestedAmount,
);
}
function distribute(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
uint256 requestedAmount,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (from != currentContext.msgSender) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
}
(, Value actualAmount) = _doDistributeViaPool(
abi.encode(token), currentContext.msgSender, address(pool), Value.wrap(requestedAmount.toInt256())
);
if (token.isAccountCriticalNow(from)) {
revert GDA_INSUFFICIENT_BALANCE();
}
emit InstantDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
requestedAmount,
);
}
function distribute(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
uint256 requestedAmount,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (from != currentContext.msgSender) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
}
(, Value actualAmount) = _doDistributeViaPool(
abi.encode(token), currentContext.msgSender, address(pool), Value.wrap(requestedAmount.toInt256())
);
if (token.isAccountCriticalNow(from)) {
revert GDA_INSUFFICIENT_BALANCE();
}
emit InstantDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
requestedAmount,
);
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
} else {
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
} else {
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
} catch {
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
} catch {
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
} catch {
function distributeFlow(
ISuperfluidToken token,
address from,
ISuperfluidPool pool,
int96 requestedFlowRate,
bytes calldata ctx
) external override returns (bytes memory newCtx) {
if (_isPool(token, address(pool)) == false) {
revert GDA_ONLY_SUPER_TOKEN_POOL();
}
if (requestedFlowRate < 0) {
revert GDA_NO_NEGATIVE_FLOW_RATE();
}
ISuperfluid.Context memory currentContext = AgreementLibrary.authorizeTokenAccess(token, ctx);
newCtx = ctx;
bytes32 distributionFlowHash = _getFlowDistributionHash(from, address(pool));
FlowRate oldFlowRate = _getFlowRate(abi.encode(token), distributionFlowHash);
(, FlowRate actualFlowRate, FlowRate newDistributionFlowRate) = _doDistributeFlowViaPool(
abi.encode(token),
from,
address(pool),
distributionFlowHash,
FlowRate.wrap(requestedFlowRate),
Time.wrap(uint32(block.timestamp))
);
{
if (from != currentContext.msgSender) {
if (requestedFlowRate > 0) {
revert GDA_DISTRIBUTE_FOR_OTHERS_NOT_ALLOWED();
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
_StackVars_Liquidation memory liquidationData;
{
UniversalIndexData memory fromUIndexData = _getUIndexData(abi.encode(token), from);
liquidationData.token = token;
liquidationData.sender = from;
liquidationData.liquidator = currentContext.msgSender;
liquidationData.distributionFlowHash = distributionFlowHash;
liquidationData.signedTotalGDADeposit = fromUIndexData.totalBuffer.toInt256();
liquidationData.availableBalance = availableBalance;
}
if (availableBalance < 0) {
_makeLiquidationPayouts(liquidationData);
revert GDA_NON_CRITICAL_SENDER();
}
}
}
}
{
_adjustBuffer(abi.encode(token), from, distributionFlowHash, oldFlowRate, actualFlowRate);
}
if (from == currentContext.msgSender) {
(int256 availableBalance,,) = token.realtimeBalanceOf(from, currentContext.timestamp);
if (requestedFlowRate > 0 && availableBalance < 0) {
revert GDA_INSUFFICIENT_BALANCE();
}
}
{
address constantOutflowNFTAddress = _canCallNFTHook(token);
if (constantOutflowNFTAddress != address(0)) {
uint256 gasLeftBefore;
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onCreate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate > 0 && FlowRate.unwrap(oldFlowRate) > 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onUpdate(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
if (requestedFlowRate == 0) {
gasLeftBefore = gasleft();
try IConstantOutflowNFT(constantOutflowNFTAddress).onDelete(token, from, address(pool)) {
SafeGasLibrary._revertWhenOutOfGas(gasLeftBefore);
}
}
}
}
{
(address adjustmentFlowRecipient,, int96 adjustmentFlowRate) =
_getPoolAdjustmentFlowInfo(abi.encode(token), address(pool));
emit FlowDistributionUpdated(
token,
pool,
from,
currentContext.msgSender,
int256(FlowRate.unwrap(oldFlowRate)).toInt96(),
int256(FlowRate.unwrap(actualFlowRate)).toInt96(),
int256(FlowRate.unwrap(newDistributionFlowRate)).toInt96(),
adjustmentFlowRecipient,
adjustmentFlowRate
);
}
}
function _canCallNFTHook(ISuperfluidToken token) internal view returns (address constantOutflowNFTAddress) {
(bool success, bytes memory data) =
address(token).staticcall(abi.encodeWithSelector(ISuperToken.CONSTANT_OUTFLOW_NFT.selector));
if (success) {
constantOutflowNFTAddress = abi.decode(data, (address));
}
}
function _canCallNFTHook(ISuperfluidToken token) internal view returns (address constantOutflowNFTAddress) {
(bool success, bytes memory data) =
address(token).staticcall(abi.encodeWithSelector(ISuperToken.CONSTANT_OUTFLOW_NFT.selector));
if (success) {
constantOutflowNFTAddress = abi.decode(data, (address));
}
}
function _makeLiquidationPayouts(_StackVars_Liquidation memory data) internal {
(, FlowDistributionData memory flowDistributionData) =
_getFlowDistributionData(ISuperfluidToken(data.token), data.distributionFlowHash);
int256 signedSingleDeposit = flowDistributionData.buffer.toInt256();
bytes memory liquidationTypeData;
bool isCurrentlyPatricianPeriod;
{
(uint256 liquidationPeriod, uint256 patricianPeriod) = _decode3PsData(data.token);
isCurrentlyPatricianPeriod = _isPatricianPeriod(
data.availableBalance, data.signedTotalGDADeposit, liquidationPeriod, patricianPeriod
);
}
int256 totalRewardLeft = data.availableBalance + data.signedTotalGDADeposit;
if (totalRewardLeft >= 0) {
int256 rewardAmount = (signedSingleDeposit * totalRewardLeft) / data.signedTotalGDADeposit;
liquidationTypeData = abi.encode(1, isCurrentlyPatricianPeriod ? 0 : 1);
data.token.makeLiquidationPayoutsV2(
data.distributionFlowHash,
liquidationTypeData,
data.liquidator,
isCurrentlyPatricianPeriod,
data.sender,
rewardAmount.toUint256(),
rewardAmount * -1
);
int256 rewardAmount = signedSingleDeposit;
data.token.makeLiquidationPayoutsV2(
data.distributionFlowHash,
abi.encode(1, 2),
data.liquidator,
false,
data.sender,
rewardAmount.toUint256(),
totalRewardLeft * -1
);
}
}
function _makeLiquidationPayouts(_StackVars_Liquidation memory data) internal {
(, FlowDistributionData memory flowDistributionData) =
_getFlowDistributionData(ISuperfluidToken(data.token), data.distributionFlowHash);
int256 signedSingleDeposit = flowDistributionData.buffer.toInt256();
bytes memory liquidationTypeData;
bool isCurrentlyPatricianPeriod;
{
(uint256 liquidationPeriod, uint256 patricianPeriod) = _decode3PsData(data.token);
isCurrentlyPatricianPeriod = _isPatricianPeriod(
data.availableBalance, data.signedTotalGDADeposit, liquidationPeriod, patricianPeriod
);
}
int256 totalRewardLeft = data.availableBalance + data.signedTotalGDADeposit;
if (totalRewardLeft >= 0) {
int256 rewardAmount = (signedSingleDeposit * totalRewardLeft) / data.signedTotalGDADeposit;
liquidationTypeData = abi.encode(1, isCurrentlyPatricianPeriod ? 0 : 1);
data.token.makeLiquidationPayoutsV2(
data.distributionFlowHash,
liquidationTypeData,
data.liquidator,
isCurrentlyPatricianPeriod,
data.sender,
rewardAmount.toUint256(),
rewardAmount * -1
);
int256 rewardAmount = signedSingleDeposit;
data.token.makeLiquidationPayoutsV2(
data.distributionFlowHash,
abi.encode(1, 2),
data.liquidator,
false,
data.sender,
rewardAmount.toUint256(),
totalRewardLeft * -1
);
}
}
function _makeLiquidationPayouts(_StackVars_Liquidation memory data) internal {
(, FlowDistributionData memory flowDistributionData) =
_getFlowDistributionData(ISuperfluidToken(data.token), data.distributionFlowHash);
int256 signedSingleDeposit = flowDistributionData.buffer.toInt256();
bytes memory liquidationTypeData;
bool isCurrentlyPatricianPeriod;
{
(uint256 liquidationPeriod, uint256 patricianPeriod) = _decode3PsData(data.token);
isCurrentlyPatricianPeriod = _isPatricianPeriod(
data.availableBalance, data.signedTotalGDADeposit, liquidationPeriod, patricianPeriod
);
}
int256 totalRewardLeft = data.availableBalance + data.signedTotalGDADeposit;
if (totalRewardLeft >= 0) {
int256 rewardAmount = (signedSingleDeposit * totalRewardLeft) / data.signedTotalGDADeposit;
liquidationTypeData = abi.encode(1, isCurrentlyPatricianPeriod ? 0 : 1);
data.token.makeLiquidationPayoutsV2(
data.distributionFlowHash,
liquidationTypeData,
data.liquidator,
isCurrentlyPatricianPeriod,
data.sender,
rewardAmount.toUint256(),
rewardAmount * -1
);
int256 rewardAmount = signedSingleDeposit;
data.token.makeLiquidationPayoutsV2(
data.distributionFlowHash,
abi.encode(1, 2),
data.liquidator,
false,
data.sender,
rewardAmount.toUint256(),
totalRewardLeft * -1
);
}
}
} else {
function _adjustBuffer(
bytes memory eff,
address from,
bytes32 flowHash,
FlowRate newFlowRate
) internal returns (bytes memory) {
address token = abi.decode(eff, (address));
ISuperfluidGovernance gov = ISuperfluidGovernance(ISuperfluid(_host).getGovernance());
uint256 minimumDeposit =
gov.getConfigAsUint256(ISuperfluid(msg.sender), ISuperfluidToken(token), SUPERTOKEN_MINIMUM_DEPOSIT_KEY);
(uint256 liquidationPeriod,) = _decode3PsData(ISuperfluidToken(token));
(, FlowDistributionData memory flowDistributionData) =
_getFlowDistributionData(ISuperfluidToken(token), flowHash);
Value newBufferAmount = newFlowRate.mul(Time.wrap(uint32(liquidationPeriod)));
if (Value.unwrap(newBufferAmount).toUint256() < minimumDeposit && FlowRate.unwrap(newFlowRate) > 0) {
newBufferAmount = Value.wrap(minimumDeposit.toInt256());
}
Value bufferDelta = newBufferAmount - Value.wrap(uint256(flowDistributionData.buffer).toInt256());
eff = _doShift(eff, from, address(this), bufferDelta);
{
bytes32[] memory data = _encodeFlowDistributionData(
FlowDistributionData({
lastUpdated: uint32(block.timestamp),
flowRate: int256(FlowRate.unwrap(newFlowRate)).toInt96(),
})
);
ISuperfluidToken(token).updateAgreementData(flowHash, data);
}
UniversalIndexData memory universalIndexData = _getUIndexData(eff, from);
int256 newBuffer = universalIndexData.totalBuffer.toInt256() + Value.unwrap(bufferDelta);
universalIndexData.totalBuffer = newBuffer.toUint256();
ISuperfluidToken(token).updateAgreementStateSlot(
from, _UNIVERSAL_INDEX_STATE_SLOT_ID, _encodeUniversalIndexData(universalIndexData)
);
universalIndexData = _getUIndexData(eff, from);
return eff;
}
function _adjustBuffer(
bytes memory eff,
address from,
bytes32 flowHash,
FlowRate newFlowRate
) internal returns (bytes memory) {
address token = abi.decode(eff, (address));
ISuperfluidGovernance gov = ISuperfluidGovernance(ISuperfluid(_host).getGovernance());
uint256 minimumDeposit =
gov.getConfigAsUint256(ISuperfluid(msg.sender), ISuperfluidToken(token), SUPERTOKEN_MINIMUM_DEPOSIT_KEY);
(uint256 liquidationPeriod,) = _decode3PsData(ISuperfluidToken(token));
(, FlowDistributionData memory flowDistributionData) =
_getFlowDistributionData(ISuperfluidToken(token), flowHash);
Value newBufferAmount = newFlowRate.mul(Time.wrap(uint32(liquidationPeriod)));
if (Value.unwrap(newBufferAmount).toUint256() < minimumDeposit && FlowRate.unwrap(newFlowRate) > 0) {
newBufferAmount = Value.wrap(minimumDeposit.toInt256());
}
Value bufferDelta = newBufferAmount - Value.wrap(uint256(flowDistributionData.buffer).toInt256());
eff = _doShift(eff, from, address(this), bufferDelta);
{
bytes32[] memory data = _encodeFlowDistributionData(
FlowDistributionData({
lastUpdated: uint32(block.timestamp),
flowRate: int256(FlowRate.unwrap(newFlowRate)).toInt96(),
})
);
ISuperfluidToken(token).updateAgreementData(flowHash, data);
}
UniversalIndexData memory universalIndexData = _getUIndexData(eff, from);
int256 newBuffer = universalIndexData.totalBuffer.toInt256() + Value.unwrap(bufferDelta);
universalIndexData.totalBuffer = newBuffer.toUint256();
ISuperfluidToken(token).updateAgreementStateSlot(
from, _UNIVERSAL_INDEX_STATE_SLOT_ID, _encodeUniversalIndexData(universalIndexData)
);
universalIndexData = _getUIndexData(eff, from);
return eff;
}
function _adjustBuffer(
bytes memory eff,
address from,
bytes32 flowHash,
FlowRate newFlowRate
) internal returns (bytes memory) {
address token = abi.decode(eff, (address));
ISuperfluidGovernance gov = ISuperfluidGovernance(ISuperfluid(_host).getGovernance());
uint256 minimumDeposit =
gov.getConfigAsUint256(ISuperfluid(msg.sender), ISuperfluidToken(token), SUPERTOKEN_MINIMUM_DEPOSIT_KEY);
(uint256 liquidationPeriod,) = _decode3PsData(ISuperfluidToken(token));
(, FlowDistributionData memory flowDistributionData) =
_getFlowDistributionData(ISuperfluidToken(token), flowHash);
Value newBufferAmount = newFlowRate.mul(Time.wrap(uint32(liquidationPeriod)));
if (Value.unwrap(newBufferAmount).toUint256() < minimumDeposit && FlowRate.unwrap(newFlowRate) > 0) {
newBufferAmount = Value.wrap(minimumDeposit.toInt256());
}
Value bufferDelta = newBufferAmount - Value.wrap(uint256(flowDistributionData.buffer).toInt256());
eff = _doShift(eff, from, address(this), bufferDelta);
{
bytes32[] memory data = _encodeFlowDistributionData(
FlowDistributionData({
lastUpdated: uint32(block.timestamp),
flowRate: int256(FlowRate.unwrap(newFlowRate)).toInt96(),
})
);
ISuperfluidToken(token).updateAgreementData(flowHash, data);
}
UniversalIndexData memory universalIndexData = _getUIndexData(eff, from);
int256 newBuffer = universalIndexData.totalBuffer.toInt256() + Value.unwrap(bufferDelta);
universalIndexData.totalBuffer = newBuffer.toUint256();
ISuperfluidToken(token).updateAgreementStateSlot(
from, _UNIVERSAL_INDEX_STATE_SLOT_ID, _encodeUniversalIndexData(universalIndexData)
);
universalIndexData = _getUIndexData(eff, from);
return eff;
}
function _adjustBuffer(
bytes memory eff,
address from,
bytes32 flowHash,
FlowRate newFlowRate
) internal returns (bytes memory) {
address token = abi.decode(eff, (address));
ISuperfluidGovernance gov = ISuperfluidGovernance(ISuperfluid(_host).getGovernance());
uint256 minimumDeposit =
gov.getConfigAsUint256(ISuperfluid(msg.sender), ISuperfluidToken(token), SUPERTOKEN_MINIMUM_DEPOSIT_KEY);
(uint256 liquidationPeriod,) = _decode3PsData(ISuperfluidToken(token));
(, FlowDistributionData memory flowDistributionData) =
_getFlowDistributionData(ISuperfluidToken(token), flowHash);
Value newBufferAmount = newFlowRate.mul(Time.wrap(uint32(liquidationPeriod)));
if (Value.unwrap(newBufferAmount).toUint256() < minimumDeposit && FlowRate.unwrap(newFlowRate) > 0) {
newBufferAmount = Value.wrap(minimumDeposit.toInt256());
}
Value bufferDelta = newBufferAmount - Value.wrap(uint256(flowDistributionData.buffer).toInt256());
eff = _doShift(eff, from, address(this), bufferDelta);
{
bytes32[] memory data = _encodeFlowDistributionData(
FlowDistributionData({
lastUpdated: uint32(block.timestamp),
flowRate: int256(FlowRate.unwrap(newFlowRate)).toInt96(),
})
);
ISuperfluidToken(token).updateAgreementData(flowHash, data);
}
UniversalIndexData memory universalIndexData = _getUIndexData(eff, from);
int256 newBuffer = universalIndexData.totalBuffer.toInt256() + Value.unwrap(bufferDelta);
universalIndexData.totalBuffer = newBuffer.toUint256();
ISuperfluidToken(token).updateAgreementStateSlot(
from, _UNIVERSAL_INDEX_STATE_SLOT_ID, _encodeUniversalIndexData(universalIndexData)
);
universalIndexData = _getUIndexData(eff, from);
return eff;
}
function _decode3PsData(ISuperfluidToken token)
internal
view
returns (uint256 liquidationPeriod, uint256 patricianPeriod)
{
ISuperfluidGovernance gov = ISuperfluidGovernance(ISuperfluid(_host).getGovernance());
uint256 pppConfig = gov.getConfigAsUint256(ISuperfluid(_host), token, CFAV1_PPP_CONFIG_KEY);
(liquidationPeriod, patricianPeriod) = SuperfluidGovernanceConfigs.decodePPPConfig(pppConfig);
}
function isPatricianPeriodNow(ISuperfluidToken token, address account)
external
view
override
returns (bool isCurrentlyPatricianPeriod, uint256 timestamp)
{
timestamp = ISuperfluid(_host).getNow();
isCurrentlyPatricianPeriod = isPatricianPeriod(token, account, timestamp);
}
function isPatricianPeriod(ISuperfluidToken token, address account, uint256 timestamp)
public
view
override
returns (bool)
{
(int256 availableBalance,,) = token.realtimeBalanceOf(account, timestamp);
if (availableBalance >= 0) {
return true;
}
(uint256 liquidationPeriod, uint256 patricianPeriod) = _decode3PsData(token);
UniversalIndexData memory uIndexData = _getUIndexData(abi.encode(token), account);
return
_isPatricianPeriod(availableBalance, uIndexData.totalBuffer.toInt256(), liquidationPeriod, patricianPeriod);
}
function isPatricianPeriod(ISuperfluidToken token, address account, uint256 timestamp)
public
view
override
returns (bool)
{
(int256 availableBalance,,) = token.realtimeBalanceOf(account, timestamp);
if (availableBalance >= 0) {
return true;
}
(uint256 liquidationPeriod, uint256 patricianPeriod) = _decode3PsData(token);
UniversalIndexData memory uIndexData = _getUIndexData(abi.encode(token), account);
return
_isPatricianPeriod(availableBalance, uIndexData.totalBuffer.toInt256(), liquidationPeriod, patricianPeriod);
}
function _isPatricianPeriod(
int256 availableBalance,
int256 signedTotalGDADeposit,
uint256 liquidationPeriod,
uint256 patricianPeriod
) internal pure returns (bool) {
if (signedTotalGDADeposit == 0) {
return false;
}
int256 totalRewardLeft = availableBalance + signedTotalGDADeposit;
int256 totalGDAOutFlowrate = signedTotalGDADeposit / liquidationPeriod.toInt256();
}
function _isPatricianPeriod(
int256 availableBalance,
int256 signedTotalGDADeposit,
uint256 liquidationPeriod,
uint256 patricianPeriod
) internal pure returns (bool) {
if (signedTotalGDADeposit == 0) {
return false;
}
int256 totalRewardLeft = availableBalance + signedTotalGDADeposit;
int256 totalGDAOutFlowrate = signedTotalGDADeposit / liquidationPeriod.toInt256();
}
return totalRewardLeft / totalGDAOutFlowrate > (liquidationPeriod - patricianPeriod).toInt256();
function _getPoolMemberHash(address poolMember, ISuperfluidPool pool) internal view returns (bytes32) {
return keccak256(abi.encode(block.chainid, "poolMember", poolMember, address(pool)));
}
function _getFlowDistributionHash(address from, address to) internal view returns (bytes32) {
return keccak256(abi.encode(block.chainid, "distributionFlow", from, to));
}
function _getPoolAdjustmentFlowHash(address from, address to) internal view returns (bytes32) {
return keccak256(abi.encode(block.chainid, "poolAdjustmentFlow", from, to));
}
function _encodeUniversalIndexData(BasicParticle memory p, uint256 buffer, bool isPool_)
internal
pure
returns (bytes32[] memory data)
{
data = new bytes32[](2);
data[0] = bytes32(
(uint256(int256(FlowRate.unwrap(p.flow_rate()))) << 160) | (uint256(Time.unwrap(p.settled_at())) << 128)
| (buffer << 32) | (isPool_ ? 1 : 0)
);
data[1] = bytes32(uint256(Value.unwrap(p._settled_value)));
}
function _encodeUniversalIndexData(UniversalIndexData memory uIndexData)
internal
pure
returns (bytes32[] memory data)
{
data = new bytes32[](2);
data[0] = bytes32(
(uint256(int256(uIndexData.flowRate)) << 160) | (uint256(uIndexData.settledAt) << 128)
| (uint256(uIndexData.totalBuffer) << 32) | (uIndexData.isPool ? 1 : 0)
);
data[1] = bytes32(uint256(uIndexData.settledValue));
}
function _decodeUniversalIndexData(bytes32[] memory data)
internal
pure
returns (bool exists, UniversalIndexData memory universalIndexData)
{
uint256 a = uint256(data[0]);
uint256 b = uint256(data[1]);
exists = a > 0 || b > 0;
if (exists) {
universalIndexData.flowRate = int96(int256(a >> 160) & int256(uint256(type(uint96).max)));
universalIndexData.settledAt = uint32(uint256(a >> 128) & uint256(type(uint32).max));
universalIndexData.totalBuffer = uint256(a >> 32) & uint256(type(uint96).max);
universalIndexData.isPool = ((a << 224) >> 224) & 1 == 1;
universalIndexData.settledValue = int256(b);
}
}
function _decodeUniversalIndexData(bytes32[] memory data)
internal
pure
returns (bool exists, UniversalIndexData memory universalIndexData)
{
uint256 a = uint256(data[0]);
uint256 b = uint256(data[1]);
exists = a > 0 || b > 0;
if (exists) {
universalIndexData.flowRate = int96(int256(a >> 160) & int256(uint256(type(uint96).max)));
universalIndexData.settledAt = uint32(uint256(a >> 128) & uint256(type(uint32).max));
universalIndexData.totalBuffer = uint256(a >> 32) & uint256(type(uint96).max);
universalIndexData.isPool = ((a << 224) >> 224) & 1 == 1;
universalIndexData.settledValue = int256(b);
}
}
function _getUIndexData(bytes memory eff, address owner)
internal
view
returns (UniversalIndexData memory universalIndexData)
{
address token = abi.decode(eff, (address));
bytes32[] memory data =
ISuperfluidToken(token).getAgreementStateSlot(address(this), owner, _UNIVERSAL_INDEX_STATE_SLOT_ID, 2);
(, universalIndexData) = _decodeUniversalIndexData(data);
}
function _getBasicParticleFromUIndex(UniversalIndexData memory universalIndexData)
internal
pure
returns (BasicParticle memory particle)
{
particle._flow_rate = FlowRate.wrap(universalIndexData.flowRate);
particle._settled_at = Time.wrap(universalIndexData.settledAt);
particle._settled_value = Value.wrap(universalIndexData.settledValue);
}
function _getUIndex(bytes memory eff, address owner) internal view override returns (BasicParticle memory uIndex) {
address token = abi.decode(eff, (address));
bytes32[] memory data =
ISuperfluidToken(token).getAgreementStateSlot(address(this), owner, _UNIVERSAL_INDEX_STATE_SLOT_ID, 2);
(, UniversalIndexData memory universalIndexData) = _decodeUniversalIndexData(data);
uIndex = _getBasicParticleFromUIndex(universalIndexData);
}
function _setUIndex(bytes memory eff, address owner, BasicParticle memory p)
internal
override
returns (bytes memory)
{
address token = abi.decode(eff, (address));
UniversalIndexData memory universalIndexData = _getUIndexData(eff, owner);
ISuperfluidToken(token).updateAgreementStateSlot(
owner,
_UNIVERSAL_INDEX_STATE_SLOT_ID,
_encodeUniversalIndexData(p, universalIndexData.totalBuffer, universalIndexData.isPool)
);
return eff;
}
function _getPDPIndex(
address pool
) internal view override returns (PDPoolIndex memory) {
SuperfluidPool.PoolIndexData memory data = SuperfluidPool(pool).getIndex();
return SuperfluidPool(pool).poolIndexDataToPDPoolIndex(data);
}
function _setPDPIndex(bytes memory eff, address pool, PDPoolIndex memory p)
internal
override
returns (bytes memory)
{
assert(SuperfluidPool(pool).operatorSetIndex(p));
return eff;
}
function _getFlowRate(bytes memory eff, bytes32 distributionFlowHash) internal view override returns (FlowRate) {
address token = abi.decode(eff, (address));
(, FlowDistributionData memory data) = _getFlowDistributionData(ISuperfluidToken(token), distributionFlowHash);
return FlowRate.wrap(data.flowRate);
}
function _setFlowInfo(
bytes memory eff,
bytes32 flowHash,
FlowRate newFlowRate,
) internal override returns (bytes memory) {
address token = abi.decode(eff, (address));
(, FlowDistributionData memory flowDistributionData) =
_getFlowDistributionData(ISuperfluidToken(token), flowHash);
bytes32[] memory data = _encodeFlowDistributionData(
FlowDistributionData({
lastUpdated: uint32(block.timestamp),
flowRate: int256(FlowRate.unwrap(newFlowRate)).toInt96(),
buffer: flowDistributionData.buffer
})
);
ISuperfluidToken(token).updateAgreementData(flowHash, data);
return eff;
}
function _setFlowInfo(
bytes memory eff,
bytes32 flowHash,
FlowRate newFlowRate,
) internal override returns (bytes memory) {
address token = abi.decode(eff, (address));
(, FlowDistributionData memory flowDistributionData) =
_getFlowDistributionData(ISuperfluidToken(token), flowHash);
bytes32[] memory data = _encodeFlowDistributionData(
FlowDistributionData({
lastUpdated: uint32(block.timestamp),
flowRate: int256(FlowRate.unwrap(newFlowRate)).toInt96(),
buffer: flowDistributionData.buffer
})
);
ISuperfluidToken(token).updateAgreementData(flowHash, data);
return eff;
}
function getPoolAdjustmentFlowInfo(ISuperfluidPool pool)
external
view
override
returns (address recipient, bytes32 flowHash, int96 flowRate)
{
bytes memory eff = abi.encode(pool.superToken());
return _getPoolAdjustmentFlowInfo(eff, address(pool));
}
function _getPoolAdjustmentFlowInfo(bytes memory eff, address pool)
internal
view
returns (address adjustmentRecipient, bytes32 flowHash, int96 flowRate)
{
adjustmentRecipient = ISuperfluidPool(pool).admin();
flowHash = _getPoolAdjustmentFlowHash(pool, adjustmentRecipient);
return (adjustmentRecipient, flowHash, int256(FlowRate.unwrap(_getFlowRate(eff, flowHash))).toInt96());
}
function _getPoolAdjustmentFlowRate(bytes memory eff, address pool)
internal
view
override
returns (FlowRate flowRate)
{
(,, int96 rawFlowRate) = _getPoolAdjustmentFlowInfo(eff, pool);
}
function getPoolAdjustmentFlowRate(address token, address pool) external view override returns (int96) {
bytes memory eff = abi.encode(token);
return int256(FlowRate.unwrap(_getPoolAdjustmentFlowRate(eff, pool))).toInt96();
}
function _setPoolAdjustmentFlowRate(bytes memory eff, address pool, FlowRate flowRate, Time t)
internal
override
returns (bytes memory)
{
return _setPoolAdjustmentFlowRate(eff, pool, false, /* doShift? */ flowRate, t);
}
function _setPoolAdjustmentFlowRate(bytes memory eff, address pool, bool doShiftFlow, FlowRate flowRate, Time t)
internal
returns (bytes memory)
{
address adjustmentRecipient = ISuperfluidPool(pool).admin();
bytes32 adjustmentFlowHash = _getPoolAdjustmentFlowHash(pool, adjustmentRecipient);
if (doShiftFlow) {
flowRate = flowRate + _getFlowRate(eff, adjustmentFlowHash);
}
eff = _doFlow(eff, pool, adjustmentRecipient, adjustmentFlowHash, flowRate, t);
return eff;
}
function _setPoolAdjustmentFlowRate(bytes memory eff, address pool, bool doShiftFlow, FlowRate flowRate, Time t)
internal
returns (bytes memory)
{
address adjustmentRecipient = ISuperfluidPool(pool).admin();
bytes32 adjustmentFlowHash = _getPoolAdjustmentFlowHash(pool, adjustmentRecipient);
if (doShiftFlow) {
flowRate = flowRate + _getFlowRate(eff, adjustmentFlowHash);
}
eff = _doFlow(eff, pool, adjustmentRecipient, adjustmentFlowHash, flowRate, t);
return eff;
}
function isPool(ISuperfluidToken token, address account) external view override returns (bool) {
return _isPool(token, account);
}
function _isPool(ISuperfluidToken token, address account) internal view returns (bool exists) {
bytes32[] memory slotData =
token.getAgreementStateSlot(address(this), account, _UNIVERSAL_INDEX_STATE_SLOT_ID, 1);
exists = ((uint256(slotData[0]) << 224) >> 224) & 1 == 1;
}
function _encodeFlowDistributionData(FlowDistributionData memory flowDistributionData)
internal
pure
returns (bytes32[] memory data)
{
data = new bytes32[](1);
data[0] = bytes32(
(uint256(uint32(flowDistributionData.lastUpdated)) << 192)
| (uint256(uint96(flowDistributionData.flowRate)) << 96) | uint256(flowDistributionData.buffer)
);
}
function _decodeFlowDistributionData(uint256 data)
internal
pure
returns (bool exist, FlowDistributionData memory flowDistributionData)
{
exist = data > 0;
if (exist) {
flowDistributionData.lastUpdated = uint32((data >> 192) & uint256(type(uint32).max));
flowDistributionData.flowRate = int96(int256(data >> 96));
flowDistributionData.buffer = uint96(data & uint256(type(uint96).max));
}
}
function _decodeFlowDistributionData(uint256 data)
internal
pure
returns (bool exist, FlowDistributionData memory flowDistributionData)
{
exist = data > 0;
if (exist) {
flowDistributionData.lastUpdated = uint32((data >> 192) & uint256(type(uint32).max));
flowDistributionData.flowRate = int96(int256(data >> 96));
flowDistributionData.buffer = uint96(data & uint256(type(uint96).max));
}
}
function _getFlowDistributionData(ISuperfluidToken token, bytes32 distributionFlowHash)
internal
view
returns (bool exist, FlowDistributionData memory flowDistributionData)
{
bytes32[] memory data = token.getAgreementData(address(this), distributionFlowHash, 1);
(exist, flowDistributionData) = _decodeFlowDistributionData(uint256(data[0]));
}
function _encodePoolMemberData(PoolMemberData memory poolMemberData)
internal
pure
returns (bytes32[] memory data)
{
data = new bytes32[](1);
data[0] = bytes32((uint256(uint32(poolMemberData.poolID)) << 160) | uint256(uint160(poolMemberData.pool)));
}
function _decodePoolMemberData(uint256 data)
internal
pure
returns (bool exist, PoolMemberData memory poolMemberData)
{
exist = data > 0;
if (exist) {
poolMemberData.pool = address(uint160(data & uint256(type(uint160).max)));
poolMemberData.poolID = uint32(data >> 160);
}
}
function _decodePoolMemberData(uint256 data)
internal
pure
returns (bool exist, PoolMemberData memory poolMemberData)
{
exist = data > 0;
if (exist) {
poolMemberData.pool = address(uint160(data & uint256(type(uint160).max)));
poolMemberData.poolID = uint32(data >> 160);
}
}
function _getPoolMemberData(ISuperfluidToken token, address poolMember, ISuperfluidPool pool)
internal
view
returns (bool exist, PoolMemberData memory poolMemberData)
{
bytes32[] memory data = token.getAgreementData(address(this), _getPoolMemberHash(poolMember, pool), 1);
(exist, poolMemberData) = _decodePoolMemberData(uint256(data[0]));
}
function _findAndFillPoolConnectionsBitmap(ISuperfluidToken token, address poolMember, bytes32 poolID)
private
returns (uint32 slotId)
{
return SlotsBitmapLibrary.findEmptySlotAndFill(
token, poolMember, _POOL_SUBS_BITMAP_STATE_SLOT_ID, _POOL_CONNECTIONS_DATA_STATE_SLOT_ID_START, poolID
);
}
function _clearPoolConnectionsBitmap(ISuperfluidToken token, address poolMember, uint32 slotId) private {
SlotsBitmapLibrary.clearSlot(token, poolMember, _POOL_SUBS_BITMAP_STATE_SLOT_ID, slotId);
}
function _listPoolConnectionIds(ISuperfluidToken token, address subscriber)
private
view
returns (uint32[] memory slotIds, bytes32[] memory pidList)
{
(slotIds, pidList) = SlotsBitmapLibrary.listData(
token, subscriber, _POOL_SUBS_BITMAP_STATE_SLOT_ID, _POOL_CONNECTIONS_DATA_STATE_SLOT_ID_START
);
}
}
| 841,340 |
[
1,
12580,
17547,
5495,
10606,
225,
14845,
2242,
1911,
225,
5235,
9995,
29584,
5495,
10606,
3287,
27705,
3340,
1910,
4694,
548,
6647,
273,
389,
10377,
31879,
67,
9199,
67,
7998,
67,
55,
1502,
56,
67,
734,
578,
374,
1234,
18,
15330,
4202,
273,
1758,
434,
30176,
3769,
21,
2236,
1850,
273,
819,
18,
3576,
12021,
27705,
3340,
1910,
9064,
279,
7651,
6393,
3711,
364,
392,
2236,
487,
5492,
487,
326,
2078,
1613,
471,
2856,
326,
2236,
353,
279,
2845,
578,
486,
18,
9708,
6968,
12224,
1910,
4694,
548,
6647,
273,
389,
20339,
67,
8362,
55,
67,
15650,
8352,
67,
7998,
67,
55,
1502,
56,
67,
734,
578,
404,
1234,
18,
15330,
4202,
273,
1758,
434,
30176,
3769,
21,
2236,
1850,
273,
819,
18,
3576,
12021,
9708,
6968,
14764,
1910,
23195,
9064,
279,
9389,
434,
326,
12169,
716,
854,
315,
5745,
6,
364,
279,
2845,
3140,
18,
8828,
4050,
87,
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,
9544,
9003,
17420,
58,
21,
353,
5495,
10606,
2171,
16,
3155,
11415,
361,
16,
467,
12580,
9003,
17420,
58,
21,
288,
203,
565,
1450,
14060,
9735,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
9735,
364,
509,
5034,
31,
203,
565,
1450,
24747,
23091,
364,
7651,
1988,
3711,
31,
203,
203,
565,
1758,
1071,
5381,
348,
1502,
8047,
67,
15650,
8352,
67,
2053,
28254,
67,
15140,
273,
1758,
12,
16266,
12224,
9313,
1769,
203,
203,
565,
1758,
1071,
5381,
16459,
654,
19054,
3060,
67,
20339,
67,
1639,
22971,
654,
67,
15140,
273,
1758,
12,
8051,
2242,
1911,
2864,
10015,
264,
9313,
1769,
203,
203,
565,
2254,
5034,
3238,
5381,
389,
10377,
31879,
67,
9199,
67,
7998,
67,
55,
1502,
56,
67,
734,
273,
374,
31,
203,
565,
2254,
5034,
3238,
5381,
389,
20339,
67,
8362,
55,
67,
15650,
8352,
67,
7998,
67,
55,
1502,
56,
67,
734,
273,
404,
31,
203,
565,
2254,
5034,
3238,
5381,
389,
20339,
67,
15461,
55,
67,
4883,
67,
7998,
67,
55,
1502,
56,
67,
734,
67,
7570,
273,
404,
2296,
8038,
31,
203,
565,
1731,
1578,
3238,
5381,
385,
2046,
58,
21,
67,
6584,
52,
67,
7203,
67,
3297,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
3341,
18,
9565,
2242,
1911,
17,
926,
1359,
18,
31135,
87,
18,
6902,
5249,
17420,
18,
90,
21,
18,
6584,
52,
1750,
8863,
203,
203,
565,
1731,
1578,
3238,
5381,
16459,
654,
8412,
67,
6236,
18605,
67,
1639,
28284,
67,
3297,
273,
203,
3639,
417,
24410,
581,
5034,
2932,
3341,
2
] |
./partial_match/1/0x1Ddad8Dfb4CB86dED31c1118e600A398C417c4b0/sources/GovernorCrowdsale.sol
|
* @dev Sets a specific beneficiary's maximum contribution. @param beneficiary Address to be capped @param cap Wei limit for individual contribution/
|
function setCap(address beneficiary, uint256 cap) external onlyCapper {
_caps[beneficiary] = cap;
}
| 2,744,239 |
[
1,
2785,
279,
2923,
27641,
74,
14463,
814,
1807,
4207,
24880,
18,
225,
27641,
74,
14463,
814,
5267,
358,
506,
3523,
1845,
225,
3523,
1660,
77,
1800,
364,
7327,
24880,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
444,
4664,
12,
2867,
27641,
74,
14463,
814,
16,
2254,
5034,
3523,
13,
3903,
1338,
4664,
457,
288,
203,
3639,
389,
22984,
63,
70,
4009,
74,
14463,
814,
65,
273,
3523,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x4Bab1619B7EEc448dCbF5b9607bcFCE0fCEBc5D5/sources/contracts/interfaces/IERC20.sol
|
Only Avalanche bridge tokens
|
function swap(address, uint256) external;
| 15,474,701 |
[
1,
3386,
432,
1125,
304,
18706,
10105,
2430,
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,
445,
7720,
12,
2867,
16,
2254,
5034,
13,
3903,
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,
-100
] |
./partial_match/1/0xB690fC16279C096999264e3C049fA133024b4d69/sources/contracts/storefront/AbstractStorefront.sol
|
solhint-disable avoid-low-level-calls */
|
(bool successfulWithdraw, ) = recipient.call{ value: amount, gas: 20000 }("");
| 3,599,573 |
[
1,
18281,
11317,
17,
8394,
4543,
17,
821,
17,
2815,
17,
12550,
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
] |
[
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,
261,
6430,
6873,
1190,
9446,
16,
262,
273,
8027,
18,
1991,
95,
460,
30,
3844,
16,
16189,
30,
576,
2787,
289,
2932,
8863,
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
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.6.0;
// pragma experimental ABIEncoderV2;
import "./Committee.sol";
import "./ProposalManager.sol";
import "./ContractAuthPrecompiled.sol";
import "./ConsensusPrecompiled.sol";
import "./SystemConfigPrecompiled.sol";
contract CommitteeManager {
// Governors and threshold
Committee public _committee;
// proposal manager
ProposalManager public _proposalMgr;
SystemConfigPrecompiled constant _systemConfigPrecompiled =
SystemConfigPrecompiled(0x1000);
ConsensusPrecompiled constant _consensusPrecompiled =
ConsensusPrecompiled(0x1003);
ContractAuthPrecompiled constant _contractPrecompiled =
ContractAuthPrecompiled(0x1005);
struct ProposalInfo {
// Committee management: 11-set governor weight; 12-set rate; 13-upgrade VoteComputer contract;
// access control: 21-set deploy auth type; 22-modify deploy auth;
// contract admin: 31-reset admin
// system config management: 41- set config
// consensus node management: 51- set weight (weigh > 0, sealer; weight = 0, observer), 52- remove
uint8 proposalType;
// unique address
address resourceId;
// uint8 array
uint8[] uint8Array;
// string array
string[] strArray;
uint32 weight;
// address array
address[] addressArray;
bool flag;
}
// [id, Proposal]
mapping(uint256 => ProposalInfo) private _proposalInfoMap;
modifier onlyGovernor() {
require(isGovernor(msg.sender), "you must be governor");
_;
}
constructor(
address[] memory initGovernors,
uint32[] memory weights,
uint8 participatesRate,
uint8 winRate
) public {
//_contractPrecompiled = ContractAuthPrecompiled(0x1005);
_committee = new Committee(
initGovernors,
weights,
participatesRate,
winRate
);
_proposalMgr = new ProposalManager(address(this), address(_committee));
}
/*
* apply for update governor
* @param external account
* @param weight, 0-delete, >0-update or insert
* @param blockNumberInterval, after current block number, it will be outdated.
*/
function createUpdateGovernorProposal(
address account,
uint32 weight,
uint256 blockNumberInterval
) public onlyGovernor returns (uint256 currentproposalId) {
address[] memory addressArray = new address[](1);
uint8[] memory uint8Array;
string[] memory strArray;
addressArray[0] = account;
ProposalInfo memory proposalInfo = ProposalInfo(
11,
account,
uint8Array,
strArray,
weight,
addressArray,
true
);
currentproposalId = _createProposal(proposalInfo, blockNumberInterval);
}
/*
* apply set participate rate and win rate.
* @param paricipate rate, [0,100]. if 0, always succeed.
* @param win rate, [0,100].
* @param blockNumberInterval, after current block number, it will be outdated.
*/
function createSetRateProposal(
uint8 participatesRate,
uint8 winRate,
uint256 blockNumberInterval
) public onlyGovernor returns (uint256 currentproposalId) {
require(
participatesRate >= 0 && participatesRate <= 100,
"invalid range of participatesRate"
);
require(winRate >= 0 && winRate <= 100, "invalid range of winRate");
address[] memory addressArray;
uint8[] memory uint8Array = new uint8[](2);
string[] memory strArray;
uint8Array[0] = participatesRate;
uint8Array[1] = winRate;
ProposalInfo memory proposalInfo = ProposalInfo(
12,
address(this),
uint8Array,
strArray,
0,
addressArray,
false
);
currentproposalId = _createProposal(proposalInfo, blockNumberInterval);
}
/*
* submit an propsal of upgrade VoteCompter.sol
* @param new address of VoteComputer
* @param contractAddr the address of contract which will propose to reset admin
*/
function createUpgradeVoteComputerProposal(
address newAddr,
uint256 blockNumberInterval
) public onlyGovernor returns (uint256 currentproposalId) {
require(newAddr != address(0), "contract address not exists.");
address[] memory addressArray = new address[](1);
uint8[] memory uint8Array;
string[] memory strArray;
addressArray[0] = newAddr;
ProposalInfo memory proposalInfo = ProposalInfo(
13,
address(_proposalMgr),
uint8Array,
strArray,
0,
addressArray,
false
);
currentproposalId = _createProposal(proposalInfo, blockNumberInterval);
}
/*
* submit an proposal of setting deploy contract auth type
* @param deployAuthType: 1- whitelist; 2-blacklist
*/
function createSetDeployAuthTypeProposal(
uint8 deployAuthType,
uint256 blockNumberInterval
) public onlyGovernor returns (uint256 currentproposalId) {
require(
_contractPrecompiled.deployType() != deployAuthType,
"the current deploy auth type is the same as you want to set"
);
address[] memory addressArray;
uint8[] memory uint8Array = new uint8[](1);
string[] memory strArray;
uint8Array[0] = deployAuthType;
ProposalInfo memory proposalInfo = ProposalInfo(
21,
address(_contractPrecompiled),
uint8Array,
strArray,
0,
addressArray,
false
);
currentproposalId = _createProposal(proposalInfo, blockNumberInterval);
}
/*
* submit an proposal of adding deploy contract auth for account
* @param account
* @param openFlag: true-open; false-close
*/
function createModifyDeployAuthProposal(
address account,
bool openFlag,
uint256 blockNumberInterval
) public onlyGovernor returns (uint256 currentproposalId) {
address[] memory addressArray = new address[](1);
addressArray[0] = account;
uint8[] memory uint8Array;
string[] memory strArray;
ProposalInfo memory proposalInfo = ProposalInfo(
22,
account,
uint8Array,
strArray,
0,
addressArray,
openFlag
);
currentproposalId = _createProposal(proposalInfo, blockNumberInterval);
}
/*
* submit an propsal of resetting contract admin
* @param newAdmin
* @param contractAddr the address of contract which will propose to reset admin
*/
function createResetAdminProposal(
address newAdmin,
address contractAddr,
uint256 blockNumberInterval
) public onlyGovernor returns (uint256 currentproposalId) {
require(contractAddr != address(0), "contract address not exists.");
// require(methodAuthMgr._owner() == address(this), "caller is not owner");
require(
newAdmin != _contractPrecompiled.getAdmin(contractAddr),
"the account has been the admin of concurrt contract."
);
address[] memory addressArray = new address[](1);
uint8[] memory uint8Array;
string[] memory strArray;
addressArray[0] = newAdmin;
ProposalInfo memory proposalInfo = ProposalInfo(
31,
contractAddr,
uint8Array,
strArray,
0,
addressArray,
false
);
currentproposalId = _createProposal(proposalInfo, blockNumberInterval);
}
/*
* submit a propsal of set system config
* @param key (tx_count_limit,consensus_leader_period,tx_gas_limit)
* @param value
*/
function createSetSysConfigProposal(
string memory key,
string memory value,
uint256 blockNumberInterval
) public onlyGovernor returns (uint256 currentproposalId) {
require(bytes(key).length > 1, "invalid key length.");
address[] memory addressArray;
uint8[] memory uint8Array;
string[] memory strArray = new string[](2);
strArray[0] = key;
strArray[1] = value;
ProposalInfo memory proposalInfo = ProposalInfo(
41,
address(_systemConfigPrecompiled),
uint8Array,
strArray,
0,
addressArray,
false
);
currentproposalId = _createProposal(proposalInfo, blockNumberInterval);
}
/*
* submit a proposal of set consensus weight
* @param node
* @param weight: weigh > 0, sealer; weight = 0, observer
* @param addFlag true-> add, false-> set
* @param blockNumberInterval, after current block number, it will be outdated.
*/
function createSetConsensusWeightProposal(
string memory node,
uint32 weight,
bool addFlag,
uint256 blockNumberInterval
) public onlyGovernor returns (uint256 currentproposalId) {
require(bytes(node).length > 1, "invalid node.");
address[] memory addressArray;
uint8[] memory uint8Array;
string[] memory strArray = new string[](1);
strArray[0] = node;
ProposalInfo memory proposalInfo = ProposalInfo(
51,
address(_consensusPrecompiled),
uint8Array,
strArray,
weight,
addressArray,
addFlag
);
currentproposalId = _createProposal(proposalInfo, blockNumberInterval);
}
/*
* submit a proposal of remove node
* @param node
* @param blockNumberInterval, after current block number, it will be outdated.
*/
function createRmNodeProposal(
string memory node,
uint256 blockNumberInterval
) public onlyGovernor returns (uint256 currentproposalId) {
require(bytes(node).length > 1, "invalid node.");
address[] memory addressArray;
uint8[] memory uint8Array;
string[] memory strArray = new string[](1);
strArray[0] = node;
ProposalInfo memory proposalInfo = ProposalInfo(
52,
address(_consensusPrecompiled),
uint8Array,
strArray,
0,
addressArray,
true
);
currentproposalId = _createProposal(proposalInfo, blockNumberInterval);
}
/*
* create proposal
* @param create address
* @param proposal type : 1X-committee;2X-deploy contract auth;3X-admin auth
* @param resource id
* @param after the block number interval, the proposal would be outdated.
*/
function _createProposal(
ProposalInfo memory proposalInfo,
uint256 blockNumberInterval
) internal returns (uint256) {
uint256 proposalId = _proposalMgr.create(
msg.sender,
proposalInfo.proposalType,
proposalInfo.resourceId,
blockNumberInterval
);
_proposalInfoMap[proposalId] = proposalInfo;
//detault vote agree for the proposal.
voteProposal(proposalId, true);
return proposalId;
}
/*
* revoke proposal
* @param proposal id
*/
function revokeProposal(uint256 proposalId) public onlyGovernor {
_proposalMgr.revoke(proposalId, msg.sender);
}
/*
* unified vote
* @param proposal id
* @param true or false
*/
function voteProposal(uint256 proposalId, bool agree) public onlyGovernor {
uint8 voteStatus = _proposalMgr.vote(proposalId, agree, msg.sender);
ProposalInfo memory proposalInfo;
if (voteStatus == 2) {
uint8 proposalType = getProposalType(proposalId);
proposalInfo = _proposalInfoMap[proposalId];
if (proposalType == 11) {
if (proposalInfo.weight == 0) {
require(
proposalInfo.addressArray[0] != msg.sender,
"You can not remove yourself!"
);
}
_committee.setWeight(
proposalInfo.addressArray[0],
proposalInfo.weight
);
} else if (proposalType == 12) {
_committee.setRate(
proposalInfo.uint8Array[0],
proposalInfo.uint8Array[1]
);
} else if (proposalType == 13) {
_proposalMgr.setVoteComputer(proposalInfo.addressArray[0]);
} else if (proposalType == 21) {
_contractPrecompiled.setDeployAuthType(
proposalInfo.uint8Array[0]
);
} else if (proposalType == 22) {
if (proposalInfo.flag) {
_contractPrecompiled.openDeployAuth(
proposalInfo.addressArray[0]
);
} else {
_contractPrecompiled.closeDeployAuth(
proposalInfo.addressArray[0]
);
}
} else if (proposalType == 31) {
// (contractAddress, adminAddress)
_contractPrecompiled.resetAdmin(
proposalInfo.resourceId,
proposalInfo.addressArray[0]
);
} else if (proposalType == 41) {
_systemConfigPrecompiled.setValueByKey(
proposalInfo.strArray[0],
proposalInfo.strArray[1]
);
} else if (proposalType == 51) {
if (proposalInfo.flag) {
if (proposalInfo.weight == 0) {
_consensusPrecompiled.addObserver(
proposalInfo.strArray[0]
);
} else {
_consensusPrecompiled.addSealer(
proposalInfo.strArray[0],
uint256(proposalInfo.weight)
);
}
} else {
_consensusPrecompiled.setWeight(
proposalInfo.strArray[0],
uint256(proposalInfo.weight)
);
}
} else if (proposalType == 52) {
_consensusPrecompiled.remove(proposalInfo.strArray[0]);
} else {
revert("vote type error.");
}
}
}
/*
* predicate governor
* @param external account
*/
function isGovernor(address account) public view returns (bool) {
return _committee.isGovernor(account);
}
/*
* get proposal type
* @param proposal id
*/
function getProposalType(uint256 proposalId) public view returns (uint8) {
return _proposalInfoMap[proposalId].proposalType;
}
}
|
predicate governor @param external account/
|
function isGovernor(address account) public view returns (bool) {
return _committee.isGovernor(account);
}
| 12,710,204 |
[
1,
18344,
314,
1643,
29561,
225,
3903,
2236,
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
] |
[
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,
445,
353,
43,
1643,
29561,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
7371,
22579,
18,
291,
43,
1643,
29561,
12,
4631,
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
] |
./full_match/4/0x4225d2e50ce41C1aA9363EE494E1d463475cf97A/sources/tribute.sol
|
TO DO - confirm proposal has processed release tribute from escrow based on proposal outcome
|
function releaseTributeProposal(IKaliDAOtribute dao, uint256 proposal) public nonReentrant virtual {
Tribute storage trib = tributes[dao][proposal];
require(address(trib.dao) != address(0), 'NOT_PROPOSAL');
if (dao.passed(proposal)) {
if (trib.asset == address(0)) {
SafeTransferLib.safeTransferETH(address(trib.dao), trib.amount);
SafeTransferLib.safeTransfer(trib.asset, address(trib.dao), trib.amount);
}
if (trib.asset == address(0)) {
SafeTransferLib.safeTransferETH(trib.proposer, trib.amount);
SafeTransferLib.safeTransfer(trib.asset, trib.proposer, trib.amount);
}
}
delete tributes[dao][proposal];
emit TributeProposalReleased(dao, proposal);
}
| 745,808 |
[
1,
4296,
5467,
300,
6932,
14708,
711,
5204,
3992,
433,
495,
624,
628,
2904,
492,
2511,
603,
14708,
12884,
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,
3992,
1070,
495,
624,
14592,
12,
45,
47,
18083,
18485,
887,
15229,
16,
2254,
5034,
14708,
13,
1071,
1661,
426,
8230,
970,
5024,
288,
203,
3639,
840,
495,
624,
2502,
433,
495,
273,
433,
495,
993,
63,
2414,
83,
6362,
685,
8016,
15533,
203,
3639,
2583,
12,
2867,
12,
665,
18,
2414,
83,
13,
480,
1758,
12,
20,
3631,
296,
4400,
67,
3373,
7057,
1013,
8284,
203,
203,
3639,
309,
261,
2414,
83,
18,
23603,
12,
685,
8016,
3719,
288,
203,
5411,
309,
261,
665,
18,
9406,
422,
1758,
12,
20,
3719,
288,
203,
7734,
14060,
5912,
5664,
18,
4626,
5912,
1584,
44,
12,
2867,
12,
665,
18,
2414,
83,
3631,
433,
495,
18,
8949,
1769,
203,
7734,
14060,
5912,
5664,
18,
4626,
5912,
12,
665,
18,
9406,
16,
1758,
12,
665,
18,
2414,
83,
3631,
433,
495,
18,
8949,
1769,
203,
5411,
289,
203,
5411,
309,
261,
665,
18,
9406,
422,
1758,
12,
20,
3719,
288,
203,
7734,
14060,
5912,
5664,
18,
4626,
5912,
1584,
44,
12,
665,
18,
685,
5607,
16,
433,
495,
18,
8949,
1769,
203,
7734,
14060,
5912,
5664,
18,
4626,
5912,
12,
665,
18,
9406,
16,
433,
495,
18,
685,
5607,
16,
433,
495,
18,
8949,
1769,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
1430,
433,
495,
993,
63,
2414,
83,
6362,
685,
8016,
15533,
203,
203,
3639,
3626,
840,
495,
624,
14592,
26363,
12,
2414,
83,
16,
14708,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.4;
import "Vehicle.sol";
import "IndexedMarketplace.sol";
contract DMR is IndexedMarketplace {
event VehicleIssued(address addr);
address[] private vehicles;
uint private lastPlate = 0;
mapping(string => address) private index;
mapping(uint => address) private licensePlates;
function DMR(Token _token) IndexedMarketplace(_token) { }
function issueVehicle(string _vin, string _brand, string _model, string _year, string _color) returns(address) {
/* Check of the plate number is already in use */
if(index[_vin] != address(0x0)) throw;
/* Creating the new vehicle */
var vehicle = new Vehicle(_vin, _brand, _model, _year, _color);
/* Transferring the ownership to caller */
vehicle.transferOwnership(msg.sender);
/* Registering the car */
vehicles.push(address(vehicle));
index[_vin] = address(vehicle);
lastPlate = lastPlate + 1;
licensePlates[lastPlate] = address(vehicle);
/* Fireing event */
VehicleIssued(address(vehicle));
return address(vehicle);
}
/* Search for registered vehicles */
function lookup(uint _plate) constant returns(address){
return licensePlates[_plate];
}
function isVinRegistered(string _vin) constant returns(bool) {
return index[_vin] != address(0x0);
}
/* Get a complete list of all vehicles */
function getVehicles() constant returns(address[]){
return vehicles;
}
/* Maybe it is more efficient to return all data and then filtering it? */
function getVehiclesOwnedBy(address _addr) constant returns(address[]){
var index = 0;
address[] memory cars = new address[](2);
for(uint i = 0; i < vehicles.length; i++){
if(Vehicle(vehicles[i]).owner() == _addr){
/* Fuck langauges without dynamic lists... */
if(index == cars.length){
address[] memory n = new address[](cars.length * 2);
for(uint j = 0; j < cars.length; j++){
n[j] = cars[j];
}
cars = n;
}
cars[index] = vehicles[i];
index++;
}
}
address[] memory result = new address[](index);
for(uint k = 0; k < index; k++){
result[k] = cars[k];
}
return result;
}
}
|
Maybe it is more efficient to return all data and then filtering it? */ Fuck langauges without dynamic lists... */
|
function getVehiclesOwnedBy(address _addr) constant returns(address[]){
var index = 0;
address[] memory cars = new address[](2);
for(uint i = 0; i < vehicles.length; i++){
if(Vehicle(vehicles[i]).owner() == _addr){
if(index == cars.length){
address[] memory n = new address[](cars.length * 2);
for(uint j = 0; j < cars.length; j++){
n[j] = cars[j];
}
cars = n;
}
cars[index] = vehicles[i];
index++;
}
}
address[] memory result = new address[](index);
for(uint k = 0; k < index; k++){
result[k] = cars[k];
}
return result;
}
| 6,360,129 |
[
1,
24876,
518,
353,
1898,
14382,
358,
327,
777,
501,
471,
1508,
11346,
518,
35,
342,
478,
9031,
3303,
6480,
281,
2887,
5976,
6035,
2777,
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
] |
[
1,
1,
1,
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,
11031,
73,
76,
8383,
5460,
18696,
12,
2867,
389,
4793,
13,
5381,
1135,
12,
2867,
63,
5717,
95,
203,
203,
3639,
569,
770,
273,
374,
31,
203,
3639,
1758,
8526,
3778,
276,
5913,
273,
394,
1758,
8526,
12,
22,
1769,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
411,
10489,
76,
8383,
18,
2469,
31,
277,
27245,
95,
203,
5411,
309,
12,
58,
73,
18870,
12,
537,
76,
8383,
63,
77,
65,
2934,
8443,
1435,
422,
389,
4793,
15329,
203,
203,
7734,
309,
12,
1615,
422,
276,
5913,
18,
2469,
15329,
203,
10792,
1758,
8526,
3778,
290,
273,
394,
1758,
8526,
12,
71,
5913,
18,
2469,
380,
576,
1769,
203,
10792,
364,
12,
11890,
525,
273,
374,
31,
525,
411,
276,
5913,
18,
2469,
31,
525,
27245,
95,
203,
13491,
290,
63,
78,
65,
273,
276,
5913,
63,
78,
15533,
203,
10792,
289,
203,
10792,
276,
5913,
273,
290,
31,
203,
7734,
289,
203,
203,
7734,
276,
5913,
63,
1615,
65,
273,
10489,
76,
8383,
63,
77,
15533,
203,
203,
7734,
770,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
1758,
8526,
3778,
563,
273,
394,
1758,
8526,
12,
1615,
1769,
203,
203,
3639,
364,
12,
11890,
417,
273,
374,
31,
417,
411,
770,
31,
417,
27245,
95,
203,
5411,
563,
63,
79,
65,
273,
276,
5913,
63,
79,
15533,
203,
3639,
289,
203,
203,
3639,
327,
563,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/**
* @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;
// @dev The Ownable constructor sets the original 'onwer' 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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
// @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 the owner to puase. Triggers stopped state
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
// @dev called by the owner to unpause, returns to normal state
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
// @dev Returns true if the claimant owns the token.
// @param _claimant - Address caliming to own the token.
// @param _tokenId - ID of token whose ownership needs to be verified
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return(nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
// @dev Escrows the NFT, assigning ownership to this contract.
// Throws if the escrow fails.
// @param _owner - Current owner address of token to escrow.
// @param _tokenId - ID of token whose approval to verify
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
// @dev Transfers an NFT owned by this contract to another address.
// Returns true if the transfer succeeds
// @param _receiver - Address to transfer NFT to.
// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
// @dev Adds an auction to the list of open auctions. Also fires the
// AuctionCreated event
// @param _tokenId - The ID of the token to be put on the auctioin.
// @param _auction - Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
// @dev Computes the price and transfers winnings.
// Does NOT transfer ownership of token
function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) {
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction 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 auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// 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 aggainst reentrancy attacks by removing the auction
// 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 cancelAuction().)
seller.transfer(sellerProceeds);
}
// 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 = _bidAmount - price;
if (bidExcess > 0) {
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
}
// Tell the world!
AuctionSuccessful(_tokenId,price, msg.sender);
return price;
}
// @dev Removes an auction from the list of open auctions.
// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
// @dev Returns true if the NFT is on auction.
// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
// @dev Returns current price of an NFT on auction. Broken into two
// functions (this one, that computes the duration from the auction
// structure, and the other that does the price computation) so we
// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction) internal view returns (uint256) {
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Progably not necessary (since Ethereum guarantees that the
// now variables doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
// @dev Computes the current price of an auction. Factored out
// from _currentPrice so we can run extensive unit tests.
// When testing, make this function public and turn on
// 'Current price computation' test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less than _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
// @dev Computes owner's cut of a sale.
// #param _price - Sale price of NFT.
function _computeCut(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 ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
contract ClockAuction is Pausable, ClockAuctionBase {
// @dev The ERC-165 interface signature for ERC721.
// Ref: https://github.com/ethereum/EIPs/issues/165
// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
// @dev Constructor creates a reference to the NFT ownership contract
// and verifies the owner cut is in the valid range.
// @param _nftAddress - address of a deployed contract implementing
// the Nonfungible Interface
// @param _cut - percent cut the owner takes on each auction, must be
// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
// @dev Remove all Ether from the contract, which is the owner's cuts
// as well as any Ether sent directly to the contract address.
// Always transfers to the NFT contract, but can be called either by
// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
nftAddress.transfer(nftAddress.balance);
}
// @dev Creates and begins a new auction.
// @param _tokenId - ID of token to auction, sender must be owner.
// @param _startingPrice - Price of iten (in wei) at beginning of auction.
// @param _endingPrice - Price of item (in wei) at beginning of auction.
// @param _duration - Length of time to move between starting
// price and ending price (in seconds).
// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
// @dev Bids on an open auction, completing the auction and transferring
// ownership of the NFT if enough Ether is supplied
// @param _tokenId - ID of token to bid on
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funs tranfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
// @dev Cancels an auction that hasn't been won yet.
// 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 auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
// @dev Cancels an auction when the contract is paused.
// Only the owner may do this, and NFTs are returned to
// the seller. This should only be used in emergencies.
// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
// @dev Returns auction info for an NFT on auction.
// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
// @dev Returns the current price of an auction.
// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of gen0 cards
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
// @dev Creates and begins a new auction.
// @param _tokenId - ID of token to auction, sender must be owner.
// @param _startingPrice - Price of item (in wei) at beginning of auction.
// @param _endingPrice - Price of item (in wei) at end of auction.
// @param _duration - Length of auction (in seconds).
// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
// @dev Updates lastSalePrice if seller is the nft contract
// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
external
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
contract AccessControl {
/// @dev The addresses of the accounts (or contracts) that can execute actions within each roles
address public ceoAddress;
address public cooAddress;
/// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Access modifier for any CLevel functionality
modifier onlyCLevel() {
require(msg.sender == ceoAddress || msg.sender == cooAddress);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @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 Pause the smart contract. Only can be called by the CEO
function pause() public onlyCEO whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Only can be called by the CEO
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
contract CryptoCardsBase is AccessControl {
/*** EVENTS ***/
// @dev The spawn event is fired whenever a new card is minted
event Spawn(address owner, uint256 tokenId, uint128 skills, bytes32 name);
// @dev Transfer event as defined in current draft of ERC721. Emitted evry time a
// card ownership is assigned, including minting
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
// @dev The main Card struct. Every card in CryptoCards is represented by a copy
// of this structure.
// WORK IN PROGRESS
struct Card {
// Contains info on skills/traits/rarity fo card
uint128 skills;
// The timestamp from the block when this card came into existence
uint64 spawnTime;
// The minimum timestamp after which this card can engage in
// combining activities again.
uint64 cooldownEndBlock;
// Name of the card
bytes32 name;
// The ID of the parents of this card, set to 0 for gen0 cards.
uint32 firstIngredientId;
uint32 secondIngredientId;
// Set to the ID of one of the ingredient cards, chosen pseudorandomly
// Will indicate this card is combining with other card to spawn new card
// and point to other card. Non zero ID indicates it is 'combining' and is
// unusable in play.
uint32 combiningWithId;
// Set to index in cooldown array (see below) that represents
// the current cooldown duration for this card
uint16 cooldownIndex;
// The 'generation number' of this card. Generation number is the
// the larger of the two 'ingredient's' generation + 1
// (i.e. max(firstIngredientId.generation, secondIndredientId.generation) + 1)
uint16 generation;
}
/*** CONSTANTS ***/
// @dev A lookup table indicating the cooldown duration after any successful
// combination.
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 Card struct for cards in existence. The ID
// of each card is an index into this array.
Card[] cards;
// @dev A mapping from card IDs to the address that owns them. All cards have
// some valid owner address.
mapping (uint256 => address) public cardIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
// @dev A mapping from card IDs to an address that has been approved to call
// transferFrom(). Each card can only have one approved address for transfer
// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public cardIndexToApproved;
// @dev The addrress of a custom ClockAuction that handles sales of Cards. This
// will handle peer-to-peer sales as well as the gen0 sales
SaleClockAuction public saleAuction;
// @dev Assigns ownership of a specific Card to an address
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Increase ownershipTokenCount of address receiving card
ownershipTokenCount[_to]++;
// Transfer ownership.
cardIndexToOwner[_tokenId] = _to;
// Additional accounting. Newly minted cards 'from' address would be zero
// so check for that first
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete cardIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
// @dev An internal method that creates a new card and stores it. This
// method doesn't do any checking and should only be called when the
// input data is known to be valid. Will generate a Spawn event
// and a Transfer event.
// @param _skills contains crucial info about card
// @param _owner The initial owner of this card, must be nonzero
function _createCard(
uint256 _skills,
bytes32 _name,
uint256 _firstIngredientId,
uint256 _secondIngredientId,
uint256 _generation,
address _owner
)
internal
returns(uint256)
{
// These requires make sure _createCard is being passed correctly sized values
require(_firstIngredientId == uint256(uint32(_firstIngredientId)));
require(_secondIngredientId == uint256(uint32(_secondIngredientId)));
require(_generation == uint256(uint16(_generation)));
require(_skills == uint256(uint128(_skills)));
// Sets initial cooldown index to floor(generation/2)
uint16 _cooldownIndex = uint16(_generation / 2);
if (_cooldownIndex > 13) {
_cooldownIndex = 13;
}
Card memory _card = Card({
skills: uint128(_skills),
name: _name,
spawnTime: uint64(now),
cooldownEndBlock: 0,
firstIngredientId: uint32(_firstIngredientId),
secondIngredientId: uint32(_secondIngredientId),
combiningWithId: 0,
cooldownIndex: _cooldownIndex,
generation: uint16(_generation)
});
uint256 newCardId = cards.push(_card) - 1;
// emit the Spawn event
Spawn(_owner, newCardId, _card.skills, _card.name);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newCardId);
return newCardId;
}
}
contract CardOwnership is CryptoCardsBase, ERC721 {
// @notice Name and symbol of the non fungible token, as defined in ERC721
string public constant name = "CryptoCards";
string public constant symbol = "CC";
/*** POTENTIAL METADATA & INTERFACE STUFF ***/
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
// Returns true for any standardized interfaces implemented by this contract. We implement
// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/*** INTERNAL UTILITY FUNCTIONS ***/
// These functions assume that their input arguments are valid.
// Leaving it to public methods to sanitize inputs
// @dev Checks if a given address is the current owner of a particular Card
// @param _claimant the address we are validating against
// @param _tokenId card id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return cardIndexToOwner[_tokenId] == _claimant;
}
// @dev Checks if a given address currently has transferApproval for a pareticular Card.
// @param _claimant the address we are confirming the kitten is approved for.
// @param _tokenId Card ID, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return cardIndexToApproved[_tokenId] == _claimant;
}
// @dev Marks an address as being approved for transferFrom(), overwriting any previous
// approval. Setting _approved to address (0) clears all transfer approval.
// NOTE: _approve() does NOT send the Approval event. This is intentional because
// _approve() and transferFrom() are used together for putting Cards on auction, and
// there is no value in spamming the log with Approval events in that case
function _approve(uint256 _tokenId, address _approved) internal {
cardIndexToApproved[_tokenId] = _approved;
}
// @notice Returns the number of Cards owned by a specific address.
// @param _owner the owner address to check.
// @dev Required for ERC721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
// @notice Transfers a Card to another address. If transferring to a smart
// contract be VERY CAREFUL to ensure that it is are of ERC721 (or
// CryptoCards specifically) or your Card may be lost forever. Fo Rlz.
// @param _to The address of the recipient
// @param _tokenId The ID of the Card to transfer
// @dev Required for ERC721 compliance
function transfer(address _to, uint256 _tokenId) external whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any Cards (except very briefly
// after a gen0 Card is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of kitties
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own Card
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event
_transfer(msg.sender, _to, _tokenId);
}
// @notice Grant another address the right to transfer a specific Card via
// transferFrom(). This is the preferred flow for transferring NFTs to contracts.
// @param _to The address to be granted transfer approval. Pass address(0) to
// clear all approvals.
// @param _tokenId The ID of the Card that can be transferred if this call succeeds.
// @dev Required for ERC721 compliance
function approve(address _to, uint256 _tokenId) external whenNotPaused {
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
// @notice Transfer a Card owned by another address, for which the calling address
// has previously been granted transfer approval by the owner.
// @param _from The address that owns the Card to be transferred.
// @param _to The address that should take ownershuip of the Card. Can be any address,
// including the caller.
// @param _tokenId The ID of the Card to be transferred.
// @dev Required for ERC721 compliance.
function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any Cards (except very briefly
// after a gen0 card is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
// @notice Returns the total number of Cards currently in existence.
// @dev Required for ERC721 compliance.
function totalSupply() public view returns (uint) {
return cards.length;
}
// @notice Returns the address currently assigned ownership of a given Card.
// @dev Required for ERC721 compliance.
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = cardIndexToOwner[_tokenId];
require(owner != address(0));
}
// @notice Returns a list of all Card IDs assigned to an address.
// @param _owner The owner whose Cards we are interested in.
// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
// expensive (it walks the intire Card array looking for Cards 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 totalCards = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all cats have IDs starting at 1 and increasing
// sequentially up to the totalCard count
uint256 cardId;
for (cardId = 0; cardId <= totalCards; cardId++) {
if (cardIndexToOwner[cardId] == _owner) {
result[resultIndex] = cardId;
resultIndex++;
}
}
return result;
}
}
// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
// This method is licenced under the Apache License.
// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chuncks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
// This method is licensed under the Apache License.
// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
}
contract skillScience {
// @dev Number of times to loop through various skills
uint256 public numLoops;
// Array containing trait strings for easy referencing
uint128[] public traitStrings;
// Define array to mask skills string to extract appropriate attributes
function maskArray() internal {
// Starting point
uint128 baseMask = 0xFFFF0000000000000000000000000000;
for(uint256 i = 0; i < numLoops; i++) {
uint128 thisMask = baseMask >> (4 * i);
traitStrings.push(thisMask);
}
}
// Constructor for SkillScience -- initializes array (so far)
function skillScience(uint256 _numLoops) public {
// make sure numLoops is not too large
//require(numLoops == uint256(uint32(_numLoops)));
numLoops = _numLoops;
maskArray();
}
function _mixSkills(uint128 _skills1, uint128 _skills2) internal returns (uint128) {
// Arrays which will hold values of each trait for both 'ingredients'
uint16[] memory firstTraitVals = new uint16[](numLoops);
uint16[] memory secondTraitVals = new uint16[](numLoops);
// New array of skills
uint16[] memory newTraitVals = new uint16[](numLoops);
uint128 newSkills;
uint256 timeStamp = now;
firstTraitVals = defineTraitVals(_skills1);
secondTraitVals = defineTraitVals(_skills2);
// Loop through parent attributes to generate new spawned card traits
for(uint256 i = 0; i < numLoops; i++) {
uint256 nowHash = uint256(keccak256(timeStamp + i));
uint256 index = myRand(0, 7, nowHash);
if(index < 5) {
newTraitVals[index] = baseSkillMix(index, nowHash, firstTraitVals, secondTraitVals);
} else {
newTraitVals[index] = traitChoose(index, nowHash, firstTraitVals, secondTraitVals);
}
}
newSkills = combine(newTraitVals);
return newSkills;
}
function defineTraitVals(uint128 _skills) internal view returns(uint16[]) {
uint16[] memory vals = new uint16[](8);
for(uint256 i = 0; i < 8; i++){
uint128 _mask = traitStrings[i];
uint16 thisTrait = uint16((_skills & _mask) >> 4*(7 - i));
vals[i] = thisTrait;
}
return vals;
}
// Create new skill string from newTraitVals array
function combine(uint16[] memory newTraitVals) internal view returns(uint128) {
uint128 _newSkills = 0;
for(uint256 i = 0; i < 8; i++) {
uint128 preShift = uint128(newTraitVals[i]);
_newSkills += preShift << 4 * (7 - i);
}
return _newSkills;
}
function baseSkillMix(uint256 ind, uint256 thisHash, uint16[] memory firstTraitVals, uint16[] memory secondTraitVals) internal returns (uint16){
uint256 outcome = myRand(0, 3, thisHash % 1009);
if(outcome == 0){
return ++firstTraitVals[ind];
} else if(outcome == 1) {
return --firstTraitVals[ind];
} else if(outcome == 2) {
return ++secondTraitVals[ind];
} else {
return --secondTraitVals[ind];
}
}
function traitChoose(uint256 ind, uint256 thisHash, uint16[] memory firstTraitVals, uint16[] memory secondTraitVals) internal returns (uint16) {
uint256 outcome = myRand(0, 2, thisHash % 1009);
if(outcome == 0){
return firstTraitVals[ind];
} else if(outcome == 1) {
return firstTraitVals[ind];
} else {
return 0;
}
}
/* ************************************
Insert Description stuff here
************************************** */
// Returns an integer x such that low <= x <= high
function myRand(uint256 low, uint256 high, uint256 myHash) internal returns(uint256) {
// Ensure no negative values or mod(0) operations
require(high > low);
uint256 modVal = high - low + 1;
uint256 result = low + (myHash % modVal);
return result;
}
}
contract SkillScienceInterface is skillScience{
function SkillScienceInterface(uint256 _numLoops) public
skillScience(_numLoops){}
function isSkillScience() public pure returns (bool) {
return true;
}
function mixSkills(uint128 skills1, uint128 skills2) public returns (uint128) {
return 2;
}
}
contract CardCombining is CardOwnership {
event Combining(address owner, uint256 firstIngredientId, uint256 secondIngredientId);
event AutoCombine(uint256 cardId, uint256 cooldownEndBlock);
uint256 public autoCombineFee = 1000000 * 1000000000; // (1M * 1 gwei)
// Keeps track of number of combining cards
uint256 public combiningCards;
SkillScienceInterface public skillScience;
function setSkillScienceAddress(address _address) public onlyCEO {
SkillScienceInterface candidateContract = SkillScienceInterface(_address);
require(candidateContract.isSkillScience());
skillScience = candidateContract;
}
function _isReadyToCombine(Card _card) internal view returns (bool) {
return (_card.combiningWithId == 0) && (_card.cooldownEndBlock <= uint64(block.number));
}
function _isCombiningPermitted(uint256 _firstIngredientId, uint256 _secondIngredientId) internal view returns (bool) {
address cardOwner = cardIndexToOwner[_firstIngredientId];
address secondCardOwner = cardIndexToOwner[_secondIngredientId];
return (cardOwner == secondCardOwner);
}
function _triggerCooldown(Card storage _card) internal {
_card.cooldownEndBlock = uint64((cooldowns[_card.cooldownIndex] / secondsPerBlock) + block.number);
if(_card.cooldownIndex < 13) {
_card.cooldownIndex += 1;
}
}
function setAutoCombineFee(uint256 val) public onlyCOO {
autoCombineFee = val;
}
// Check to see if the cards are combining and the time period has passed
function _isReadyToSpawn(Card _card) private view returns (bool) {
return (_card.combiningWithId != 0) && (_card.cooldownEndBlock <= now);
}
// Checks that the given card is able to breed, ie not currently combining or in cooldown
function isReadyToCombine(uint256 _cardId)
public
view
returns (bool)
{
require(_cardId > 0);
Card storage card = cards[_cardId];
return _isReadyToCombine(card);
}
function _isValidCombination(
Card storage _firstIngredient,
uint256 _firstIngredientId,
Card storage _secondIngredient,
uint256 _secondIngredientId
)
private
view
returns(bool)
{
// Can't combine card with itself!
if (_firstIngredientId == _secondIngredientId) {
return false;
}
// Allow combination if either are gen 0
if(_firstIngredient.firstIngredientId == 0 || _secondIngredient.firstIngredientId == 0) {
return true;
}
return true;
}
function canCombineWith(uint256 _firstIngredientId, uint256 _secondIngredientId)
public
view
returns(bool)
{
require(_firstIngredientId >= 0);
require(_secondIngredientId >= 0);
Card storage firstIngredient = cards[_firstIngredientId];
Card storage secondIngredient = cards[_secondIngredientId];
return _isValidCombination(firstIngredient, _firstIngredientId, secondIngredient, _secondIngredientId);
}
function combineWith(uint256 _firstIngredientId, uint256 _secondIngredientId) public whenNotPaused {
require(_owns(msg.sender, _firstIngredientId));
require(_isCombiningPermitted(_firstIngredientId, _secondIngredientId));
Card storage firstIngredient = cards[_firstIngredientId];
require(_isReadyToCombine(firstIngredient));
Card storage secondIngredient = cards[_secondIngredientId];
require(_isReadyToCombine(secondIngredient));
require(_isValidCombination(
firstIngredient,
_firstIngredientId,
secondIngredient,
_secondIngredientId
));
// All checks passed, card gets pregnant!
_combineWith(_firstIngredientId, _secondIngredientId);
}
function _combineWith(uint256 _firstIngredientId, uint256 _secondIngredientId) internal {
Card storage firstIngredient = cards[_firstIngredientId];
Card storage secondIngredient = cards[_secondIngredientId];
firstIngredient.combiningWithId = uint32(_secondIngredientId);
_triggerCooldown(firstIngredient);
_triggerCooldown(secondIngredient);
// Every time a card combines, counter is incremented
combiningCards++;
Combining(cardIndexToOwner[_firstIngredientId], _firstIngredientId, _secondIngredientId);
}
function spawnCard(uint256 _firstIngredientId)
public
whenNotPaused
returns(uint256)
{
Card storage firstIngredient = cards[_firstIngredientId];
require(firstIngredient.spawnTime != 0);
require(_isReadyToSpawn(firstIngredient));
uint256 secondIngredientId = firstIngredient.combiningWithId;
Card storage secondIngredient = cards[secondIngredientId];
uint newGen = firstIngredient.generation;
if (secondIngredient.generation > firstIngredient.generation) {
newGen = secondIngredient.generation;
}
uint256 newCardSkills = skillScience.mixSkills(firstIngredient.skills, secondIngredient.skills);
address owner = cardIndexToOwner[_firstIngredientId];
uint256 cardId = _createCard(newCardSkills, firstIngredient.name, _firstIngredientId, firstIngredient.combiningWithId, newGen + 1, owner);
delete firstIngredient.combiningWithId;
// Every time card spawns, counter is decremented.
combiningCards--;
return cardId;
}
}
contract CardAuction is CardCombining {
// @notice The auction contract variables are defined in CryptoCardsBase to allow
// us to refer to them in CardOwnership to prevent accidental transfers.
// @dev Sets the reference to the sale auction.
// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: Verify that a contract is what we expect
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
// @dev Put a kitty up for auction.
// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _cardId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If card is already on any auction, this will throw
// becuase it will be owned by the auction contract.
require(_owns(msg.sender, _cardId));
_approve(_cardId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer approval after escrowing the card
saleAuction.createAuction(
_cardId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
}
contract CardMinting is CardAuction {
// Constants for gen0 auctions.
// DANGER CHANGED THESE CONSTANTS
uint256 public constant GEN0_STARTING_PRICE = 1 wei;
uint256 public constant GEN0_AUCTION_DURATION = 1 days;
// Counts the number of cards the contract owner has created.
uint256 public gen0CreatedCount;
// @dev Creates a new gen0 card with the given skills and
// creates an auction for it.
function createGen0Auction(uint128 _skills, bytes32 _name) external onlyCLevel {
uint256 cardId = _createCard(_skills, _name, 0, 0, 0, address(this));
_approve(cardId, saleAuction);
saleAuction.createAuction(
cardId,
_computeNextGen0Price(),
0,
GEN0_AUCTION_DURATION,
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 = saleAuction.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 CryptoCardsCore is CardMinting {
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
// @notice Creates the main CryptoKitties smart contract instance.
function CryptoCardsCore() public payable {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the intial COO
cooAddress = msg.sender;
}
// @notice No tipping!
// @dev Reject all Ether from being sent here, unless it's from one of the
// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
// @notice Returns all the relevant info about a specific card.
// @param _id The ID of the card of interest.
function getCard(uint256 _id) external view returns (
bool isCombining,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 combiningWithId,
uint256 spawnTime,
uint256 firstIngredientId,
uint256 secondIngredientId,
uint256 generation,
uint256 skills,
bytes32 name
) {
Card storage card = cards[_id];
isCombining = (card.combiningWithId != 0);
isReady = (card.cooldownEndBlock <= block.number);
cooldownIndex = uint256(card.cooldownIndex);
nextActionAt = uint256(card.cooldownEndBlock);
combiningWithId = uint256(card.combiningWithId);
spawnTime = uint256(card.spawnTime);
firstIngredientId = uint256(card.firstIngredientId);
secondIngredientId = uint256(card.secondIngredientId);
generation = uint256(card.generation);
skills = uint256(card.skills);
name = card.name;
}
// @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 onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
require(skillScience != address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CEO to capture the balance available to the contract.
function withdrawBalance() external onlyCEO {
uint256 balance = this.balance;
// Subtract all the currently combining cards, plus 1 of margin.
uint256 subtractFees = (combiningCards + 1) * autoCombineFee;
if (balance > subtractFees) {
ceoAddress.transfer(balance - subtractFees);
}
}
}
|
@notice Name and symbol of the non fungible token, as defined in ERC721 @notice Introspection interface as per ERC-165 (https:github.com/ethereum/EIPs/issues/165). Returns true for any standardized interfaces implemented by this contract. We implement ERC-165 (obviously!) and ERC-721.
|
contract CardOwnership is CryptoCardsBase, ERC721 {
string public constant name = "CryptoCards";
string public constant symbol = "CC";
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return cardIndexToOwner[_tokenId] == _claimant;
}
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return cardIndexToApproved[_tokenId] == _claimant;
}
function _approve(uint256 _tokenId, address _approved) internal {
cardIndexToApproved[_tokenId] = _approved;
}
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
function transfer(address _to, uint256 _tokenId) external whenNotPaused {
require(_to != address(0));
require(_to != address(this));
require(_to != address(saleAuction));
require(_owns(msg.sender, _tokenId));
_transfer(msg.sender, _to, _tokenId);
}
function approve(address _to, uint256 _tokenId) external whenNotPaused {
require(_owns(msg.sender, _tokenId));
_approve(_tokenId, _to);
Approval(msg.sender, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused {
require(_to != address(0));
require(_to != address(this));
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
_transfer(_from, _to, _tokenId);
}
function totalSupply() public view returns (uint) {
return cards.length;
}
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = cardIndexToOwner[_tokenId];
require(owner != address(0));
}
function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCards = totalSupply();
uint256 resultIndex = 0;
uint256 cardId;
for (cardId = 0; cardId <= totalCards; cardId++) {
if (cardIndexToOwner[cardId] == _owner) {
result[resultIndex] = cardId;
resultIndex++;
}
}
return result;
}
}
function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCards = totalSupply();
uint256 resultIndex = 0;
uint256 cardId;
for (cardId = 0; cardId <= totalCards; cardId++) {
if (cardIndexToOwner[cardId] == _owner) {
result[resultIndex] = cardId;
resultIndex++;
}
}
return result;
}
}
} else {
function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCards = totalSupply();
uint256 resultIndex = 0;
uint256 cardId;
for (cardId = 0; cardId <= totalCards; cardId++) {
if (cardIndexToOwner[cardId] == _owner) {
result[resultIndex] = cardId;
resultIndex++;
}
}
return result;
}
}
function tokensOfOwner(address _owner) external view returns (uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
uint256[] memory result = new uint256[](tokenCount);
uint256 totalCards = totalSupply();
uint256 resultIndex = 0;
uint256 cardId;
for (cardId = 0; cardId <= totalCards; cardId++) {
if (cardIndexToOwner[cardId] == _owner) {
result[resultIndex] = cardId;
resultIndex++;
}
}
return result;
}
}
function _memcpy(uint _dest, uint _src, uint _len) private view {
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
function _memcpy(uint _dest, uint _src, uint _len) private view {
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
function _memcpy(uint _dest, uint _src, uint _len) private view {
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
uint256 mask = 256 ** (32 - _len) - 1;
function _memcpy(uint _dest, uint _src, uint _len) private view {
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
function _toString(bytes[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
function _toString(bytes[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
}
| 12,984,873 |
[
1,
461,
471,
3273,
434,
326,
1661,
9831,
75,
1523,
1147,
16,
487,
2553,
316,
4232,
39,
27,
5340,
225,
3094,
26362,
1560,
487,
1534,
4232,
39,
17,
28275,
261,
4528,
30,
6662,
18,
832,
19,
546,
822,
379,
19,
41,
18246,
19,
9618,
19,
28275,
2934,
225,
2860,
638,
364,
1281,
4529,
1235,
7349,
8249,
635,
333,
6835,
18,
1660,
2348,
225,
4232,
39,
17,
28275,
261,
947,
2084,
715,
24949,
471,
4232,
39,
17,
27,
5340,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
14338,
5460,
12565,
353,
15629,
30492,
2171,
16,
4232,
39,
27,
5340,
288,
203,
203,
565,
533,
1071,
5381,
508,
273,
315,
18048,
30492,
14432,
203,
565,
533,
1071,
5381,
3273,
273,
315,
6743,
14432,
203,
203,
377,
203,
565,
1731,
24,
5381,
6682,
5374,
67,
654,
39,
28275,
273,
7010,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
28064,
1358,
12,
3890,
24,
2506,
10019,
203,
203,
377,
1731,
24,
5381,
6682,
5374,
67,
654,
39,
27,
5340,
273,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
529,
11866,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
7175,
11866,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
4963,
3088,
1283,
11866,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
12296,
951,
12,
2867,
2506,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
8443,
951,
12,
11890,
5034,
2506,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
12908,
537,
12,
2867,
16,
11890,
5034,
2506,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
13866,
12,
2867,
16,
11890,
5034,
2506,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
13866,
1265,
12,
2867,
16,
2867,
16,
11890,
5034,
2506,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
7860,
951,
5541,
12,
2867,
2506,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
2316,
2277,
12,
11890,
2
] |
//Address: 0xcd820a2f792f429bf95e6d0de909d06110b44123
//Contract name: ReplaySafeSplit
//Balance: 0 Ether
//Verification Date: 9/4/2016
//Transacion Count: 1
// CODE STARTS HERE
contract RequiringFunds {
modifier NeedEth () {
if (msg.value <= 0 ) throw;
_
}
}
contract AmIOnTheFork {
function forked() constant returns(bool);
}
contract ReplaySafeSplit is RequiringFunds {
// address private constant oracleAddress = 0x8128B12cABc6043d94BD3C4d9B9455077Eb18807; // testnet
address private constant oracleAddress = 0x2bd2326c993dfaef84f696526064ff22eba5b362; // mainnet
// Fork oracle to use
AmIOnTheFork amIOnTheFork = AmIOnTheFork(oracleAddress);
// Splits the funds into 2 addresses
function split(address targetFork, address targetNoFork) NeedEth returns(bool) {
// The 2 checks are to ensure that users provide BOTH addresses
// and prevent funds to be sent to 0x0 on one fork or the other.
if (targetFork == 0) throw;
if (targetNoFork == 0) throw;
if (amIOnTheFork.forked() // if we are on the fork
&& targetFork.send(msg.value)) { // send the ETH to the targetFork address
return true;
} else if (!amIOnTheFork.forked() // if we are NOT on the fork
&& targetNoFork.send(msg.value)) { // send the ETH to the targetNoFork address
return true;
}
throw; // don't accept value transfer, otherwise it would be trapped.
}
// Reject value transfers.
function() {
throw;
}
}
|
send the ETH to the targetFork address
|
&& targetFork.send(msg.value)) {
| 2,473,649 |
[
1,
4661,
326,
512,
2455,
358,
326,
1018,
22662,
1758,
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,
6647,
597,
1018,
22662,
18,
4661,
12,
3576,
18,
1132,
3719,
288,
540,
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.24;
import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
/**
* @title IPFSeable contract
* @author cyber•Congress
* @dev Allows store in contract links to files which stored in IPFS
* @notice not recommend to use before release!
*/
contract IPFSeable is Ownable {
/*
* Storage
*/
// @dev IPFS hash link to JSON with ABI of contract
string internal linkABI;
// @dev IPFS hash link to JSON with metainformation of contract
string internal linkMeta;
// @dev IPFS hash link to *.sol of deployed contract
string internal linkSourceCode;
/*
* Events
*/
/*
* External Functions
*/
/**
* @dev Allows set new link to JSON with contract's ABI
* @param _linkABI string IPFS hash link to file
*/
function setABILink(
string _linkABI
)
external
onlyOwner
{
linkABI = _linkABI;
}
/**
* @dev Allows set new link to contract metainformation
* @param _linkMeta string IPFS hash link to file
*/
function setMetaLink(
string _linkMeta
)
external
onlyOwner
{
linkMeta = _linkMeta;
}
/**
* @dev Allows set new link to source code
* @param _linkSourceCode string IPFS hash link to file
*/
function setSourceLink(
string _linkSourceCode
)
external
onlyOwner
{
linkSourceCode = _linkSourceCode;
}
/*
* View Functions
*/
/**
* @dev getter for IPFS hask link to JSON file with contract's ABI
* @return string hash to file
*/
function getLinkABI()
public
view
returns (
string
)
{
return linkABI;
}
/**
* @dev getter for IPFS hask link to contract metainformation
* @return string hash to file
*/
function getMetaLink()
public
view
returns (
string
)
{
return linkMeta;
}
/**
* @dev getter for IPFS hask link to source code
* @return string hash to file
*/
function getSourceLink()
public
view
returns (
string
)
{
return linkSourceCode;
}
}
|
* @dev Allows set new link to contract metainformation @param _linkMeta string IPFS hash link to file/
|
function setMetaLink(
string _linkMeta
)
external
onlyOwner
{
linkMeta = _linkMeta;
}
| 940,725 |
[
1,
19132,
444,
394,
1692,
358,
6835,
5100,
530,
1471,
225,
389,
1232,
2781,
533,
2971,
4931,
1651,
1692,
358,
585,
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
] |
[
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,
0
] |
[
1,
565,
445,
29234,
2098,
12,
203,
3639,
533,
389,
1232,
2781,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
1692,
2781,
273,
389,
1232,
2781,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./exchange/Exchange.sol";
import "./registry/ProxyRegistry.sol";
import "./modules/TokenTransferProxy.sol";
import "./modules/ERC20.sol";
contract PaceArtExchange is Exchange {
string public constant name = "Project Wyvern Exchange";
string public constant version = "2.2";
string public constant codename = "Lambton Worm";
/**
* @dev Initialize a WyvernExchange instance
* @param registryAddress Address of the registry instance which this Exchange instance will use
* @param tokenAddress Address of the token used for protocol fees
*/
constructor (ProxyRegistry registryAddress, TokenTransferProxy tokenTransferProxyAddress, ERC20 tokenAddress) {
registry = registryAddress;
tokenTransferProxy = tokenTransferProxyAddress;
exchangeToken = tokenAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "../libraries/ArrayUtils.sol";
import "../libraries/SaleKindInterface.sol";
import "../libraries/ReentrancyGuarded.sol";
import "../registry/ProxyRegistry.sol";
import "../modules/TokenTransferProxy.sol";
import "../registry/AuthenticatedProxy.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ExchangeCore.sol";
import "hardhat/console.sol";
contract Exchange is ExchangeCore {
// /**
// * @dev Call guardedArrayReplace - library function exposed for testing.
// */
// function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask)
// public
// pure
// returns (bytes memory)
// {
// ArrayUtils.guardedArrayReplace(array, desired, mask);
// return array;
// }
// /**
// * Test copy byte array
// *
// * @param arrToCopy Array to copy
// * @return byte array
// */
// function testCopy(bytes memory arrToCopy)
// public
// pure
// returns (bytes memory)
// {
// bytes memory arr = new bytes(arrToCopy.length);
// uint index;
// assembly {
// index := add(arr, 0x20)
// }
// ArrayUtils.unsafeWriteBytes(index, arrToCopy);
// return arr;
// }
// /**
// * Test write address to bytes
// *
// * @param addr Address to write
// * @return byte array
// */
// function testCopyAddress(address addr)
// public
// pure
// returns (bytes memory)
// {
// bytes memory arr = new bytes(0x14);
// uint index;
// assembly {
// index := add(arr, 0x20)
// }
// ArrayUtils.unsafeWriteAddress(index, addr);
// return arr;
// }
/**
* @dev Call calculateFinalPrice - library function exposed for testing.
*/
function calculateFinalPrice(SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime)
public
view
returns (uint)
{
return SaleKindInterface.calculateFinalPrice(side, saleKind, basePrice, extra, listingTime, expirationTime);
}
/**
* @dev Call hashOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function hashOrder_(
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata)
public
pure
returns (bytes32)
{
return hashOrder(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6])
);
}
/**
* @dev Call hashToSign - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function hashToSign_(
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata)
public
pure
returns (bytes32)
{
return hashToSign(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6])
);
}
/**
* @dev Call validateOrderParameters - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function validateOrderParameters_ (
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata)
view
public
returns (bool)
{
Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
return validateOrderParameters(
order
);
}
/**
* @dev Call validateOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function validateOrder_ (
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
uint8 v,
bytes32 r,
bytes32 s)
view
public
returns (bool)
{
Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
return validateOrder(
hashToSign(order),
order,
Sig(v, r, s)
);
}
/**
* @dev Call approveOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function approveOrder_ (
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
bool orderbookInclusionDesired)
public
{
Order memory order = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
return approveOrder(order, orderbookInclusionDesired);
}
/**
* @dev Call cancelOrder - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function cancelOrder_(
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata,
uint8 v,
bytes32 r,
bytes32 s)
public
{
return cancelOrder(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]),
Sig(v, r, s)
);
}
/**
* @dev Call calculateCurrentPrice - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function calculateCurrentPrice_(
address[7] memory addrs,
uint[7] memory uints,
FeeMethod feeMethod,
SaleKindInterface.Side side,
SaleKindInterface.SaleKind saleKind,
AuthenticatedProxy.HowToCall howToCall,
bytes memory callData,
bytes memory replacementPattern,
bytes memory staticExtradata)
public
view
returns (uint)
{
return calculateCurrentPrice(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], feeMethod, side, saleKind, addrs[4], howToCall, callData, replacementPattern, addrs[5], staticExtradata, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6])
);
}
/**
* @dev Call ordersCanMatch - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function ordersCanMatch_(
address[14] memory addrs,
uint[14] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell)
public
view
returns (bool)
{
Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[7], uints[8], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, addrs[13], uints[9], uints[10], uints[11], uints[12], uints[13]);
return ordersCanMatch(
buy,
sell
);
}
/**
* @dev Return whether or not two orders' calldata specifications can match
* @param buyCalldata Buy-side order calldata
* @param buyReplacementPattern Buy-side order calldata replacement mask
* @param sellCalldata Sell-side order calldata
* @param sellReplacementPattern Sell-side order calldata replacement mask
* @return Whether the orders' calldata can be matched
*/
function orderCalldataCanMatch(bytes memory buyCalldata, bytes memory buyReplacementPattern, bytes memory sellCalldata, bytes memory sellReplacementPattern)
public
pure
returns (bool)
{
if (buyReplacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(buyCalldata, sellCalldata, buyReplacementPattern);
}
if (sellReplacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(sellCalldata, buyCalldata, sellReplacementPattern);
}
return ArrayUtils.arrayEq(buyCalldata, sellCalldata);
}
/**
* @dev Call calculateMatchPrice - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function calculateMatchPrice_(
address[14] memory addrs,
uint[14] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell)
public
view
returns (uint)
{
Order memory buy = Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]);
Order memory sell = Order(addrs[7], addrs[8], addrs[9], uints[7], uints[8], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, addrs[13], uints[9], uints[10], uints[11], uints[12], uints[13]);
return calculateMatchPrice(
buy,
sell
);
}
/**
* @dev Call atomicMatch - Solidity ABI encoding limitation workaround, hopefully temporary.
*/
function atomicMatch_(
address[14] memory addrs,
uint[14] memory uints,
uint8[8] memory feeMethodsSidesKindsHowToCalls,
bytes memory calldataBuy,
bytes memory calldataSell,
bytes memory replacementPatternBuy,
bytes memory replacementPatternSell,
bytes memory staticExtradataBuy,
bytes memory staticExtradataSell,
uint8[2] memory vs,
bytes32[5] memory rssMetadata)
public
payable
{
return atomicMatch(
Order(addrs[0], addrs[1], addrs[2], uints[0], uints[1], addrs[3], FeeMethod(feeMethodsSidesKindsHowToCalls[0]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[1]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[2]), addrs[4], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[3]), calldataBuy, replacementPatternBuy, addrs[5], staticExtradataBuy, addrs[6], uints[2], uints[3], uints[4], uints[5], uints[6]),
Sig(vs[0], rssMetadata[0], rssMetadata[1]),
Order(addrs[7], addrs[8], addrs[9], uints[7], uints[8], addrs[10], FeeMethod(feeMethodsSidesKindsHowToCalls[4]), SaleKindInterface.Side(feeMethodsSidesKindsHowToCalls[5]), SaleKindInterface.SaleKind(feeMethodsSidesKindsHowToCalls[6]), addrs[11], AuthenticatedProxy.HowToCall(feeMethodsSidesKindsHowToCalls[7]), calldataSell, replacementPatternSell, addrs[12], staticExtradataSell, addrs[13], uints[9], uints[10], uints[11], uints[12], uints[13]),
Sig(vs[1], rssMetadata[2], rssMetadata[3]),
rssMetadata[4]
);
}
}
/*
Proxy registry; keeps a mapping of AuthenticatedProxy contracts and mapping of contracts authorized to access them.
Abstracted away from the Exchange (a) to reduce Exchange attack surface and (b) so that the Exchange contract can be upgraded without users needing to transfer assets to new proxies.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./OwnableDelegateProxy.sol";
import "./ProxyRegistryInterface.sol";
/**
* @title ProxyRegistry
* @author Wyvern Protocol Developers
*/
contract ProxyRegistry is Ownable, ProxyRegistryInterface {
/* DelegateProxy implementation contract. Must be initialized. */
address public override delegateProxyImplementation;
/* Authenticated proxies by user. */
mapping(address => OwnableDelegateProxy) public override proxies;
/* Contracts pending access. */
mapping(address => uint) public pending;
/* Contracts allowed to call those proxies. */
mapping(address => bool) public contracts;
/* Delay period for adding an authenticated contract.
This mitigates a particular class of potential attack on the Wyvern DAO (which owns this registry) - if at any point the value of assets held by proxy contracts exceeded the value of half the WYV supply (votes in the DAO),
a malicious but rational attacker could buy half the Wyvern and grant themselves access to all the proxy contracts. A delay period renders this attack nonthreatening - given two weeks, if that happened, users would have
plenty of time to notice and transfer their assets.
*/
uint public DELAY_PERIOD = 2 weeks;
/**
* Start the process to enable access for specified contract. Subject to delay period.
*
* @dev ProxyRegistry owner only
* @param addr Address to which to grant permissions
*/
function startGrantAuthentication (address addr)
public
onlyOwner
{
require(!contracts[addr] && pending[addr] == 0, "Contract is already allowed in registry, or pending");
pending[addr] = block.timestamp;
}
/**
* End the process to enable access for specified contract after delay period has passed.
*
* @dev ProxyRegistry owner only
* @param addr Address to which to grant permissions
*/
function endGrantAuthentication (address addr)
public
onlyOwner
{
require(!contracts[addr] && pending[addr] != 0 && ((pending[addr] + DELAY_PERIOD) < block.timestamp), "Contract is no longer pending or has already been approved by registry");
pending[addr] = 0;
contracts[addr] = true;
}
/**
* Revoke access for specified contract. Can be done instantly.
*
* @dev ProxyRegistry owner only
* @param addr Address of which to revoke permissions
*/
function revokeAuthentication (address addr)
public
onlyOwner
{
contracts[addr] = false;
}
/**
* Register a proxy contract with this registry
*
* @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy
* @return proxy New AuthenticatedProxy contract
*/
function registerProxy()
public
returns (OwnableDelegateProxy proxy)
{
return registerProxyFor(msg.sender);
}
/**
* Register a proxy contract with this registry, overriding any existing proxy
*
* @dev Must be called by the user which the proxy is for, creates a new AuthenticatedProxy
* @return proxy New AuthenticatedProxy contract
*/
function registerProxyOverride()
public
returns (OwnableDelegateProxy proxy)
{
proxy = new OwnableDelegateProxy(msg.sender, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", msg.sender, address(this)));
proxies[msg.sender] = proxy;
return proxy;
}
/**
* Register a proxy contract with this registry
*
* @dev Can be called by any user
* @return proxy New AuthenticatedProxy contract
*/
function registerProxyFor(address user)
public
returns (OwnableDelegateProxy proxy)
{
require(proxies[user] == OwnableDelegateProxy(0), "User already has a proxy");
proxy = new OwnableDelegateProxy(user, delegateProxyImplementation, abi.encodeWithSignature("initialize(address,address)", user, address(this)));
proxies[user] = proxy;
return proxy;
}
/**
* Transfer access
*/
function transferAccessTo(address from, address to)
public
{
OwnableDelegateProxy proxy = proxies[from];
/* CHECKS */
require(OwnableDelegateProxy(msg.sender) == proxy, "Proxy transfer can only be called by the proxy");
require(proxies[to] == OwnableDelegateProxy(0), "Proxy transfer has existing proxy as destination");
/* EFFECTS */
delete proxies[from];
proxies[to] = proxy;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "../registry/ProxyRegistry.sol";
import "../libraries/TransferHelper.sol";
import "./ERC20.sol";
contract TokenTransferProxy {
/* Authentication registry. */
ProxyRegistry public registry;
constructor(ProxyRegistry _registry)
{
require(address(_registry) != address(0), "INVALID REGISTRY");
registry = _registry;
}
/**
* Call ERC20 `transferFrom`
*
* @dev Authenticated contract only
* @param token ERC20 token address
* @param from From address
* @param to To address
* @param amount Transfer amount
*/
function transferFrom(address token, address from, address to, uint amount)
public
{
require(registry.contracts(msg.sender));
TransferHelper.safeTransferFrom(token, from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./ERC20Basic.sol";
interface ERC20 is ERC20Basic {
function allowance(address owner, address spender)
external view returns (uint256);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title ArrayUtils
* @author Wyvern Protocol Developers
*/
library ArrayUtils {
/**
* Replace bytes in an array with bytes in another array, guarded by a bitmask
* Efficiency of this function is a bit unpredictable because of the EVM's word-specific model (arrays under 32 bytes will be slower)
* Modifies the provided byte array parameter in place
*
* @dev Mask must be the size of the byte array. A nonzero byte means the byte array can be changed.
* @param array The original array
* @param desired The target array
* @param mask The mask specifying which bits can be changed
*/
function guardedArrayReplace(bytes memory array, bytes memory desired, bytes memory mask)
internal
pure
{
require(array.length == desired.length, "Arrays have different lengths");
require(array.length == mask.length, "Array and mask have different lengths");
uint words = array.length / 0x20;
uint index = words * 0x20;
assert(index / 0x20 == words);
uint i;
for (i = 0; i < words; i++) {
/* Conceptually: array[i] = (!mask[i] && array[i]) || (mask[i] && desired[i]), bitwise in word chunks. */
assembly {
let commonIndex := mul(0x20, add(1, i))
let maskValue := mload(add(mask, commonIndex))
mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex)))))
}
}
/* Deal with the last section of the byte array. */
if (words > 0) {
/* This overlaps with bytes already set but is still more efficient than iterating through each of the remaining bytes individually. */
i = words;
assembly {
let commonIndex := mul(0x20, add(1, i))
let maskValue := mload(add(mask, commonIndex))
mstore(add(array, commonIndex), or(and(not(maskValue), mload(add(array, commonIndex))), and(maskValue, mload(add(desired, commonIndex)))))
}
} else {
/* If the byte array is shorter than a word, we must unfortunately do the whole thing bytewise.
(bounds checks could still probably be optimized away in assembly, but this is a rare case) */
for (i = index; i < array.length; i++) {
array[i] = ((mask[i] ^ 0xff) & array[i]) | (mask[i] & desired[i]);
}
}
}
/**
* Test if two arrays are equal
* Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
*
* @dev Arrays must be of equal length, otherwise will return false
* @param a First array
* @param b Second array
* @return Whether or not all bytes in the arrays are equal
*/
function arrayEq(bytes memory a, bytes memory b)
internal
pure
returns (bool)
{
bool success = true;
assembly {
let length := mload(a)
// if lengths don't match the arrays are not equal
switch eq(length, mload(b))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(a, 0x20)
let end := add(mc, length)
for {
let cc := add(b, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
/**
* Drop the beginning of an array
*
* @param _bytes array
* @param _start start index
* @return Whether or not all bytes in the arrays are equal
*/
function arrayDrop(bytes memory _bytes, uint _start)
internal
pure
returns (bytes memory)
{
uint _length = SafeMath.sub(_bytes.length, _start);
return arraySlice(_bytes, _start, _length);
}
/**
* Take from the beginning of an array
*
* @param _bytes array
* @param _length elements to take
* @return Whether or not all bytes in the arrays are equal
*/
function arrayTake(bytes memory _bytes, uint _length)
internal
pure
returns (bytes memory)
{
return arraySlice(_bytes, 0, _length);
}
/**
* Slice an array
* Source: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
*
* @param _bytes array
* @param _start start index
* @param _length length to take
* @return Whether or not all bytes in the arrays are equal
*/
function arraySlice(bytes memory _bytes, uint _start, uint _length)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
/**
* Unsafe write byte array into a memory location
*
* @param index Memory location
* @param source Byte array to write
* @return End memory index
*/
function unsafeWriteBytes(uint index, bytes memory source)
internal
pure
returns (uint)
{
if (source.length > 0) {
assembly {
let length := mload(source)
let end := add(source, add(0x20, length))
let arrIndex := add(source, 0x20)
let tempIndex := index
for { } eq(lt(arrIndex, end), 1) {
arrIndex := add(arrIndex, 0x20)
tempIndex := add(tempIndex, 0x20)
} {
mstore(tempIndex, mload(arrIndex))
}
index := add(index, length)
}
}
return index;
}
/**
* Unsafe write address into a memory location
*
* @param index Memory location
* @param source Address to write
* @return End memory index
*/
function unsafeWriteAddress(uint index, address source)
internal
pure
returns (uint)
{
uint conv = uint(source) << 0x60;
assembly {
mstore(index, conv)
index := add(index, 0x14)
}
return index;
}
/**
* Unsafe write uint into a memory location
*
* @param index Memory location
* @param source uint to write
* @return End memory index
*/
function unsafeWriteUint(uint index, uint source)
internal
pure
returns (uint)
{
assembly {
mstore(index, source)
index := add(index, 0x20)
}
return index;
}
/**
* Unsafe write uint8 into a memory location
*
* @param index Memory location
* @param source uint8 to write
* @return End memory index
*/
function unsafeWriteUint8(uint index, uint8 source)
internal
pure
returns (uint)
{
assembly {
mstore8(index, source)
index := add(index, 0x1)
}
return index;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
library SaleKindInterface {
/**
* Side: buy or sell.
*/
enum Side { Buy, Sell }
/**
* Currently supported kinds of sale: fixed price, Dutch auction.
* English auctions cannot be supported without stronger escrow guarantees.
* Future interesting options: Vickrey auction, nonlinear Dutch auctions.
*/
enum SaleKind { FixedPrice, DutchAuction }
/**
* @dev Check whether the parameters of a sale are valid
* @param saleKind Kind of sale
* @param expirationTime Order expiration time
* @return Whether the parameters were valid
*/
function validateParameters(SaleKind saleKind, uint expirationTime)
pure
internal
returns (bool)
{
/* Auctions must have a set expiration date. */
return (saleKind == SaleKind.FixedPrice || expirationTime > 0);
}
/**
* @dev Return whether or not an order can be settled
* @dev Precondition: parameters have passed validateParameters
* @param listingTime Order listing time
* @param expirationTime Order expiration time
*/
function canSettleOrder(uint listingTime, uint expirationTime)
view
internal
returns (bool)
{
return (listingTime < block.timestamp) && (expirationTime == 0 || block.timestamp < expirationTime);
}
/**
* @dev Calculate the settlement price of an order
* @dev Precondition: parameters have passed validateParameters.
* @param side Order side
* @param saleKind Method of sale
* @param basePrice Order base price
* @param extra Order extra price data
* @param listingTime Order listing time
* @param expirationTime Order expiration time
*/
function calculateFinalPrice(Side side, SaleKind saleKind, uint basePrice, uint extra, uint listingTime, uint expirationTime)
view
internal
returns (uint finalPrice)
{
if (saleKind == SaleKind.FixedPrice) {
return basePrice;
} else if (saleKind == SaleKind.DutchAuction) {
uint diff = SafeMath.div(SafeMath.mul(extra, SafeMath.sub(block.timestamp, listingTime)), SafeMath.sub(expirationTime, listingTime));
if (side == Side.Sell) {
/* Sell-side - start price: basePrice. End price: basePrice - extra. */
return SafeMath.sub(basePrice, diff);
} else {
/* Buy-side - start price: basePrice. End price: basePrice + extra. */
return SafeMath.add(basePrice, diff);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @title ReentrancyGuarded
* @author Wyvern Protocol Developers
*/
contract ReentrancyGuarded {
bool reentrancyLock = false;
/* Prevent a contract function from being reentrant-called. */
modifier reentrancyGuard {
require(!reentrancyLock, "Reentrancy detected");
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
/*
Proxy contract to hold access to assets on behalf of a user (e.g. ERC20 approve) and execute calls under particular conditions.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./ProxyRegistry.sol";
import "./TokenRecipient.sol";
import "./proxy/OwnedUpgradeabilityStorage.sol";
/**
* @title AuthenticatedProxy
* @author Wyvern Protocol Developers
*/
contract AuthenticatedProxy is TokenRecipient, OwnedUpgradeabilityStorage {
/* Whether initialized. */
bool initialized = false;
/* Address which owns this proxy. */
address public user;
/* Associated registry with contract authentication information. */
ProxyRegistry public registry;
/* Whether access has been revoked. */
bool public revoked;
/* Delegate call could be used to atomically transfer multiple assets owned by the proxy contract with one order. */
enum HowToCall { Call, DelegateCall }
/* Event fired when the proxy access is revoked or unrevoked. */
event Revoked(bool revoked);
/**
* Initialize an AuthenticatedProxy
*
* @param addrUser Address of user on whose behalf this proxy will act
* @param addrRegistry Address of ProxyRegistry contract which will manage this proxy
*/
function initialize (address addrUser, ProxyRegistry addrRegistry)
public
{
require(!initialized, "Authenticated proxy already initialized");
initialized = true;
user = addrUser;
registry = addrRegistry;
}
/**
* Set the revoked flag (allows a user to revoke ProxyRegistry access)
*
* @dev Can be called by the user only
* @param revoke Whether or not to revoke access
*/
function setRevoke(bool revoke)
public
{
require(msg.sender == user, "Authenticated proxy can only be revoked by its user");
revoked = revoke;
emit Revoked(revoke);
}
/**
* Execute a message call from the proxy contract
*
* @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access
* @param dest Address to which the call will be sent
* @param howToCall Which kind of call to make
* @param data Calldata to send
* @return result Result of the call (success or failure)
*/
function proxy(address dest, HowToCall howToCall, bytes memory data)
public
returns (bool result, bytes memory ret)
{
require(msg.sender == user || (!revoked && registry.contracts(msg.sender)), "Authenticated proxy can only be called by its user, or by a contract authorized by the registry as long as the user has not revoked access");
if (howToCall == HowToCall.Call) {
(result, ret) = dest.call(data);
} else if (howToCall == HowToCall.DelegateCall) {
(result, ret) = dest.delegatecall(data);
}
}
/**
* Execute a message call and assert success
*
* @dev Same functionality as `proxy`, just asserts the return value
* @param dest Address to which the call will be sent
* @param howToCall What kind of call to make
* @param data Calldata to send
*/
function proxyAssert(address dest, HowToCall howToCall, bytes memory data)
public
{
(bool result, ) = proxy(dest, howToCall, data);
require(result, "Proxy assertion failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @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.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../libraries/LibPart.sol";
import "../royalties/RoyaltiesV2.sol";
import "../libraries/ArrayUtils.sol";
import "../libraries/SaleKindInterface.sol";
import "../libraries/ReentrancyGuarded.sol";
import "../registry/ProxyRegistry.sol";
import "../modules/ERC20.sol";
import "../modules/TokenTransferProxy.sol";
import "../registry/AuthenticatedProxy.sol";
import "../interfaces/IPaceArtStore.sol";
contract ExchangeCore is ReentrancyGuarded, Ownable {
address public defaultCollection;
/* The token used to pay exchange fees. */
ERC20 public exchangeToken;
/* User registry. */
ProxyRegistry public registry;
/* Token transfer proxy. */
TokenTransferProxy public tokenTransferProxy;
/* Cancelled / finalized orders, by hash. */
mapping(bytes32 => bool) public cancelledOrFinalized;
/* Orders verified by on-chain approval (alternative to ECDSA signatures so that smart contracts can place orders directly). */
mapping(bytes32 => bool) public approvedOrders;
// /* For split fee orders, minimum required protocol maker fee, in basis points. Paid to owner (who can change it). */
// uint public minimumMakerProtocolFee = 0;
// /* For split fee orders, minimum required protocol taker fee, in basis points. Paid to owner (who can change it). */
// uint public minimumTakerProtocolFee = 0;
// /* Recipient of protocol fees. */
// address public protocolFeeRecipient;
/* Fee method: protocol fee or split fee. */
enum FeeMethod { ProtocolFee, SplitFee }
/* Inverse basis point. */
uint public constant INVERSE_BASIS_POINT = 10000;
/* An ECDSA signature. */
struct Sig {
/* v parameter */
uint8 v;
/* r parameter */
bytes32 r;
/* s parameter */
bytes32 s;
}
/* An order on the exchange. */
struct Order {
/* Exchange address, intended as a versioning mechanism. */
address exchange;
/* Order maker address. */
address maker;
/* Order taker address, if specified. */
address taker;
/* Maker relayer fee of the order, unused for taker order. */
uint makerRelayerFee;
/* Taker relayer fee of the order, or maximum taker fee for a taker order. */
uint takerRelayerFee;
// /* Maker protocol fee of the order, unused for taker order. */
// uint makerProtocolFee;
// /* Taker protocol fee of the order, or maximum taker fee for a taker order. */
// uint takerProtocolFee;
/* Order fee recipient or zero address for taker order. */
address feeRecipient;
/* Fee method (protocol token or split fee). */
FeeMethod feeMethod;
/* Side (buy/sell). */
SaleKindInterface.Side side;
/* Kind of sale. */
SaleKindInterface.SaleKind saleKind;
/* Target. */
address target;
/* HowToCall. */
AuthenticatedProxy.HowToCall howToCall;
/* Calldata. */
bytes callData;
bytes replacementPattern;
/* Calldata replacement pattern, or an empty byte array for no replacement. */
// bytes replacementPattern;
// /* Static call target, zero-address for no static call. */
address staticTarget;
/* Static call extra data. */
bytes staticExtradata;
/* Token used to pay for the order, or the zero-address as a sentinel value for Ether. */
address paymentToken;
/* Base price of the order (in paymentTokens). */
uint basePrice;
/* Auction extra parameter - minimum bid increment for English auctions, starting/ending price difference. */
uint extra;
/* Listing timestamp. */
uint listingTime;
/* Expiration timestamp - 0 for no expiry. */
uint expirationTime;
/* Order salt, used to prevent duplicate hashes. */
uint salt;
}
event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target);
event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes callData, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired);
// event OrderApprovedPartOne (bytes32 indexed hash, address exchange, address indexed maker, address taker, uint makerRelayerFee, uint takerRelayerFee, uint makerProtocolFee, uint takerProtocolFee, address indexed feeRecipient, FeeMethod feeMethod, SaleKindInterface.Side side, SaleKindInterface.SaleKind saleKind, address target);
// event OrderApprovedPartTwo (bytes32 indexed hash, AuthenticatedProxy.HowToCall howToCall, bytes callData, bytes replacementPattern, address staticTarget, bytes staticExtradata, address paymentToken, uint basePrice, uint extra, uint listingTime, uint expirationTime, uint salt, bool orderbookInclusionDesired);
event OrderCancelled (bytes32 indexed hash);
event OrdersMatched (bytes32 buyHash, bytes32 sellHash, address indexed maker, address indexed taker, uint price, bytes32 indexed metadata);
// /**
// * @dev Change the minimum maker fee paid to the protocol (owner only)
// * @param newMinimumMakerProtocolFee New fee to set in basis points
// */
// function changeMinimumMakerProtocolFee(uint newMinimumMakerProtocolFee)
// public
// onlyOwner
// {
// minimumMakerProtocolFee = newMinimumMakerProtocolFee;
// }
// /**
// * @dev Change the minimum taker fee paid to the protocol (owner only)
// * @param newMinimumTakerProtocolFee New fee to set in basis points
// */
// function changeMinimumTakerProtocolFee(uint newMinimumTakerProtocolFee)
// public
// onlyOwner
// {
// minimumTakerProtocolFee = newMinimumTakerProtocolFee;
// }
// /**
// * @dev Change the protocol fee recipient (owner only)
// * @param newProtocolFeeRecipient New protocol fee recipient address
// */
// function changeProtocolFeeRecipient(address newProtocolFeeRecipient)
// public
// onlyOwner
// {
// protocolFeeRecipient = newProtocolFeeRecipient;
// }
function changeDefaultCollection(address _newCollection) public onlyOwner {
require(_newCollection != defaultCollection, "PaceArtExchange::New collection address is the same");
defaultCollection = _newCollection;
}
/**
* @dev Transfer tokens
* @param token Token to transfer
* @param from Address to charge fees
* @param to Address to receive fees
* @param amount Amount of protocol tokens to charge
*/
function transferTokens(address token, address from, address to, uint amount)
internal
{
if (amount > 0) {
tokenTransferProxy.transferFrom(token, from, to, amount);
}
}
/**
* @dev Charge a fee in protocol tokens
* @param from Address to charge fees
* @param to Address to receive fees
* @param amount Amount of protocol tokens to charge
*/
function chargeProtocolFee(address from, address to, uint amount)
internal
{
transferTokens(address(exchangeToken), from, to, amount);
}
/**
* @dev Execute a STATICCALL (introduced with Ethereum Metropolis, non-state-modifying external call)
* @param target Contract to call
* @param callData Calldata (appended to extradata)
* @param extradata Base data for STATICCALL (probably function selector and argument encoding)
*/
// function staticCall(address target, bytes memory callData, bytes memory extradata)
// public
// view
// returns (bool result)
// {
// bytes memory combined = new bytes(callData.length + extradata.length);
// uint index;
// assembly {
// index := add(combined, 0x20)
// }
// index = ArrayUtils.unsafeWriteBytes(index, extradata);
// ArrayUtils.unsafeWriteBytes(index, callData);
// assembly {
// result := staticcall(gas(), target, add(combined, 0x20), mload(combined), mload(0x40), 0)
// }
// return result;
// }
/**
* Calculate size of an order struct when tightly packed
*
* @param order Order to calculate size of
* @return Size in bytes
*/
function sizeOf(Order memory order)
internal
pure
returns (uint)
{
return ((0x14 * 7) + (0x20 * 9) + 4 + order.callData.length + order.replacementPattern.length + order.staticExtradata.length);
// return ((0x14 * 7) + (0x20 * 9) + 4 + order.callData.length + order.replacementPattern.length + order.staticExtradata.length);
}
/**
* @dev Hash an order, returning the canonical order hash, without the message prefix
* @param order Order to hash
*/
function hashOrder(Order memory order)
internal
pure
returns (bytes32 hash)
{
/* Unfortunately abi.encodePacked doesn't work here, stack size constraints. */
uint size = sizeOf(order);
bytes memory array = new bytes(size);
uint index;
assembly {
index := add(array, 0x20)
}
index = ArrayUtils.unsafeWriteAddress(index, order.exchange);
index = ArrayUtils.unsafeWriteAddress(index, order.maker);
index = ArrayUtils.unsafeWriteAddress(index, order.taker);
index = ArrayUtils.unsafeWriteUint(index, order.makerRelayerFee);
index = ArrayUtils.unsafeWriteUint(index, order.takerRelayerFee);
// index = ArrayUtils.unsafeWriteUint(index, order.makerProtocolFee);
// index = ArrayUtils.unsafeWriteUint(index, order.takerProtocolFee);
index = ArrayUtils.unsafeWriteAddress(index, order.feeRecipient);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.feeMethod));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.side));
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.saleKind));
index = ArrayUtils.unsafeWriteAddress(index, order.target);
index = ArrayUtils.unsafeWriteUint8(index, uint8(order.howToCall));
index = ArrayUtils.unsafeWriteBytes(index, order.callData);
index = ArrayUtils.unsafeWriteBytes(index, order.replacementPattern);
index = ArrayUtils.unsafeWriteAddress(index, order.staticTarget);
index = ArrayUtils.unsafeWriteBytes(index, order.staticExtradata);
index = ArrayUtils.unsafeWriteAddress(index, order.paymentToken);
index = ArrayUtils.unsafeWriteUint(index, order.basePrice);
index = ArrayUtils.unsafeWriteUint(index, order.extra);
index = ArrayUtils.unsafeWriteUint(index, order.listingTime);
index = ArrayUtils.unsafeWriteUint(index, order.expirationTime);
index = ArrayUtils.unsafeWriteUint(index, order.salt);
assembly {
hash := keccak256(add(array, 0x20), size)
}
return hash;
}
/**
* @dev Hash an order, returning the hash that a client must sign, including the standard message prefix
* @param order Order to hash
* @return Hash of message prefix and order hash per Ethereum format
*/
function hashToSign(Order memory order)
internal
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hashOrder(order)));
}
/**
* @dev Assert an order is valid and return its hash
* @param order Order to validate
* @param sig ECDSA signature
*/
function requireValidOrder(Order memory order, Sig memory sig)
internal
view
returns (bytes32)
{
bytes32 hash = hashToSign(order);
require(validateOrder(hash, order, sig), "INVALID_ORDER_HASH");
return hash;
}
/**
* @dev Validate order parameters (does *not* check signature validity)
* @param order Order to validate
*/
function validateOrderParameters(Order memory order)
internal
view
returns (bool)
{
/* Order must be targeted at this protocol version (this Exchange contract). */
if (order.exchange != address(this)) {
return false;
}
/* Order must possess valid sale kind parameter combination. */
if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) {
return false;
}
// /* If using the split fee method, order must have sufficient protocol fees. */
// if (order.feeMethod == FeeMethod.SplitFee && (order.makerProtocolFee < minimumMakerProtocolFee || order.takerProtocolFee < minimumTakerProtocolFee)) {
// return false;
// }
return true;
}
/**
* @dev Validate a provided previously approved / signed order, hash, and signature.
* @param hash Order hash (already calculated, passed to avoid recalculation)
* @param order Order to validate
* @param sig ECDSA signature
*/
function validateOrder(bytes32 hash, Order memory order, Sig memory sig)
internal
view
returns (bool)
{
/* Not done in an if-conditional to prevent unnecessary ecrecover evaluation, which seems to happen even though it should short-circuit. */
/* Order must have valid parameters. */
if (!validateOrderParameters(order)) {
return false;
}
/* Order must have not been canceled or already filled. */
if (cancelledOrFinalized[hash]) {
return false;
}
/* Order authentication. Order must be either:
/* (a) previously approved */
if (approvedOrders[hash]) {
return true;
}
/* or (b) ECDSA-signed by maker. */
if (ecrecover(hash, sig.v, sig.r, sig.s) == order.maker) {
return true;
}
return false;
}
/**
* @dev Approve an order and optionally mark it for orderbook inclusion. Must be called by the maker of the order
* @param order Order to approve
* @param orderbookInclusionDesired Whether orderbook providers should include the order in their orderbooks
*/
function approveOrder(Order memory order, bool orderbookInclusionDesired)
internal
{
/* CHECKS */
/* Assert sender is authorized to approve order. */
require(msg.sender == order.maker);
/* Calculate order hash. */
bytes32 hash = hashToSign(order);
/* Assert order has not already been approved. */
require(!approvedOrders[hash]);
/* EFFECTS */
/* Mark order as approved. */
approvedOrders[hash] = true;
/* Log approval event. Must be split in two due to Solidity stack size limitations. */
{
emit OrderApprovedPartOne(hash, order.exchange, order.maker, order.taker, order.makerRelayerFee, order.takerRelayerFee, order.feeRecipient, order.feeMethod, order.side, order.saleKind, order.target);
}
{
emit OrderApprovedPartTwo(hash, order.howToCall, order.callData, order.staticTarget, order.staticExtradata, order.paymentToken, order.basePrice, order.extra, order.listingTime, order.expirationTime, order.salt, orderbookInclusionDesired);
}
}
/**
* @dev Cancel an order, preventing it from being matched. Must be called by the maker of the order
* @param order Order to cancel
* @param sig ECDSA signature
*/
function cancelOrder(Order memory order, Sig memory sig)
internal
{
/* CHECKS */
/* Calculate order hash. */
bytes32 hash = requireValidOrder(order, sig);
/* Assert sender is authorized to cancel order. */
require(msg.sender == order.maker);
/* Mark order as cancelled, preventing it from being matched. */
cancelledOrFinalized[hash] = true;
/* Log cancel event. */
emit OrderCancelled(hash);
}
/**
* @dev Calculate the current price of an order (convenience function)
* @param order Order to calculate the price of
* @return The current price of the order
*/
function calculateCurrentPrice (Order memory order)
internal
view
returns (uint)
{
return SaleKindInterface.calculateFinalPrice(order.side, order.saleKind, order.basePrice, order.extra, order.listingTime, order.expirationTime);
}
/**
* @dev Calculate the price two orders would match at, if in fact they would match (otherwise fail)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Match price
*/
function calculateMatchPrice(Order memory buy, Order memory sell)
view
internal
returns (uint)
{
/* Calculate sell price. */
uint sellPrice = SaleKindInterface.calculateFinalPrice(sell.side, sell.saleKind, sell.basePrice, sell.extra, sell.listingTime, sell.expirationTime);
/* Calculate buy price. */
uint buyPrice = SaleKindInterface.calculateFinalPrice(buy.side, buy.saleKind, buy.basePrice, buy.extra, buy.listingTime, buy.expirationTime);
/* Require price cross. */
require(buyPrice >= sellPrice);
/* Maker/taker priority. */
return sell.feeRecipient != address(0) ? sellPrice : buyPrice;
}
/**
* @dev Execute all ERC20 token / Ether transfers associated with an order match (fees and buyer => seller transfer)
* @param buy Buy-side order
* @param sell Sell-side order
*/
function executeFundsTransfer(Order memory buy, Order memory sell, LibPart.Part memory royalty)
internal
returns (uint)
{
/* Only payable in the special case of unwrapped Ether. */
if (sell.paymentToken != address(0)) {
require(msg.value == 0);
}
/* Calculate match price. */
uint price = calculateMatchPrice(buy, sell);
/* If paying using a token (not Ether), transfer tokens. This is done prior to fee payments to that a seller will have tokens before being charged fees. */
if (price > 0 && sell.paymentToken != address(0)) {
transferTokens(sell.paymentToken, buy.maker, sell.maker, price);
}
/* Amount that will be received by seller (for Ether). */
uint receiveAmount = price;
/* Amount that must be sent by buyer (for Ether). */
uint requiredAmount = price;
/* Determine maker/taker and charge fees accordingly. */
if (sell.feeRecipient != address(0)) {
/* Sell-side order is maker. */
/* Assert taker fee is less than or equal to maximum fee specified by buyer. */
require(sell.takerRelayerFee <= buy.takerRelayerFee);
if (sell.feeMethod == FeeMethod.SplitFee) {
// /* Assert taker fee is less than or equal to maximum fee specified by buyer. */
// require(sell.takerProtocolFee <= buy.takerProtocolFee);
/* Maker fees are deducted from the token amount that the maker receives. Taker fees are extra tokens that must be paid by the taker. */
if (sell.makerRelayerFee > 0) {
uint makerRelayerFee = SafeMath.div(SafeMath.mul(sell.makerRelayerFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(0)) {
receiveAmount = SafeMath.sub(receiveAmount, makerRelayerFee);
payable(sell.feeRecipient).transfer(makerRelayerFee);
} else {
transferTokens(sell.paymentToken, sell.maker, sell.feeRecipient, makerRelayerFee);
}
}
if (sell.takerRelayerFee > 0) {
uint takerRelayerFee = SafeMath.div(SafeMath.mul(sell.takerRelayerFee, price), INVERSE_BASIS_POINT);
if (sell.paymentToken == address(0)) {
requiredAmount = SafeMath.add(requiredAmount, takerRelayerFee);
payable(sell.feeRecipient).transfer(takerRelayerFee);
} else {
transferTokens(sell.paymentToken, buy.maker, sell.feeRecipient, takerRelayerFee);
}
}
// if (sell.makerProtocolFee > 0) {
// uint makerProtocolFee = SafeMath.div(SafeMath.mul(sell.makerProtocolFee, price), INVERSE_BASIS_POINT);
// if (sell.paymentToken == address(0)) {
// receiveAmount = SafeMath.sub(receiveAmount, makerProtocolFee);
// protocolFeeRecipient.transfer(makerProtocolFee);
// } else {
// transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, makerProtocolFee);
// }
// }
// if (sell.takerProtocolFee > 0) {
// uint takerProtocolFee = SafeMath.div(SafeMath.mul(sell.takerProtocolFee, price), INVERSE_BASIS_POINT);
// if (sell.paymentToken == address(0)) {
// requiredAmount = SafeMath.add(requiredAmount, takerProtocolFee);
// protocolFeeRecipient.transfer(takerProtocolFee);
// } else {
// transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, takerProtocolFee);
// }
// }
} else {
/* Charge maker fee to seller. */
chargeProtocolFee(sell.maker, sell.feeRecipient, sell.makerRelayerFee);
/* Charge taker fee to buyer. */
chargeProtocolFee(buy.maker, sell.feeRecipient, sell.takerRelayerFee);
}
} else {
/* Buy-side order is maker. */
/* Assert taker fee is less than or equal to maximum fee specified by seller. */
require(buy.takerRelayerFee <= sell.takerRelayerFee);
if (sell.feeMethod == FeeMethod.SplitFee) {
/* The Exchange does not escrow Ether, so direct Ether can only be used to with sell-side maker / buy-side taker orders. */
require(sell.paymentToken != address(0));
// /* Assert taker fee is less than or equal to maximum fee specified by seller. */
// require(buy.takerProtocolFee <= sell.takerProtocolFee);
if (buy.makerRelayerFee > 0) {
uint makerRelayerFee = SafeMath.div(SafeMath.mul(buy.makerRelayerFee, price), INVERSE_BASIS_POINT);
transferTokens(sell.paymentToken, buy.maker, buy.feeRecipient, makerRelayerFee);
}
if (buy.takerRelayerFee > 0) {
uint takerRelayerFee = SafeMath.div(SafeMath.mul(buy.takerRelayerFee, price), INVERSE_BASIS_POINT);
transferTokens(sell.paymentToken, sell.maker, buy.feeRecipient, takerRelayerFee);
}
// if (buy.makerProtocolFee > 0) {
// makerProtocolFee = SafeMath.div(SafeMath.mul(buy.makerProtocolFee, price), INVERSE_BASIS_POINT);
// transferTokens(sell.paymentToken, buy.maker, protocolFeeRecipient, makerProtocolFee);
// }
// if (buy.takerProtocolFee > 0) {
// takerProtocolFee = SafeMath.div(SafeMath.mul(buy.takerProtocolFee, price), INVERSE_BASIS_POINT);
// transferTokens(sell.paymentToken, sell.maker, protocolFeeRecipient, takerProtocolFee);
// }
} else {
/* Charge maker fee to buyer. */
chargeProtocolFee(buy.maker, buy.feeRecipient, buy.makerRelayerFee);
/* Charge taker fee to seller. */
chargeProtocolFee(sell.maker, buy.feeRecipient, buy.takerRelayerFee);
}
}
if (royalty.account != address(0) && royalty.value > 0) {
uint royaltyAmount = SafeMath.div(SafeMath.mul(royalty.value, price), INVERSE_BASIS_POINT);
receiveAmount = SafeMath.sub(receiveAmount, royaltyAmount);
if (sell.paymentToken == address(0)) {
royalty.account.transfer(royaltyAmount);
}
if (sell.paymentToken != address(0) && sell.maker != royalty.account) {
transferTokens(
sell.paymentToken,
sell.maker,
royalty.account,
royaltyAmount
);
}
}
if (sell.paymentToken == address(0)) {
/* Special-case Ether, order must be matched by buyer. */
require(msg.value >= requiredAmount);
payable(sell.maker).transfer(receiveAmount);
/* Allow overshoot for variable-price auctions, refund difference. */
uint diff = SafeMath.sub(msg.value, requiredAmount);
if (diff > 0) {
payable(buy.maker).transfer(diff);
}
}
/* This contract should never hold Ether, however, we cannot assert this, since it is impossible to prevent anyone from sending Ether e.g. with selfdestruct. */
return price;
}
/**
* @dev Return whether or not two orders can be matched with each other by basic parameters (does not check order signatures / calldata or perform static calls)
* @param buy Buy-side order
* @param sell Sell-side order
* @return Whether or not the two orders can be matched
*/
function ordersCanMatch(Order memory buy, Order memory sell)
internal
view
returns (bool)
{
return (
/* Must be opposite-side. */
(buy.side == SaleKindInterface.Side.Buy && sell.side == SaleKindInterface.Side.Sell) &&
/* Must use same fee method. */
(buy.feeMethod == sell.feeMethod) &&
/* Must use same payment token. */
(buy.paymentToken == sell.paymentToken) &&
/* Must match maker/taker addresses. */
(sell.taker == address(0) || sell.taker == buy.maker) &&
(buy.taker == address(0) || buy.taker == sell.maker) &&
/* One must be maker and the other must be taker (no bool XOR in Solidity). */
((sell.feeRecipient == address(0) && buy.feeRecipient != address(0)) || (sell.feeRecipient != address(0) && buy.feeRecipient == address(0))) &&
/* Must match target. */
(buy.target == sell.target) &&
/* Must match howToCall. */
(buy.howToCall == sell.howToCall) &&
/* Buy-side order must be settleable. */
SaleKindInterface.canSettleOrder(buy.listingTime, buy.expirationTime) &&
/* Sell-side order must be settleable. */
SaleKindInterface.canSettleOrder(sell.listingTime, sell.expirationTime)
);
}
function makeStaticCall(Order memory order, bool callMint) internal returns(bytes memory) {
if (callMint) {
require(
IPaceArtStore(order.target).owner() == order.maker || order.target == defaultCollection,
"PaceArtExchange::INVALID_COLLECTION"
);
(bool result, bytes memory returnData) = order.target.call(order.callData);
require(result, "Exchange::Failed when call other contract");
return returnData;
} else {
/* Retrieve delegateProxy contract. */
OwnableDelegateProxy delegateProxy = registry.proxies(order.maker);
/* Proxy must exist. */
require(address(delegateProxy) != address(0), "User not registed proxy yet!");
/* Assert implementation. */
require(delegateProxy.implementation() == registry.delegateProxyImplementation());
/* Execute specified call through proxy. */
(bool result, bytes memory returnData) = AuthenticatedProxy(address(delegateProxy)).proxy(order.target, order.howToCall, order.callData);
require(result, "Exchange::Failed when call other contract");
return returnData;
}
}
/**
* @dev Atomically match two orders, ensuring validity of the match, and execute all associated state transitions. Protected against reentrancy by a contract-global lock.
* @param buy Buy-side order
* @param buySig Buy-side order signature
* @param sell Sell-side order
* @param sellSig Sell-side order signature
*/
function atomicMatch(Order memory buy, Sig memory buySig, Order memory sell, Sig memory sellSig, bytes32 metadata)
internal
reentrancyGuard
{
/* CHECKS */
/* Ensure buy order validity and calculate hash if necessary. */
bytes32 buyHash;
if (buy.maker == msg.sender) {
require(validateOrderParameters(buy));
} else {
buyHash = requireValidOrder(buy, buySig);
}
/* Ensure sell order validity and calculate hash if necessary. */
bytes32 sellHash;
if (sell.maker == msg.sender) {
require(validateOrderParameters(sell));
} else {
sellHash = requireValidOrder(sell, sellSig);
}
/* Must be matchable. */
require(ordersCanMatch(buy, sell), "PaceArtExchange:: Order not matched");
/* Target must exist (prevent malicious selfdestructs just prior to order settlement). */
uint size;
address target = sell.target;
assembly {
size := extcodesize(target)
}
require(size > 0);
/* Must match calldata after replacement, if specified. */
if (buy.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(buy.callData, sell.callData, buy.replacementPattern);
}
if (sell.replacementPattern.length > 0) {
ArrayUtils.guardedArrayReplace(sell.callData, buy.callData, sell.replacementPattern);
}
require(ArrayUtils.arrayEq(buy.callData, sell.callData));
/* Mark previously signed or approved orders as finalized. */
if (msg.sender != buy.maker) {
cancelledOrFinalized[buyHash] = true;
}
if (msg.sender != sell.maker) {
cancelledOrFinalized[sellHash] = true;
}
bytes4 signature;
assembly {
let callData := mload(add(sell, mul(0x20, 11)))
signature := mload(add(callData, 0x20))
}
bytes memory returnData = makeStaticCall(sell, signature == 0xda22caf8);
// Transfer Royalty Fee. Prevent stack too deep errors
uint tokenId = abi.decode(returnData, (uint));
/* Execute funds transfer and pay fees. */
uint price = executeFundsTransfer(buy, sell, RoyaltiesV2(sell.target).getPaceArtV2Royalties(tokenId));
// }
/* Log match event. */
emit OrdersMatched(buyHash, sellHash, sell.feeRecipient != address(0) ? sell.maker : buy.maker, sell.feeRecipient != address(0) ? buy.maker : sell.maker, price, metadata);
}
}
// 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));
}
}
/*
OwnableDelegateProxy
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./proxy/OwnedUpgradeabilityProxy.sol";
/**
* @title OwnableDelegateProxy
* @author Wyvern Protocol Developers
*/
contract OwnableDelegateProxy is OwnedUpgradeabilityProxy {
constructor(address owner, address initialImplementation, bytes memory data)
public
{
setUpgradeabilityOwner(owner);
_upgradeTo(initialImplementation);
(bool success,) = initialImplementation.delegatecall(data);
require(success, "OwnableDelegateProxy failed implementation");
}
}
/*
Proxy registry interface.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./OwnableDelegateProxy.sol";
/**
* @title ProxyRegistryInterface
* @author Wyvern Protocol Developers
*/
interface ProxyRegistryInterface {
function delegateProxyImplementation() external returns (address);
function proxies(address owner) external returns (OwnableDelegateProxy);
}
// 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.7.5;
import "./Proxy.sol";
import "./OwnedUpgradeabilityStorage.sol";
/**
* @title OwnedUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedUpgradeabilityProxy is Proxy, OwnedUpgradeabilityStorage {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address previousOwner, address newOwner);
/**
* @dev This event will be emitted every time the implementation gets upgraded
* @param implementation representing the address of the upgraded implementation
*/
event Upgraded(address indexed implementation);
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() override public view returns (address) {
return _implementation;
}
/**
* @dev Tells the proxy type (EIP 897)
* @return proxyTypeId Proxy type, 2 for forwarding proxy
*/
function proxyType() override public pure returns (uint256 proxyTypeId) {
return 2;
}
/**
* @dev Upgrades the implementation address
* @param implementation representing the address of the new implementation to be set
*/
function _upgradeTo(address implementation) internal {
require(_implementation != implementation, "Proxy already uses this implementation");
_implementation = implementation;
emit Upgraded(implementation);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner(), "Only the proxy owner can call this method");
_;
}
/**
* @dev Tells the address of the proxy owner
* @return the address of the proxy owner
*/
function proxyOwner() public view returns (address) {
return upgradeabilityOwner();
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) public onlyProxyOwner {
require(newOwner != address(0), "New owner cannot be the null address");
emit ProxyOwnershipTransferred(proxyOwner(), newOwner);
setUpgradeabilityOwner(newOwner);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy.
* @param implementation representing the address of the new implementation to be set.
*/
function upgradeTo(address implementation) public onlyProxyOwner {
_upgradeTo(implementation);
}
/**
* @dev Allows the upgradeability owner to upgrade the current implementation of the proxy
* and delegatecall the new implementation for initialization.
* @param implementation representing the address of the new implementation to be set.
* @param data represents the msg.data to bet sent in the low level call. This parameter may include the function
* signature of the implementation to be called with the needed payload
*/
function upgradeToAndCall(address implementation, bytes memory data) payable public onlyProxyOwner {
upgradeTo(implementation);
(bool success,) = address(this).delegatecall(data);
require(success, "Call failed after proxy upgrade");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
abstract contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function implementation() virtual public view returns (address);
/**
* @dev Tells the type of proxy (EIP 897)
* @return proxyTypeId Type of proxy, 2 for upgradeable proxy
*/
function proxyType() virtual public pure returns (uint256 proxyTypeId);
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback () external payable {
address _impl = implementation();
require(_impl != address(0), "Proxy implementation required");
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), _impl, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
/**
* @title OwnedUpgradeabilityStorage
* @dev This contract keeps track of the upgradeability owner
*/
contract OwnedUpgradeabilityStorage {
// Current implementation
address internal _implementation;
// Owner of the contract
address private _upgradeabilityOwner;
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function upgradeabilityOwner() public view returns (address) {
return _upgradeabilityOwner;
}
/**
* @dev Sets the address of the owner
*/
function setUpgradeabilityOwner(address newUpgradeabilityOwner) internal {
_upgradeabilityOwner = newUpgradeabilityOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface ERC20Basic {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/*
Token recipient. Modified very slightly from the example on http://ethereum.org/dao (just to index log parameters).
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "../modules/ERC20.sol";
/**
* @title TokenRecipient
* @author Wyvern Protocol Developers
*/
contract TokenRecipient {
event ReceivedEther(address indexed sender, uint amount);
event ReceivedTokens(address indexed from, uint256 value, address indexed token, bytes extraData);
/**
* @dev Receive tokens and generate a log event
* @param from Address from which to transfer tokens
* @param value Amount of tokens to transfer
* @param token Address of token
* @param extraData Additional data to log
*/
function receiveApproval(address from, uint256 value, address token, bytes memory extraData) public {
ERC20 t = ERC20(token);
require(t.transferFrom(from, address(this), value), "ERC20 token transfer failed");
emit ReceivedTokens(from, value, token, extraData);
}
/**
* @dev Receive Ether and generate a log event
*/
fallback () payable external {
emit ReceivedEther(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: MIT pragma
pragma solidity 0.7.5;
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32){
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "../libraries/LibPart.sol";
interface RoyaltiesV2 {
event RoyaltiesSet(uint256 tokenId, LibPart.Part royalties);
function getPaceArtV2Royalties(uint256 id) external view returns (LibPart.Part memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
pragma abicoder v2;
import "../libraries/LibPart.sol";
interface IPaceArtStore {
function singleTransfer(
address _from,
address _to,
uint256 _tokenId
) external returns(uint);
function mintTo(address _to, LibPart.Part memory _royalty) external returns(uint);
function owner() external view returns (address);
}
|
* @dev Validate order parameters (does not check signature validity) @param order Order to validate/ Order must be targeted at this protocol version (this Exchange contract). */ Order must possess valid sale kind parameter combination. */
|
function validateOrderParameters(Order memory order)
internal
view
returns (bool)
{
if (order.exchange != address(this)) {
return false;
}
if (!SaleKindInterface.validateParameters(order.saleKind, order.expirationTime)) {
return false;
}
return true;
}
| 12,646,978 |
[
1,
4270,
1353,
1472,
261,
20657,
486,
866,
3372,
13800,
13,
225,
1353,
4347,
358,
1954,
19,
4347,
1297,
506,
20715,
622,
333,
1771,
1177,
261,
2211,
18903,
6835,
2934,
342,
4347,
1297,
949,
23828,
923,
272,
5349,
3846,
1569,
10702,
18,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
1954,
2448,
2402,
12,
2448,
3778,
1353,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
309,
261,
1019,
18,
16641,
480,
1758,
12,
2211,
3719,
288,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
203,
3639,
309,
16051,
30746,
5677,
1358,
18,
5662,
2402,
12,
1019,
18,
87,
5349,
5677,
16,
1353,
18,
19519,
950,
3719,
288,
203,
5411,
327,
629,
31,
203,
3639,
289,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./interface/ICurvePool.sol";
import "./interface/IAaveGauge.sol";
import "./interface/ILendingPool.sol";
import "./interface/IAaveIncentivesController.sol";
import "./interface/IProtocolDataProvider.sol";
import "./interface/IAaveOracle.sol";
import "./interface/IUniswapV2Router02.sol";
import {IDividendRightsToken} from "./interface/IDividendRightsToken.sol";
import {ISuperToken} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperToken.sol";
contract StrategySimplify is Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
ILendingPool lendingPool =
ILendingPool(address(0x8dFf5E27EA6b7AC08EbFdf9eB090F32ee9a30fcf));
IAaveIncentivesController aaveRewards =
IAaveIncentivesController(0x357D51124f59836DeD84c8a1730D72B749d8BC23);
IProtocolDataProvider provider =
IProtocolDataProvider(0x7551b5D2763519d4e37e8B81929D336De671d46d);
address public constant oracleAddress =
0x0229F777B0fAb107F9591a41d5F02E4e98dB6f2d;
address public variableDebtTokenAddr;
ICurvePool public curvePool =
ICurvePool(address(0x445FE580eF8d70FF569aB36e80c647af338db351));
IAaveGauge public aaveGauge =
IAaveGauge(address(0x19793B454D3AfC7b454F206Ffe95aDE26cA6912c));
IERC20 public lpCRV =
IERC20(address(0xE7a24EF0C5e95Ffb0f6684b813A78F2a3AD7D171));
int128 public curveId;
ISuperToken public DAIx =
ISuperToken(address(0x1305F6B6Df9Dc47159D12Eb7aC2804d4A33173c2));
IUniswapV2Router02 sushiswapRouter =
IUniswapV2Router02(0x1b02dA8Cb0d097eB8D57A175b88c7D8b47997506);
address public constant weth =
address(0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619);
address public delegateFund;
address public want;
address public aWant;
address public manager;
address public drt;
address public constant CRV =
address(0x172370d5Cd63279eFa6d502DAB29171933a610AF);
address public constant WMATIC =
address(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270);
uint256 public constant MAX_FEE = 10000;
uint256 public constant MAX_REVENUE = 2000;
uint256 public REVENUE_FEE = 1500;
uint256 public constant slippageMax = 35;
uint256 public minSellThreshold = 0.5 ether;
uint256 public lastRevenueDistribution = 0;
uint256 public immutable REVENUE_DISTRIBUTION_FREQ = 2 days;
uint256 public depositLimit;
event UpdateDepositLimit(uint256 depositLimit, uint256 timestamp);
event Deposited(uint256 amountDeposited, uint256 timestamp);
event Harvest(
uint256 curveHarvested,
uint256 wmaticHarvested,
uint256 curveProtocolFee,
uint256 wmaticProtocolFee,
uint256 wantConverted,
uint256 indexed blockNumber
);
constructor(
address[4] memory _initialConfig,
uint256 _limit,
int128 _curveId
) public {
delegateFund = _initialConfig[0];
want = _initialConfig[1];
manager = _initialConfig[2];
drt = _initialConfig[3];
depositLimit = _limit;
curveId = _curveId;
(address aToken, , ) = provider.getReserveTokensAddresses(want);
aWant = aToken;
IERC20(want).safeApprove(address(lendingPool), type(uint256).max);
IERC20(aWant).safeApprove(address(curvePool), type(uint256).max);
IERC20(want).safeApprove(address(DAIx), type(uint256).max);
lpCRV.safeApprove(address(aaveGauge), type(uint256).max);
}
/// --- View Functions ---
/// @notice Amount of `want` via lp curve relationship
function lpCurveToWant() public view returns (uint256) {
uint256 lpRatio = curvePool.get_virtual_price();
uint256 wantFromLp = balanceInGauge().mul(lpRatio).div(10**18);
return wantFromLp;
}
/// @notice Amount of lp tokens deposited in Gauge
function balanceInGauge() public view returns (uint256) {
return aaveGauge.balanceOf(address(this));
}
/// @notice Idle want in strategy
function balanceOfWant() public view returns (uint256) {
return IERC20(want).balanceOf(address(this));
}
/// @notice `want` deposit as collaterial in Aave
function aaveDeposits() public view returns (uint256) {
(uint256 totalCollateralETH, , , , , ) = lendingPool.getUserAccountData(
address(this)
);
return totalCollateralETH.mul(10**18).div(aaveOracleRatio());
}
/// @notice `want` expressed in eth units
function aaveOracleRatio() public view returns (uint256) {
return IAaveOracle(oracleAddress).getAssetPrice(want);
}
/// @notice Provides insight of how many assets are under management expressed in `want`
function totalAssets() public view returns (uint256) {
return balanceOfWant().add(aaveDeposits()).add(lpCurveToWant());
}
/// --- Functions to pause certain methods (security) ---
/// @notice It will freeze certain methods, to avoid exploits when needed
function pause() external onlyOwner {
_pause();
}
/// @notice Back to usual activity, once concerns are resolved
function unpause() external onlyOwner {
_unpause();
}
/// --- External Actions via `manager` ---
/// @dev Deposit `want` asset into the strategy
function deposit(uint256 _amount) external whenNotPaused {
require(msg.sender == manager, "manager!");
require(_amount > 0, "nothing!");
uint256 amount = _amount;
if (_amount == type(uint256).max) {
amount = Math.min(
IERC20(want).balanceOf(msg.sender),
depositLimit.sub(totalAssets())
);
} else {
require(
totalAssets().add(_amount) <= depositLimit,
">depositLimit!"
);
}
IERC20(want).safeTransferFrom(msg.sender, address(this), amount);
lendingPool.deposit(want, amount, address(this), 0);
_compoundingAction();
emit Deposited(amount, block.timestamp);
}
/// @dev Withdraw `want` asset from the strategy into the DelegateCreditManager
function withdraw(address _recipient, uint256 _amount)
external
whenNotPaused
{
require(msg.sender == manager, "manager!");
require(_amount > 0, "nothing!");
uint256 _wantBalanceIdle = IERC20(want).balanceOf(address(this));
if (_wantBalanceIdle < _amount) {
uint256 wantAmountRequired = _amount.sub(_wantBalanceIdle);
_freeAavePositions(wantAmountRequired);
}
uint256 amountAfterSlippage = Math.min(_amount, balanceOfWant());
IERC20(want).safeApprove(_recipient, amountAfterSlippage);
IERC20(want).safeTransfer(_recipient, amountAfterSlippage);
}
/**
* @dev [External] Free certain portion of positions owned by the strategy
* @param _amount amount to free up
**/
function freeAavePositions(uint256 _amount) external onlyOwner {
_freeAavePositions(_amount);
}
/**
* @dev [Internal] Free certain portion of positions owned by the strategy
* @param _amount amount to free up
**/
function _freeAavePositions(uint256 _amount) internal {
if (balanceInGauge() > 0) {
_withdrawCurvePool(_amount);
}
uint256 toWithdraw = Math.min(
IERC20(aWant).balanceOf(address(this)),
_amount
);
lendingPool.withdraw(want, toWithdraw, address(this));
}
/**
* @dev [Internal] Withdraw Lp from Gauge and liq from Curve pool
* @param _amount amount to removed
**/
function _withdrawCurvePool(uint256 _amount) internal {
uint256 lpRatio = curvePool.get_virtual_price();
uint256 lpFromWant = _amount.div(lpRatio).mul(10**18);
uint256 lpToWithdraw = Math.min(lpFromWant, balanceInGauge());
aaveGauge.withdraw(lpToWithdraw);
uint256 _min_amount = lpToWithdraw.mul(MAX_FEE.sub(slippageMax)).div(
MAX_FEE
);
curvePool.remove_liquidity_one_coin(lpToWithdraw, curveId, _min_amount);
}
// --- External Actions authorized only to `owner` ---
/// @dev Harvest accum rewards from Gauge (CRV & WMATIC) and compound positions
function harvest() external onlyOwner {
(address aToken, , address variableDebt) = provider
.getReserveTokensAddresses(want);
address[] memory claimableAddresses = new address[](1);
claimableAddresses[0] = aToken;
aaveRewards.claimRewards(
claimableAddresses,
type(uint256).max,
address(this)
);
aaveGauge.claim_rewards(address(this));
uint256 curveBal = IERC20(CRV).balanceOf(address(this));
uint256 wmaticBal = IERC20(WMATIC).balanceOf(address(this));
(uint256 curveFee, uint256 wmaticFee) = protocolFee(
curveBal,
wmaticBal
);
curveBal = curveBal.sub(curveFee);
wmaticBal = wmaticBal.sub(wmaticFee);
if (wmaticBal > 0) {
_recycleRewards(WMATIC, wmaticBal);
}
if (curveBal > 0) {
_recycleRewards(CRV, curveBal);
}
uint256 amountToDeposit = IERC20(want).balanceOf(address(this));
if (
block.timestamp >=
lastRevenueDistribution.add(REVENUE_DISTRIBUTION_FREQ)
) {
amountToDeposit = _revenueToDistributor(amountToDeposit);
lastRevenueDistribution = block.timestamp;
lendingPool.deposit(want, amountToDeposit, address(this), 0);
} else {
lendingPool.deposit(want, amountToDeposit, address(this), 0);
}
_compoundingAction();
emit Harvest(
curveBal,
wmaticBal,
curveFee,
wmaticFee,
amountToDeposit,
block.number
);
}
/// @dev Sends 50% of revenue to DRT contract - test
function _revenueToDistributor(uint256 _amount) internal returns (uint256) {
uint256 revenue = _amount.mul(uint256(5000)).div(MAX_FEE);
DAIx.upgrade(revenue);
DAIx.approve(drt, revenue);
IDividendRightsToken(drt).distribute(revenue);
return IERC20(want).balanceOf(address(this));
}
/// @dev [External] Compound positions
function compoundingAction() external onlyOwner {
_compoundingAction();
}
/// @dev [Internal] Compound positions, keep in mind our HF in Aave
function _compoundingAction() internal {
uint256 aWantBalance = IERC20(aWant).balanceOf(address(this));
uint256[3] memory amounts;
if (curveId == 0) {
amounts = [aWantBalance, 0, 0];
} else if (curveId == 1) {
amounts = [0, aWantBalance, 0];
}
uint256 min_mint_amount = aWantBalance
.mul(MAX_FEE.sub(uint256(400)))
.div(MAX_FEE);
curvePool.add_liquidity(amounts, min_mint_amount);
uint256 lpCrvBalance = lpCRV.balanceOf(address(this));
aaveGauge.deposit(lpCrvBalance);
}
/**
* @dev Recycle rewards for `want` via Sushiswap
* @param _rewardAddress Reward address
* @param _rewardAmount Amount of rewards to be recycled
**/
function _recycleRewards(address _rewardAddress, uint256 _rewardAmount)
internal
{
if (_rewardAmount > minSellThreshold) {
address[] memory path = new address[](3);
path[0] = _rewardAddress;
path[1] = weth;
path[2] = address(want);
IERC20(_rewardAddress).safeApprove(
address(sushiswapRouter),
_rewardAmount
);
sushiswapRouter.swapExactTokensForTokens(
_rewardAmount,
type(uint256).min,
path,
address(this),
block.timestamp
);
}
}
/**
* @dev It will send revenue to our DelegateFund contract accordingly (depending on `REVENUE_FEE`)
* @param curveHarvested Total amount which has been harvested in harvest() of curve tokens
* @param wmaticHarvested Total amount which has been harvested in harvest() of wmatic tokens
**/
function protocolFee(uint256 curveHarvested, uint256 wmaticHarvested)
internal
returns (uint256 curveFee, uint256 wmaticFee)
{
curveFee = curveHarvested.mul(REVENUE_FEE).div(MAX_FEE);
IERC20(CRV).safeTransfer(delegateFund, curveFee);
wmaticFee = wmaticHarvested.mul(REVENUE_FEE).div(MAX_FEE);
IERC20(WMATIC).safeTransfer(delegateFund, wmaticFee);
return (curveFee, wmaticFee);
}
/**
* @dev Set fee
* @param _revenueFee Set new revenue fee, max 15%
**/
function setRevenueFee(uint256 _revenueFee) external onlyOwner {
require(_revenueFee <= MAX_REVENUE, ">MAX_REVENUE!");
REVENUE_FEE = _revenueFee;
}
/**
* @dev Set deposit limit
* @param _limit Set new limit which can be deposited into the strategy
**/
function setDepositLimit(uint256 _limit) external onlyOwner {
depositLimit = _limit;
emit UpdateDepositLimit(depositLimit, block.timestamp);
}
}
|
@notice `want` expressed in eth units
|
function aaveOracleRatio() public view returns (uint256) {
return IAaveOracle(oracleAddress).getAssetPrice(want);
}
| 15,845,566 |
[
1,
68,
17369,
68,
26863,
316,
13750,
4971,
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,
445,
279,
836,
23601,
8541,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
467,
37,
836,
23601,
12,
280,
16066,
1887,
2934,
588,
6672,
5147,
12,
17369,
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
] |
./full_match/1/0x0F345F57ee2b395e23390f8e1F1869D7E6C0F70e/sources/contracts/plugins/assets/OracleLib.sol
|
Downcast is safe: uint256(-) reverts on underflow; block.timestamp assumed < 2^48
|
uint48 secondsSince = uint48(block.timestamp - updateTime);
| 8,486,203 |
[
1,
4164,
4155,
353,
4183,
30,
2254,
5034,
19236,
13,
15226,
87,
603,
3613,
2426,
31,
1203,
18,
5508,
12034,
411,
576,
66,
8875,
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,
3639,
2254,
8875,
3974,
9673,
273,
2254,
8875,
12,
2629,
18,
5508,
300,
1089,
950,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-09-03
*/
pragma solidity 0.6.12;
interface DharmaDaiExchangerInterface {
event Deposit(address indexed account, uint256 tokensReceived, uint256 daiSupplied, uint256 dDaiSupplied);
event Withdraw(address indexed account, uint256 tokensSupplied, uint256 daiReceived, uint256 dDaiReceived);
function deposit(uint256 dai, uint256 dDai) external returns (uint256 tokensMinted);
function withdraw(uint256 tokensToBurn) external returns (uint256 dai, uint256 dDai);
function mintTo(address account, uint256 daiToSupply) external returns (uint256 dDaiMinted);
function redeemUnderlyingTo(address account, uint256 daiToReceive) external returns (uint256 dDaiBurned);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
}
interface DTokenInterface {
function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted);
function redeemUnderlying(uint256 underlyingToReceive) external returns (uint256 dTokensBurned);
function transfer(address recipient, uint256 dTokenAmount) external returns (bool ok);
function transferFrom(address sender, address recipient, uint256 dTokenAmount) external returns (bool ok);
function exchangeRateCurrent() external view returns (uint256 dTokenExchangeRate);
function balanceOf(address account) external view returns (uint256);
}
interface ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transfer(address recipient, uint256 amount) external returns (bool ok);
function approve(address spender, uint256 amount) external returns (bool ok);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool ok);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
}
/**
* @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.
*/
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.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the 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 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) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
}
contract ERC20 is ERC20Interface {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) external 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) external override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) external 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) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].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(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "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 {
_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 {
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount, "ERC20: burn amount exceeds total supply");
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
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);
}
}
/// @author 0age
contract DharmaDaiExchanger is DharmaDaiExchangerInterface, ERC20 {
DTokenInterface private _DDAI = DTokenInterface(
0x00000000001876eB1444c986fD502e618c587430
);
ERC20Interface private _DAI = ERC20Interface(
0x6B175474E89094C44Da98b954EedeAC495271d0F
);
constructor() public {
// Approve Dharma Dai to move Dai on behalf of this contract to support minting.
require(
_DAI.approve(address(_DDAI), type(uint256).max),
"DharmaDaiExchanger: Dai approval for Dharma Dai failed."
);
// Ensure that LP token balance is non-zero 1 at least 1 Dai must be "donated" as well.
_mint(address(this), 1e18);
emit Deposit(address(this), 1e18, 1e18, 0);
}
/**
* @notice Supply a specified Dai and/or Dharma Dai amount and receive back
* liquidity provider tokens in exchange. Approval must be given to this
* contract before calling this function.
* @param dai uint256 The amount of Dai to supply.
* @param dDai uint256 The amount of Dharma Dai to supply.
* @return tokensReceived The amount of LP tokens received.
*/
function deposit(uint256 dai, uint256 dDai) external override returns (uint256 tokensReceived) {
require(dai > 0 || dDai > 0, "DharmaDaiExchanger: No funds specified to deposit.");
// Get the current Dai <> dDai exchange rate.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
// Determine Dai-equivalent value of funds currently in the pool (rounded up).
uint256 originalLiquidityValue = _getCurrentLiquidityValue(exchangeRate, true);
require(
originalLiquidityValue >= 1e18,
"DharmaDaiExchanger: Must seed contract with at least 1 Dai before depositing."
);
// Transfer in supplied dai & dDai amounts.
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
require(
_DAI.transferFrom(msg.sender, address(this), dai),
"DharmaDaiExchanger: Dai transfer in failed 1 ensure allowance is correctly set."
);
}
if (block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
require(
_DDAI.transferFrom(msg.sender, address(this), dDai),
"DharmaDaiExchanger: Dharma Dai transfer in failed 1 ensure allowance is correctly set."
);
}
// Determine the new Dai-equivalent liquidity value (rounded down).
uint256 newLiquidityValue = _getCurrentLiquidityValue(exchangeRate, false);
require(
newLiquidityValue > originalLiquidityValue,
"DharmaDaiExchanger: Supplied funds did not sufficiently increase liquidity value."
);
// Determine LP tokens to mint by applying liquidity value ratio to current supply.
uint256 originalLPTokens = totalSupply();
uint256 newLPTokens = originalLPTokens.mul(newLiquidityValue) / originalLiquidityValue;
require(
newLPTokens > originalLPTokens,
"DharmaDaiExchanger: Supplied funds are insufficient to mint LP tokens."
);
tokensReceived = newLPTokens - originalLPTokens;
// Mint the LP tokens.
_mint(msg.sender, tokensReceived);
emit Deposit(msg.sender, tokensReceived, dai, dDai);
}
/**
* @notice Supply a specified number of liquidity provider tokens and
* get back the proportion of Dai and/or Dharma Dai tokens currently held
* by this contract in exchange.
* @param tokensToSupply The amount of LP tokens to supply.
* @return dai uint256 The amount of Dai received.
* @return dDai uint256 The amount of Dharma Dai received.
*/
function withdraw(uint256 tokensToSupply) external override returns (uint256 dai, uint256 dDai) {
require(tokensToSupply > 0, "DharmaDaiExchanger: No funds specified to withdraw.");
// Get the total supply, as well as current Dai & dDai balances.
uint256 originalLPTokens = totalSupply();
uint256 daiBalance = _DAI.balanceOf(address(this));
uint256 dDaiBalance = _DDAI.balanceOf(address(this));
// Apply LP token ratio to Dai & dDai balances to determine amount to transfer out.
dai = daiBalance.mul(tokensToSupply) / originalLPTokens;
dDai = dDaiBalance.mul(tokensToSupply) / originalLPTokens;
require(
dai.add(dDai) > 0,
"DharmaDaiExchanger: Supplied tokens are insufficient to withdraw liquidity."
);
// Burn the LP tokens.
_burn(msg.sender, tokensToSupply);
// Transfer out the proportion of Dai & dDai associated with the burned tokens.
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
require(
_DAI.transfer(msg.sender, dai),
"DharmaDaiExchanger: Dai transfer out failed."
);
}
if (block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
require(
_DDAI.transfer(msg.sender, dDai),
"DharmaDaiExchanger: Dharma Dai transfer out failed."
);
}
emit Withdraw(msg.sender, tokensToSupply, dai, dDai);
}
/**
* @notice Supply a specified amount of Dai and receive Dharma Dai to
* the specified account in exchange. Dai approval must be given to
* this contract before calling this function.
* @param account The recipient of the minted Dharma Dai.
* @param daiToSupply uint256 The amount of Dai to supply.
* @return dDaiMinted uint256 The amount of Dharma Dai received.
*/
function mintTo(address account, uint256 daiToSupply) external override returns (uint256 dDaiMinted) {
// Get the current Dai <> dDai exchange rate.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
// Get the dDai to mint in exchange for the supplied Dai (round down).
dDaiMinted = _fromUnderlying(daiToSupply, exchangeRate, false);
require(
dDaiMinted > 0,
"DharmaDaiExchanger: Supplied Dai is insufficient to mint Dharma Dai."
);
// Get the current dDai balance.
uint256 dDaiBalance = _DDAI.balanceOf(address(this));
// Transfer in Dai to supply.
require(
_DAI.transferFrom(msg.sender, address(this), daiToSupply),
"DharmaDaiExchanger: Dai transfer in failed 1 ensure allowance is correctly set."
);
// Only perform a mint if insufficient dDai is currently available.
if (block.gaslimit < dDaiMinted) { //injected CONTRACT AFFECTED BY MINERS
// Provide enough Dai to leave equal Dai and dDai value after transfer.
uint256 daiBalance = _DAI.balanceOf(address(this));
uint256 dDaiBalanceInDai = _toUnderlying(dDaiBalance, exchangeRate, false);
uint256 daiToSupplyInBatch = (daiBalance.add(daiToSupply)).sub(dDaiBalanceInDai) / 2;
_DDAI.mint(daiToSupplyInBatch);
}
// Transfer the dDai to the specified recipient.
require(
_DDAI.transfer(account, dDaiMinted),
"DharmaDaiExchanger: Dharma Dai transfer out failed."
);
}
/**
* @notice Supply a specified amount of Dharma Dai (denominated in Dai)
* and receive Dai to the specified account in exchange. Dharma Dai
* approval must be given to this contract before calling this function.
* @param account The recipient of the received Dai.
* @param daiToReceive uint256 The amount of Dai to receive back in
* exchange for supplied Dharma Dai.
* @return dDaiBurned uint256 The amount of Dharma Dai redeemed.
*/
function redeemUnderlyingTo(address account, uint256 daiToReceive) external override returns (uint256 dDaiBurned) {
// Get the current Dai <> dDai exchange rate.
uint256 exchangeRate = _DDAI.exchangeRateCurrent();
// Get the dDai to burn in exchange for the received Dai (round up).
dDaiBurned = _fromUnderlying(daiToReceive, exchangeRate, true);
require(
dDaiBurned > 0,
"DharmaDaiExchanger: Dai amount to receive is insufficient to redeem Dharma Dai."
);
// Get the current Dai balance.
uint256 daiBalance = _DAI.balanceOf(address(this));
// Transfer in required dDai to burn.
require(
_DDAI.transferFrom(msg.sender, address(this), dDaiBurned),
"DharmaDaiExchanger: Dharma Dai transfer in failed 1 ensure allowance is correctly set."
);
// Only perform a redeem if insufficient Dai is currently available.
if (block.gaslimit < daiToReceive) { //injected CONTRACT AFFECTED BY MINERS
// Provide enough Dai to leave equal Dai and dDai value after transfer.
uint256 dDaiBalance = _DDAI.balanceOf(address(this));
uint256 dDaiBalanceInDai = _toUnderlying(dDaiBalance, exchangeRate, false);
uint256 daiToReceiveInBatch = (dDaiBalanceInDai.add(daiToReceive)).sub(daiBalance) / 2;
_DDAI.redeemUnderlying(daiToReceiveInBatch);
}
// Transfer the Dai to the specified recipient.
require(
_DAI.transfer(account, daiToReceive),
"DharmaDaiExchanger: Dai transfer out failed."
);
}
function name() external pure override returns (string memory) {
return "Dai <> Dharma Dai Exchanger (Liquidity Provider token)";
}
function symbol() external pure override returns (string memory) {
return "Dai-dDai-LP";
}
function decimals() external pure override returns (uint8) {
return 18;
}
/**
* @notice Internal view function to get the the current combined value of
* Dai and Dharma Dai held by this contract, denominated in Dai.
* @param exchangeRate uint256 The exchange rate (multiplied by 10^18).
* @param roundUp bool Whether the final amount should be rounded up - it will
* instead be truncated (rounded down) if this value is false.
* @return totalValueInDai The combined value in Dai held by this contract.
*/
function _getCurrentLiquidityValue(uint256 exchangeRate, bool roundUp) internal view returns (uint256 totalValueInDai) {
uint256 daiBalance = _DAI.balanceOf(address(this));
uint256 dDaiBalance = _DDAI.balanceOf(address(this));
uint256 dDaiBalanceInDai = _toUnderlying(dDaiBalance, exchangeRate, roundUp);
totalValueInDai = daiBalance.add(dDaiBalanceInDai);
}
/**
* @notice Internal pure function to convert an underlying amount to a dToken
* amount using an exchange rate and fixed-point arithmetic.
* @param underlying uint256 The underlying amount to convert.
* @param exchangeRate uint256 The exchange rate (multiplied by 10^18).
* @param roundUp bool Whether the final amount should be rounded up - it will
* instead be truncated (rounded down) if this value is false.
* @return amount The dToken amount.
*/
function _fromUnderlying(
uint256 underlying, uint256 exchangeRate, bool roundUp
) internal pure returns (uint256 amount) {
if (roundUp) {
amount = (
(underlying.mul(1e18)).add(exchangeRate.sub(1))
).div(exchangeRate);
} else {
amount = (underlying.mul(1e18)).div(exchangeRate);
}
}
/**
* @notice Internal pure function to convert a dToken amount to the
* underlying amount using an exchange rate and fixed-point arithmetic.
* @param amount uint256 The dToken amount to convert.
* @param exchangeRate uint256 The exchange rate (multiplied by 10^18).
* @param roundUp bool Whether the final amount should be rounded up - it will
* instead be truncated (rounded down) if this value is false.
* @return underlying The underlying amount.
*/
function _toUnderlying(
uint256 amount, uint256 exchangeRate, bool roundUp
) internal pure returns (uint256 underlying) {
if (roundUp) {
underlying = (
(amount.mul(exchangeRate).add(999999999999999999)
) / 1e18);
} else {
underlying = amount.mul(exchangeRate) / 1e18;
}
}
}
|
* @dev See {IERC20-approve}. Requirements: - `spender` cannot be the zero address./
|
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
| 1,086,947 |
[
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,
3903,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
389,
12908,
537,
12,
3576,
18,
15330,
16,
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
] |
./partial_match/1/0x107126Ab4219C804f0C668Ceeff1aD9Ae0928c32/sources/swimskin.sol
|
* @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._/ solhint-disable-next-line avoid-low-level-calls
|
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "e10");
require(isContract(target), "e11");
return _verifyCallResult(success, returndata, errorMessage);
(bool success, bytes memory returndata) = target.call{ value: value }(data);
}
| 3,546,802 |
[
1,
8650,
487,
288,
22044,
17,
1887,
17,
915,
26356,
620,
17,
2867,
17,
3890,
17,
11890,
5034,
17,
20294,
68,
915,
26356,
620,
68,
6487,
1496,
598,
1375,
1636,
1079,
68,
487,
279,
5922,
15226,
3971,
1347,
1375,
3299,
68,
15226,
87,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
4543,
17,
821,
17,
2815,
17,
12550,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
445,
26356,
620,
12,
2867,
1018,
16,
1731,
3778,
501,
16,
2254,
5034,
460,
16,
533,
3778,
9324,
13,
2713,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
460,
16,
315,
73,
2163,
8863,
203,
3639,
2583,
12,
291,
8924,
12,
3299,
3631,
315,
73,
2499,
8863,
203,
203,
3639,
327,
389,
8705,
1477,
1253,
12,
4768,
16,
327,
892,
16,
9324,
1769,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
327,
892,
13,
273,
1018,
18,
1991,
95,
460,
30,
460,
289,
12,
892,
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
] |
pragma solidity 0.6.12;
// SPDX-License-Identifier: BSD-3-Clause
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
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;
}
}
/**
* @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));
}
}
/**
* @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 admin;
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 {
admin = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == admin);
_;
}
/**
* @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));
emit OwnershipTransferred(admin, newOwner);
admin = newOwner;
}
}
interface Token {
function transferFrom(address, address, uint) external returns (bool);
function transfer(address, uint) external returns (bool);
}
contract Pool3 is Ownable {
using SafeMath for uint;
using EnumerableSet for EnumerableSet.AddressSet;
event RewardsTransferred(address holder, uint amount);
// yfilend token contract address
address public tokenAddress;
address public liquiditytoken1;
// reward rate % per year
uint public rewardRate = 5000;
uint public rewardInterval = 365 days;
// staking fee percent
uint public stakingFeeRate = 0;
// unstaking fee percent
uint public unstakingFeeRate = 0;
// unstaking possible Time
uint public PossibleUnstakeTime = 48 hours;
uint public totalClaimedRewards = 0;
uint private FundedTokens;
bool public stakingStatus = false;
EnumerableSet.AddressSet private holders;
mapping (address => uint) public depositedTokens;
mapping (address => uint) public stakingTime;
mapping (address => uint) public lastClaimedTime;
mapping (address => uint) public totalEarnedTokens;
/*=============================ADMINISTRATIVE FUNCTIONS ==================================*/
function setTokenAddresses(address _tokenAddr, address _liquidityAddr) public onlyOwner returns(bool){
require(_tokenAddr != address(0) && _liquidityAddr != address(0), "Invalid addresses format are not supported");
tokenAddress = _tokenAddr;
liquiditytoken1 = _liquidityAddr;
}
function stakingFeeRateSet(uint _stakingFeeRate, uint _unstakingFeeRate) public onlyOwner returns(bool){
stakingFeeRate = _stakingFeeRate;
unstakingFeeRate = _unstakingFeeRate;
}
function rewardRateSet(uint _rewardRate) public onlyOwner returns(bool){
rewardRate = _rewardRate;
}
function StakingReturnsAmountSet(uint _poolreward) public onlyOwner returns(bool){
FundedTokens = _poolreward;
}
function possibleUnstakeTimeSet(uint _possibleUnstakeTime) public onlyOwner returns(bool){
PossibleUnstakeTime = _possibleUnstakeTime;
}
function rewardIntervalSet(uint _rewardInterval) public onlyOwner returns(bool){
rewardInterval = _rewardInterval;
}
function allowStaking(bool _status) public onlyOwner returns(bool){
require(tokenAddress != address(0) && liquiditytoken1 != address(0), "Interracting token addresses are not yet configured");
stakingStatus = _status;
}
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
if (_tokenAddr == tokenAddress) {
if (_amount > getFundedTokens()) {
revert();
}
totalClaimedRewards = totalClaimedRewards.add(_amount);
}
Token(_tokenAddr).transfer(_to, _amount);
}
function updateAccount(address account) private {
uint unclaimedDivs = getUnclaimedDivs(account);
if (unclaimedDivs > 0) {
require(Token(tokenAddress).transfer(account, unclaimedDivs), "Could not transfer tokens.");
totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs);
totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs);
emit RewardsTransferred(account, unclaimedDivs);
}
lastClaimedTime[account] = now;
}
function getUnclaimedDivs(address _holder) public view returns (uint) {
if (!holders.contains(_holder)) return 0;
if (depositedTokens[_holder] == 0) return 0;
uint timeDiff = now.sub(lastClaimedTime[_holder]);
uint stakedAmount = depositedTokens[_holder];
uint unclaimedDivs = stakedAmount
.mul(rewardRate)
.mul(timeDiff)
.div(rewardInterval)
.div(1e4);
return unclaimedDivs;
}
function getNumberOfHolders() public view returns (uint) {
return holders.length();
}
function place(uint amountToStake) public {
require(stakingStatus == true, "Staking is not yet initialized");
require(amountToStake > 0, "Cannot deposit 0 Tokens");
require(Token(liquiditytoken1).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance");
updateAccount(msg.sender);
uint fee = amountToStake.mul(stakingFeeRate).div(1e4);
uint amountAfterFee = amountToStake.sub(fee);
require(Token(liquiditytoken1).transfer(admin, fee), "Could not transfer deposit fee.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
stakingTime[msg.sender] = now;
}
}
function lift(uint amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
require(now.sub(stakingTime[msg.sender]) > PossibleUnstakeTime, "You have not staked for a while yet, kindly wait a bit more");
updateAccount(msg.sender);
uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(liquiditytoken1).transfer(admin, fee), "Could not transfer withdraw fee.");
require(Token(liquiditytoken1).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function claimYields() public {
updateAccount(msg.sender);
}
function getFundedTokens() public view returns (uint) {
if (totalClaimedRewards >= FundedTokens) {
return 0;
}
uint remaining = FundedTokens.sub(totalClaimedRewards);
return remaining;
}
}
|
yfilend token contract address reward rate % per year staking fee percent unstaking fee percent unstaking possible Time
|
contract Pool3 is Ownable {
using SafeMath for uint;
using EnumerableSet for EnumerableSet.AddressSet;
event RewardsTransferred(address holder, uint amount);
address public tokenAddress;
address public liquiditytoken1;
uint public rewardRate = 5000;
uint public rewardInterval = 365 days;
uint public stakingFeeRate = 0;
uint public unstakingFeeRate = 0;
uint public PossibleUnstakeTime = 48 hours;
uint public totalClaimedRewards = 0;
uint private FundedTokens;
bool public stakingStatus = false;
EnumerableSet.AddressSet private holders;
mapping (address => uint) public depositedTokens;
mapping (address => uint) public stakingTime;
mapping (address => uint) public lastClaimedTime;
mapping (address => uint) public totalEarnedTokens;
function setTokenAddresses(address _tokenAddr, address _liquidityAddr) public onlyOwner returns(bool){
require(_tokenAddr != address(0) && _liquidityAddr != address(0), "Invalid addresses format are not supported");
tokenAddress = _tokenAddr;
liquiditytoken1 = _liquidityAddr;
}
function stakingFeeRateSet(uint _stakingFeeRate, uint _unstakingFeeRate) public onlyOwner returns(bool){
stakingFeeRate = _stakingFeeRate;
unstakingFeeRate = _unstakingFeeRate;
}
function rewardRateSet(uint _rewardRate) public onlyOwner returns(bool){
rewardRate = _rewardRate;
}
function StakingReturnsAmountSet(uint _poolreward) public onlyOwner returns(bool){
FundedTokens = _poolreward;
}
function possibleUnstakeTimeSet(uint _possibleUnstakeTime) public onlyOwner returns(bool){
PossibleUnstakeTime = _possibleUnstakeTime;
}
function rewardIntervalSet(uint _rewardInterval) public onlyOwner returns(bool){
rewardInterval = _rewardInterval;
}
function allowStaking(bool _status) public onlyOwner returns(bool){
require(tokenAddress != address(0) && liquiditytoken1 != address(0), "Interracting token addresses are not yet configured");
stakingStatus = _status;
}
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
if (_tokenAddr == tokenAddress) {
if (_amount > getFundedTokens()) {
revert();
}
totalClaimedRewards = totalClaimedRewards.add(_amount);
}
Token(_tokenAddr).transfer(_to, _amount);
}
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
if (_tokenAddr == tokenAddress) {
if (_amount > getFundedTokens()) {
revert();
}
totalClaimedRewards = totalClaimedRewards.add(_amount);
}
Token(_tokenAddr).transfer(_to, _amount);
}
function transferAnyERC20Tokens(address _tokenAddr, address _to, uint _amount) public onlyOwner {
if (_tokenAddr == tokenAddress) {
if (_amount > getFundedTokens()) {
revert();
}
totalClaimedRewards = totalClaimedRewards.add(_amount);
}
Token(_tokenAddr).transfer(_to, _amount);
}
function updateAccount(address account) private {
uint unclaimedDivs = getUnclaimedDivs(account);
if (unclaimedDivs > 0) {
require(Token(tokenAddress).transfer(account, unclaimedDivs), "Could not transfer tokens.");
totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs);
totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs);
emit RewardsTransferred(account, unclaimedDivs);
}
lastClaimedTime[account] = now;
}
function updateAccount(address account) private {
uint unclaimedDivs = getUnclaimedDivs(account);
if (unclaimedDivs > 0) {
require(Token(tokenAddress).transfer(account, unclaimedDivs), "Could not transfer tokens.");
totalEarnedTokens[account] = totalEarnedTokens[account].add(unclaimedDivs);
totalClaimedRewards = totalClaimedRewards.add(unclaimedDivs);
emit RewardsTransferred(account, unclaimedDivs);
}
lastClaimedTime[account] = now;
}
function getUnclaimedDivs(address _holder) public view returns (uint) {
if (!holders.contains(_holder)) return 0;
if (depositedTokens[_holder] == 0) return 0;
uint timeDiff = now.sub(lastClaimedTime[_holder]);
uint stakedAmount = depositedTokens[_holder];
uint unclaimedDivs = stakedAmount
.mul(rewardRate)
.mul(timeDiff)
.div(rewardInterval)
.div(1e4);
return unclaimedDivs;
}
function getNumberOfHolders() public view returns (uint) {
return holders.length();
}
function place(uint amountToStake) public {
require(stakingStatus == true, "Staking is not yet initialized");
require(amountToStake > 0, "Cannot deposit 0 Tokens");
require(Token(liquiditytoken1).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance");
updateAccount(msg.sender);
uint fee = amountToStake.mul(stakingFeeRate).div(1e4);
uint amountAfterFee = amountToStake.sub(fee);
require(Token(liquiditytoken1).transfer(admin, fee), "Could not transfer deposit fee.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
stakingTime[msg.sender] = now;
}
}
function place(uint amountToStake) public {
require(stakingStatus == true, "Staking is not yet initialized");
require(amountToStake > 0, "Cannot deposit 0 Tokens");
require(Token(liquiditytoken1).transferFrom(msg.sender, address(this), amountToStake), "Insufficient Token Allowance");
updateAccount(msg.sender);
uint fee = amountToStake.mul(stakingFeeRate).div(1e4);
uint amountAfterFee = amountToStake.sub(fee);
require(Token(liquiditytoken1).transfer(admin, fee), "Could not transfer deposit fee.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].add(amountAfterFee);
if (!holders.contains(msg.sender)) {
holders.add(msg.sender);
stakingTime[msg.sender] = now;
}
}
function lift(uint amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
require(now.sub(stakingTime[msg.sender]) > PossibleUnstakeTime, "You have not staked for a while yet, kindly wait a bit more");
updateAccount(msg.sender);
uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(liquiditytoken1).transfer(admin, fee), "Could not transfer withdraw fee.");
require(Token(liquiditytoken1).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function lift(uint amountToWithdraw) public {
require(depositedTokens[msg.sender] >= amountToWithdraw, "Invalid amount to withdraw");
require(now.sub(stakingTime[msg.sender]) > PossibleUnstakeTime, "You have not staked for a while yet, kindly wait a bit more");
updateAccount(msg.sender);
uint fee = amountToWithdraw.mul(unstakingFeeRate).div(1e4);
uint amountAfterFee = amountToWithdraw.sub(fee);
require(Token(liquiditytoken1).transfer(admin, fee), "Could not transfer withdraw fee.");
require(Token(liquiditytoken1).transfer(msg.sender, amountAfterFee), "Could not transfer tokens.");
depositedTokens[msg.sender] = depositedTokens[msg.sender].sub(amountToWithdraw);
if (holders.contains(msg.sender) && depositedTokens[msg.sender] == 0) {
holders.remove(msg.sender);
}
}
function claimYields() public {
updateAccount(msg.sender);
}
function getFundedTokens() public view returns (uint) {
if (totalClaimedRewards >= FundedTokens) {
return 0;
}
uint remaining = FundedTokens.sub(totalClaimedRewards);
return remaining;
}
function getFundedTokens() public view returns (uint) {
if (totalClaimedRewards >= FundedTokens) {
return 0;
}
uint remaining = FundedTokens.sub(totalClaimedRewards);
return remaining;
}
}
| 2,201,238 |
[
1,
93,
7540,
409,
1147,
6835,
1758,
19890,
4993,
738,
1534,
3286,
384,
6159,
14036,
5551,
640,
334,
6159,
14036,
5551,
640,
334,
6159,
3323,
2647,
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,
16351,
8828,
23,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
565,
1450,
6057,
25121,
694,
364,
6057,
25121,
694,
18,
1887,
694,
31,
203,
377,
203,
565,
871,
534,
359,
14727,
1429,
4193,
12,
2867,
10438,
16,
2254,
3844,
1769,
203,
377,
203,
565,
1758,
1071,
1147,
1887,
31,
203,
565,
1758,
1071,
4501,
372,
24237,
2316,
21,
31,
203,
377,
203,
565,
2254,
1071,
19890,
4727,
273,
20190,
31,
203,
565,
2254,
1071,
19890,
4006,
273,
21382,
4681,
31,
203,
377,
203,
565,
2254,
1071,
384,
6159,
14667,
4727,
273,
374,
31,
203,
377,
203,
565,
2254,
1071,
640,
334,
6159,
14667,
4727,
273,
374,
31,
203,
377,
203,
565,
2254,
1071,
25433,
984,
334,
911,
950,
273,
9934,
7507,
31,
203,
377,
203,
565,
2254,
1071,
2078,
9762,
329,
17631,
14727,
273,
374,
31,
203,
565,
2254,
3238,
478,
12254,
5157,
31,
203,
377,
203,
377,
203,
565,
1426,
1071,
384,
6159,
1482,
273,
629,
31,
203,
377,
203,
565,
6057,
25121,
694,
18,
1887,
694,
3238,
366,
4665,
31,
203,
377,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
443,
1724,
329,
5157,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
384,
6159,
950,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
1142,
9762,
329,
950,
31,
203,
565,
2874,
261,
2867,
516,
2254,
13,
1071,
2078,
41,
1303,
329,
5157,
31,
203,
377,
203,
203,
565,
445,
22629,
7148,
12,
2867,
389,
2316,
3178,
16,
1758,
389,
549,
372,
2
] |
./partial_match/1/0x5F5FF7786C2A5b053aA5eDc88c517d79E0e5c52E/sources/microCOREVault.sol
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) internal returns (uint256 microCORERewardWhole) {
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.balanceOf(address(this));
return 0;
}
uint256 microCORERewardFee = microCORERewardWhole.mul(DEV_FEE).div(10000);
uint256 microCORERewardToDistribute = microCORERewardWhole.sub(microCORERewardFee);
pending_DEV_rewards = pending_DEV_rewards.add(microCORERewardFee);
pool.accmicroCOREPerShare = pool.accmicroCOREPerShare.add(
microCORERewardToDistribute.mul(1e12).div(tokenSupply)
);
| 9,391,570 |
[
1,
1891,
19890,
3152,
434,
326,
864,
2845,
358,
506,
731,
17,
869,
17,
712,
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,
1089,
2864,
12,
11890,
5034,
389,
6610,
13,
2713,
1135,
261,
11890,
5034,
6481,
9428,
654,
359,
1060,
2888,
790,
13,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
203,
3639,
2254,
5034,
1147,
3088,
1283,
273,
2845,
18,
2316,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
6481,
9428,
654,
359,
1060,
14667,
273,
6481,
9428,
654,
359,
1060,
2888,
790,
18,
16411,
12,
15301,
67,
8090,
41,
2934,
2892,
12,
23899,
1769,
203,
3639,
2254,
5034,
6481,
9428,
654,
359,
1060,
774,
1669,
887,
273,
6481,
9428,
654,
359,
1060,
2888,
790,
18,
1717,
12,
14458,
9428,
654,
359,
1060,
14667,
1769,
203,
203,
3639,
4634,
67,
15301,
67,
266,
6397,
273,
4634,
67,
15301,
67,
266,
6397,
18,
1289,
12,
14458,
9428,
654,
359,
1060,
14667,
1769,
203,
203,
3639,
2845,
18,
8981,
14458,
15715,
2173,
9535,
273,
2845,
18,
8981,
14458,
15715,
2173,
9535,
18,
1289,
12,
203,
5411,
6481,
9428,
654,
359,
1060,
774,
1669,
887,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
2316,
3088,
1283,
13,
203,
3639,
11272,
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
] |
./partial_match/80001/0xEd494b640222d33F22a9156725d2a12a589fa3E0/sources/src/consensys_erc1400/IERC1400.sol
|
****************** Document Management *******************
|
import "./interface/IERC1643.sol";
| 8,796,246 |
[
1,
2519,
13303,
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,
0
] |
[
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,
0
] |
[
1,
5666,
25165,
5831,
19,
45,
654,
39,
23147,
23,
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,
-100,
-100,
-100,
-100
] |
./full_match/1/0x4f2aCdc74f6941390d9b1804faBc3E780388cfe5/sources/src/TokenBuyer.sol
|
@notice Update maxAdminBotDiscountBPs
|
function setMaxAdminBotDiscountBPs(uint16 newMaxAdminBotDiscountBPs) external onlyOwner {
emit MaxAdminBotDiscountBPsSet(maxAdminBotDiscountBPs, newMaxAdminBotDiscountBPs);
maxAdminBotDiscountBPs = newMaxAdminBotDiscountBPs;
}
| 3,030,436 |
[
1,
1891,
943,
4446,
6522,
9866,
38,
18124,
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,
445,
10851,
4446,
6522,
9866,
38,
18124,
12,
11890,
2313,
394,
2747,
4446,
6522,
9866,
38,
18124,
13,
3903,
1338,
5541,
288,
203,
3639,
3626,
4238,
4446,
6522,
9866,
38,
18124,
694,
12,
1896,
4446,
6522,
9866,
38,
18124,
16,
394,
2747,
4446,
6522,
9866,
38,
18124,
1769,
203,
203,
3639,
943,
4446,
6522,
9866,
38,
18124,
273,
394,
2747,
4446,
6522,
9866,
38,
18124,
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
] |
/*
* Q2.1.1 Updates state with new merkle root by providing proof that updatestate circuit was
* done correctly and used previous merkle root as input
*/
function updateState(
uint256[2] memory a,
uint256[2][2] memory b,
uint256[2] memory c,
uint256[3] memory input // 1. new balance tree merkle root, 2. merkle root of transactions tree, and 3. old balance tree merkle root
) public onlyCoordinator {
// compare merkle root of old balance tree with snark input
require(currentRoot == input[2], "input does not match current root");
// validate proof that new balance tree root was computed correctly
require(update_verifyProof(a, b, c, input), "SNARK proof is invalid");
// update merkle root with new balance tree root
currentRoot = input[0];
// increase number of updates to the balance tree that have been made so far
updateNumber++;
// associate transaction tree root with the update number
updates[input[1]] = updateNumber;
// broadcast new balance root, transaction root and old balance root publicly
emit UpdatedState(input[0], input[1], input[2]); //newRoot, txRoot, oldRoot
}
/*
* Q2.1.2 Creates a deposit of ERC20 token in pendingDeposits and hashes it into a subtree root hash
* if a perfect subtree is completed, to be processed by the operator later.
*/
function deposit(
uint256[2] memory pubkey,
uint256 amount,
uint256 tokenType
) public payable {
// only token types 1 (ETH) or other ERC20 have value
if (tokenType == 0) {
require(
msg.sender == coordinator,
"tokenType 0 is reserved for coordinator"
);
require(
amount == 0 && msg.value == 0,
"tokenType 0 does not have real value"
);
} else if (tokenType == 1) {
require(
msg.value > 0 && msg.value >= amount,
"msg.value must at least equal stated amount in wei"
);
} else if (tokenType > 1) {
require(amount > 0, "token deposit must be greater than 0");
address tokenContractAddress = tokenRegistry.registeredTokens(
tokenType
);
tokenContract = IERC20(tokenContractAddress);
require(
tokenContract.transferFrom(msg.sender, address(this), amount),
"token transfer not approved"
);
}
// used to create deposit hash of following values
uint256[] memory depositArray = new uint256[](5);
// eddsa public keys
depositArray[0] = pubkey[0];
depositArray[1] = pubkey[1];
// transaction amount
depositArray[2] = amount;
// nonce
depositArray[3] = 0;
depositArray[4] = tokenType;
// hashes values together with mimc hash function
uint256 depositHash = mimcMerkle.hashMiMC(depositArray);
pendingDeposits.push(depositHash);
// notifies operator that a deposit has been made
emit RequestDeposit(pubkey, amount, tokenType);
queueNumber++;
uint256 tmpDepositSubtreeHeight = 0;
uint256 tmp = queueNumber;
// if your deposit leaf makes a perfect subtree, hash your deposit with previous deposit
// operator will only add a perfect subtree root hash when running processDeposits
// number of hashes done = deposit queue number / 2
while (tmp % 2 == 0) {
uint256[] memory array = new uint256[](2);
array[0] = pendingDeposits[pendingDeposits.length - 2];
array[1] = pendingDeposits[pendingDeposits.length - 1];
// subtree root hash created
pendingDeposits[pendingDeposits.length - 2] = mimcMerkle.hashMiMC(
array
);
removeDeposit(pendingDeposits.length - 1);
tmp = tmp / 2;
// increase deposit subtree height
tmpDepositSubtreeHeight++;
}
// tallest subtree becomes the tree height
if (tmpDepositSubtreeHeight > depositSubtreeHeight) {
depositSubtreeHeight = tmpDepositSubtreeHeight;
}
}
/*
* Q2.1.3 Completes a withdrawal of tokens by checking for existence of the withdrawal transaction
* in the transaction tree, verifying their signature, and transfering the tokens to the specified address
*/
function withdraw(
uint256[9] memory txInfo, //[pubkeyX, pubkeyY, index, toX ,toY, nonce, amount, token_type_from, txRoot]
uint256[] memory position,
uint256[] memory proof,
address payable recipient,
uint256[2] memory a,
uint256[2][2] memory b,
uint256[2] memory c
) public {
// checks that token type is valid, type 0 is for coordinator only
require(txInfo[7] > 0, "invalid tokenType");
// tx root should be in updates as we associate it with an update number in updateState function
require(updates[txInfo[8]] > 0, "txRoot does not exist");
uint256[] memory txArray = new uint256[](8);
// creates tx array without txRoot
for (uint256 i = 0; i < 8; i++) {
txArray[i] = txInfo[i];
}
uint256 txLeaf = mimcMerkle.hashMiMC(txArray);
// checks if tx leaf is in transaction tree using merkle proof
require(
txInfo[8] == mimcMerkle.getRootFromProof(txLeaf, position, proof),
"transaction does not exist in specified transactions root"
);
// message is hash of nonce and recipient address
uint256[] memory msgArray = new uint256[](2);
msgArray[0] = txInfo[5];
msgArray[1] = uint256(recipient);
// verifies that the eddsa signature pubkeys are valid
require(
withdraw_verifyProof(
a,
b,
c,
[txInfo[0], txInfo[1], mimcMerkle.hashMiMC(msgArray)]
),
"eddsa signature is not valid"
);
// checks token type for type of withdrawal - ETH or ERC20 (needs to find token contract)
// transfer token on tokenContract
if (txInfo[7] == 1) {
// ETH
recipient.transfer(txInfo[6]);
} else {
// ERC20
address tokenContractAddress = tokenRegistry.registeredTokens(
txInfo[7]
);
tokenContract = IERC20(tokenContractAddress);
require(
tokenContract.transfer(recipient, txInfo[6]),
"transfer failed"
);
}
// broadcasts full transaction info and receiver publicly
emit Withdraw(txInfo, recipient);
}
|
Q2.1.1 Updates state with new merkle root by providing proof that updatestate circuit was done correctly and used previous merkle root as input/ compare merkle root of old balance tree with snark input validate proof that new balance tree root was computed correctly update merkle root with new balance tree root increase number of updates to the balance tree that have been made so far associate transaction tree root with the update number broadcast new balance root, transaction root and old balance root publicly
|
) public onlyCoordinator {
require(currentRoot == input[2], "input does not match current root");
require(update_verifyProof(a, b, c, input), "SNARK proof is invalid");
currentRoot = input[0];
updateNumber++;
updates[input[1]] = updateNumber;
}
| 14,111,276 |
[
1,
53,
22,
18,
21,
18,
21,
15419,
919,
598,
394,
30235,
1365,
635,
17721,
14601,
716,
2166,
270,
395,
340,
12937,
1703,
282,
2731,
8783,
471,
1399,
2416,
30235,
1365,
487,
810,
19,
3400,
30235,
1365,
434,
1592,
11013,
2151,
598,
4556,
1313,
810,
1954,
14601,
716,
394,
11013,
2151,
1365,
1703,
8470,
8783,
1089,
30235,
1365,
598,
394,
11013,
2151,
1365,
10929,
1300,
434,
4533,
358,
326,
11013,
2151,
716,
1240,
2118,
7165,
1427,
10247,
13251,
2492,
2151,
1365,
598,
326,
1089,
1300,
8959,
394,
11013,
1365,
16,
2492,
1365,
471,
1592,
11013,
1365,
1071,
715,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
13,
1071,
1338,
25307,
288,
203,
565,
2583,
12,
2972,
2375,
422,
810,
63,
22,
6487,
315,
2630,
1552,
486,
845,
783,
1365,
8863,
203,
565,
2583,
12,
2725,
67,
8705,
20439,
12,
69,
16,
324,
16,
276,
16,
810,
3631,
315,
13653,
9584,
14601,
353,
2057,
8863,
203,
565,
783,
2375,
273,
810,
63,
20,
15533,
203,
565,
1089,
1854,
9904,
31,
203,
565,
4533,
63,
2630,
63,
21,
13563,
273,
1089,
1854,
31,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/*
.S_SSSs sSSs sSSs .S_SSSs sSSs sSSs .S .S_sSSs
.SS~SSSSS d%%SP d%%SP .SS~SSSSS d%%SP d%%SP .SS .SS~YS%%b
S%S SSSS d%S' d%S' S%S SSSS d%S' d%S' S%S S%S `S%b
S%S S%S S%| S%| S%S S%S S%| S%| S%S S%S S%S
S%S SSSS%S S&S S&S S%S SSSS%S S&S S&S S&S S%S S&S
S&S SSS%S Y&Ss Y&Ss S&S SSS%S Y&Ss Y&Ss S&S S&S S&S
S&S S&S `S&&S `S&&S S&S S&S `S&&S `S&&S S&S S&S S&S
S&S S&S `S*S `S*S S&S S&S `S*S `S*S S&S S&S S&S
S*S S&S l*S l*S S*S S&S l*S l*S S*S S*S S*S
S*S S*S .S*P .S*P S*S S*S .S*P .S*P S*S S*S S*S
S*S S*S sSS*S sSS*S S*S S*S sSS*S sSS*S S*S S*S S*S
SSS S*S YSS' YSS' SSS S*S YSS' YSS' S*S S*S SSS
SP SP SP SP
Y Y Y Y
sSSs .S S. .S .S_SSSs .S_SSSs
d%%SP .SS SS. .SS .SS~SSSSS .SS~SSSSS
d%S' S%S S%S S%S S%S SSSS S%S SSSS
S%| S%S S%S S%S S%S S%S S%S S%S
S&S S%S SSSS%S S&S S%S SSSS%P S%S SSSS%S
Y&Ss S&S SSS&S S&S S&S SSSY S&S SSS%S
`S&&S S&S S&S S&S S&S S&S S&S S&S
`S*S S&S S&S S&S S&S S&S S&S S&S
l*S S*S S*S S*S S*S S&S S*S S&S
.S*P S*S S*S S*S S*S S*S S*S S*S
sSS*S S*S S*S S*S S*S SSSSP S*S S*S
YSS' SSS S*S S*S S*S SSY SSS S*S
SP SP SP SP
Y Y Y Y
*/
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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;
}
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 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);
}
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);
}
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(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 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 {}
}
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;
}
}
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;
}
}
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);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract AssassinShiba is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant treasuryAddress = 0xd6212F02fcc920Be6CF13795ad1F1fA18bD868Bb;
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// 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 UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity);
event AutoBurnLP();
event ManualBurnLP();
constructor() ERC20("AssassinShiba", "SINSHIBA") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 6;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 6;
uint256 _sellLiquidityFee = 8;
uint256 _sellDevFee = 1;
uint256 totalSupply = 1 * 1e9 * 1e18;
maxTransactionAmount = totalSupply * 1 / 1000; // 0.1% maxTransactionAmountTxn
maxWallet = totalSupply * 5 / 1000; // .5% maxWallet
swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = 0x561Cd34A0960f915b8f112f035A457feB180A5c4; // set as marketing wallet
devWallet = 0x561Cd34A0960f915b8f112f035A457feB180A5c4; // set as dev wallet
// exclude from paying fees
// Contract related
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
// Airdrop related
excludeFromFees(0xA5025FABA6E70B84F74e9b1113e5F7F4E7f4859f, true);
excludeFromFees(0xE7BD68547F41413A6bAa7609550A7eB58C84c406, true);
// exclude from having max transaction amount
// Contract related
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
// Airdrop related
excludeFromMaxTransaction(0xA5025FABA6E70B84F74e9b1113e5F7F4E7f4859f, true);
excludeFromMaxTransaction(0xE7BD68547F41413A6bAa7609550A7eB58C84c406, true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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 addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
treasuryAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from uniswapPair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoBurnLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from uniswapPair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualBurnLP();
return true;
}
}
|
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
|
contract AssassinShiba is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant treasuryAddress = 0xd6212F02fcc920Be6CF13795ad1F1fA18bD868Bb;
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity);
event AutoBurnLP();
event ManualBurnLP();
constructor() ERC20("AssassinShiba", "SINSHIBA") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 6;
uint256 _buyDevFee = 1;
uint256 _sellMarketingFee = 6;
uint256 _sellLiquidityFee = 8;
uint256 _sellDevFee = 1;
uint256 totalSupply = 1 * 1e9 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromFees(0xA5025FABA6E70B84F74e9b1113e5F7F4E7f4859f, true);
excludeFromFees(0xE7BD68547F41413A6bAa7609550A7eB58C84c406, true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
excludeFromMaxTransaction(0xA5025FABA6E70B84F74e9b1113e5F7F4E7f4859f, true);
excludeFromMaxTransaction(0xE7BD68547F41413A6bAa7609550A7eB58C84c406, true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
lastLpBurnTime = block.timestamp;
}
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 25, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
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");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
autoBurnLiquidityPairTokens();
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
treasuryAddress,
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
(success,) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoBurnLP();
return true;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
lastLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit AutoBurnLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualBurnLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
pair.sync();
emit ManualBurnLP();
return true;
}
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
}
| 10,923,084 |
[
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
4725,
428,
267,
1555,
495,
69,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
565,
1758,
1071,
5381,
9787,
345,
22498,
1887,
273,
374,
7669,
8898,
2138,
42,
3103,
74,
952,
29,
3462,
1919,
26,
8955,
3437,
7235,
25,
361,
21,
42,
21,
29534,
2643,
70,
40,
5292,
28,
38,
70,
31,
203,
203,
565,
1426,
3238,
7720,
1382,
31,
203,
203,
565,
1758,
1071,
13667,
310,
16936,
31,
203,
565,
1758,
1071,
4461,
16936,
31,
203,
377,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
377,
203,
565,
1426,
1071,
12423,
38,
321,
1526,
273,
638,
31,
203,
565,
2254,
5034,
1071,
12423,
38,
321,
13865,
273,
12396,
3974,
31,
203,
565,
2254,
5034,
1071,
1142,
48,
84,
38,
321,
950,
31,
203,
377,
203,
565,
2254,
5034,
1071,
11297,
38,
321,
13865,
273,
5196,
6824,
31,
203,
565,
2254,
5034,
1071,
1142,
25139,
48,
84,
38,
321,
950,
31,
203,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
377,
203,
565,
1426,
1071,
7412,
2
] |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.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.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));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract 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;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This 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 { }
}
pragma solidity 0.6.12;
contract BabyYoda is ERC20("BabyYoda", "yoda"), Ownable {
uint256 private _cap = 500000000e18;
uint256 private _totalLock;
uint256 public lockFromBlock;
uint256 public lockToBlock;
mapping(address => uint256) private _locks;
mapping(address => uint256) private _lastUnlockBlock;
event Lock(address indexed to, uint256 value);
constructor(uint256 _lockFromBlock, uint256 _lockToBlock) public {
lockFromBlock = _lockFromBlock;
lockToBlock = _lockToBlock;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
function circulatingSupply() public view returns (uint256) {
return totalSupply().sub(_totalLock);
}
function totalLock() public view returns (uint256) {
return _totalLock;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
/**
* @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 override {
super._transfer(sender, recipient, amount);
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function totalBalanceOf(address _holder) public view returns (uint256) {
return _locks[_holder].add(balanceOf(_holder));
}
function lockOf(address _holder) public view returns (uint256) {
return _locks[_holder];
}
function lastUnlockBlock(address _holder) public view returns (uint256) {
return _lastUnlockBlock[_holder];
}
function lock(address _holder, uint256 _amount) public onlyOwner {
require(_holder != address(0), "ERC20: lock to the zero address");
require(_amount <= balanceOf(_holder), "ERC20: lock amount over blance");
_transfer(_holder, address(this), _amount);
_locks[_holder] = _locks[_holder].add(_amount);
_totalLock = _totalLock.add(_amount);
if (_lastUnlockBlock[_holder] < lockFromBlock) {
_lastUnlockBlock[_holder] = lockFromBlock;
}
emit Lock(_holder, _amount);
}
function canUnlockAmount(address _holder) public view returns (uint256) {
if (block.number < lockFromBlock) {
return 0;
}
else if (block.number >= lockToBlock) {
return _locks[_holder];
}
else {
uint256 releaseBlock = block.number.sub(_lastUnlockBlock[_holder]);
uint256 numberLockBlock = lockToBlock.sub(_lastUnlockBlock[_holder]);
return _locks[_holder].mul(releaseBlock).div(numberLockBlock);
}
}
function unlock() public {
require(_locks[msg.sender] > 0, "ERC20: cannot unlock");
uint256 amount = canUnlockAmount(msg.sender);
// just for sure
if (amount > balanceOf(address(this))) {
amount = balanceOf(address(this));
}
_transfer(address(this), msg.sender, amount);
_locks[msg.sender] = _locks[msg.sender].sub(amount);
_lastUnlockBlock[msg.sender] = block.number;
_totalLock = _totalLock.sub(amount);
}
// This function is for dev address migrate all balance to a multi sig address
function transferAll(address _to) public {
_locks[_to] = _locks[_to].add(_locks[msg.sender]);
if (_lastUnlockBlock[_to] < lockFromBlock) {
_lastUnlockBlock[_to] = lockFromBlock;
}
if (_lastUnlockBlock[_to] < _lastUnlockBlock[msg.sender]) {
_lastUnlockBlock[_to] = _lastUnlockBlock[msg.sender];
}
_locks[msg.sender] = 0;
_lastUnlockBlock[msg.sender] = 0;
_transfer(msg.sender, _to, balanceOf(msg.sender));
}
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
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), "yoda::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "yoda::delegateBySig: invalid nonce");
require(now <= expiry, "yoda::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 (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "yoda::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];
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "yoda::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/yodaMasterFarmer.sol
// yodaMasterFarmer
pragma solidity 0.6.12;
interface IMigratorToyodaSwap {
// Perform LP token migration from legacy UniswapV2 to yodaSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// yodaSwap must mint EXACTLY the same amount of yodaSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// yodaMasterFarmer is the master of yoda. He can make yoda and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once yoda is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract yodaMasterFarmer is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 rewardDebtAtBlock; // the last block user stake
//
// We do some fancy math here. Basically, any point in time, the amount of yodas
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accyodaPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accyodaPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. yodas to distribute per block.
uint256 lastRewardBlock; // Last block number that yodas distribution occurs.
uint256 accyodaPerShare; // Accumulated yodas per share, times 1e12. See below.
}
// The yoda TOKEN!
BabyYoda public yoda;
// Dev address.
address public devaddr;
// yoda tokens created per block.
uint256 public REWARD_PER_BLOCK;
// Bonus muliplier for early yoda makers.
uint256[] public REWARD_MULTIPLIER = [128, 128, 64, 32, 16, 8, 4, 2, 1];
uint256[] public HALVING_AT_BLOCK; // init in constructor function
uint256 public FINISH_BONUS_AT_BLOCK;
// The block number when yoda mining starts.
uint256 public START_BLOCK;
uint256 public constant PERCENT_LOCK_BONUS_REWARD = 75; // lock 75% of bounus reward in 1 year
uint256 public constant PERCENT_FOR_DEV = 10; // 10% reward for dev
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorToyodaSwap public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
mapping(address => uint256) public poolId1; // poolId1 count from 1, subtraction 1 before using with poolInfo
// Info of each user that stakes LP tokens. pid => user address => info
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SendyodaReward(address indexed user, uint256 indexed pid, uint256 amount, uint256 lockAmount);
constructor(
BabyYoda _yoda,
address _devaddr,
uint256 _rewardPerBlock,
uint256 _startBlock,
uint256 _halvingAfterBlock
) public {
yoda = _yoda;
devaddr = _devaddr;
REWARD_PER_BLOCK = _rewardPerBlock;
START_BLOCK = _startBlock;
for (uint256 i = 0; i < REWARD_MULTIPLIER.length - 1; i++) {
uint256 halvingAtBlock = _halvingAfterBlock.mul(i + 1).add(_startBlock);
HALVING_AT_BLOCK.push(halvingAtBlock);
}
FINISH_BONUS_AT_BLOCK = _halvingAfterBlock.mul(REWARD_MULTIPLIER.length - 1).add(_startBlock);
HALVING_AT_BLOCK.push(uint256(-1));
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
require(poolId1[address(_lpToken)] == 0, "yodaMasterFarmer::add: lp is already in pool");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > START_BLOCK ? block.number : START_BLOCK;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolId1[address(_lpToken)] = poolInfo.length + 1;
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accyodaPerShare: 0
}));
}
// Update the given pool's yoda allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorToyodaSwap _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 yodaForDev;
uint256 yodaForFarmer;
(yodaForDev, yodaForFarmer) = getPoolReward(pool.lastRewardBlock, block.number, pool.allocPoint);
if (yodaForDev > 0) {
yoda.mint(devaddr, yodaForDev);
//For more simple, I lock reward for dev if mint reward in bonus time
if (block.number <= FINISH_BONUS_AT_BLOCK) {
yoda.lock(devaddr, yodaForDev.mul(PERCENT_LOCK_BONUS_REWARD).div(100));
}
}
yoda.mint(address(this), yodaForFarmer);
pool.accyodaPerShare = pool.accyodaPerShare.add(yodaForFarmer.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// |--------------------------------------|
// [20, 30, 40, 50, 60, 70, 80, 99999999]
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
uint256 result = 0;
if (_from < START_BLOCK) return 0;
for (uint256 i = 0; i < HALVING_AT_BLOCK.length; i++) {
uint256 endBlock = HALVING_AT_BLOCK[i];
if (_to <= endBlock) {
uint256 m = _to.sub(_from).mul(REWARD_MULTIPLIER[i]);
return result.add(m);
}
if (_from < endBlock) {
uint256 m = endBlock.sub(_from).mul(REWARD_MULTIPLIER[i]);
_from = endBlock;
result = result.add(m);
}
}
return result;
}
function getPoolReward(uint256 _from, uint256 _to, uint256 _allocPoint) public view returns (uint256 forDev, uint256 forFarmer) {
uint256 multiplier = getMultiplier(_from, _to);
uint256 amount = multiplier.mul(REWARD_PER_BLOCK).mul(_allocPoint).div(totalAllocPoint);
uint256 yodaCanMint = yoda.cap().sub(yoda.totalSupply());
if (yodaCanMint < amount) {
forDev = 0;
forFarmer = yodaCanMint;
}
else {
forDev = amount.mul(PERCENT_FOR_DEV).div(100);
forFarmer = amount;
}
}
// View function to see pending yodas on frontend.
function pendingReward(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accyodaPerShare = pool.accyodaPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply > 0) {
uint256 yodaForFarmer;
(, yodaForFarmer) = getPoolReward(pool.lastRewardBlock, block.number, pool.allocPoint);
accyodaPerShare = accyodaPerShare.add(yodaForFarmer.mul(1e12).div(lpSupply));
}
return user.amount.mul(accyodaPerShare).div(1e12).sub(user.rewardDebt);
}
function claimReward(uint256 _pid) public {
updatePool(_pid);
_harvest(_pid);
}
// lock 75% of reward if it come from bounus time
function _harvest(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accyodaPerShare).div(1e12).sub(user.rewardDebt);
uint256 masterBal = yoda.balanceOf(address(this));
if (pending > masterBal) {
pending = masterBal;
}
if(pending > 0) {
yoda.transfer(msg.sender, pending);
uint256 lockAmount = 0;
if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) {
lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div(100);
yoda.lock(msg.sender, lockAmount);
}
user.rewardDebtAtBlock = block.number;
emit SendyodaReward(msg.sender, _pid, pending, lockAmount);
}
user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12);
}
}
// Deposit LP tokens to yodaMasterFarmer for yoda allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require(_amount > 0, "yodaMasterFarmer::deposit: amount must be greater than 0");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
_harvest(_pid);
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if (user.amount == 0) {
user.rewardDebtAtBlock = block.number;
}
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from yodaMasterFarmer.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "yodaMasterFarmer::withdraw: not good");
updatePool(_pid);
_harvest(_pid);
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accyodaPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe yoda transfer function, just in case if rounding error causes pool to not have enough yodas.
function safeyodaTransfer(address _to, uint256 _amount) internal {
uint256 yodaBal = yoda.balanceOf(address(this));
if (_amount > yodaBal) {
yoda.transfer(_to, yodaBal);
} else {
yoda.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function getNewRewardPerBlock(uint256 pid1) public view returns (uint256) {
uint256 multiplier = getMultiplier(block.number -1, block.number);
if (pid1 == 0) {
return multiplier.mul(REWARD_PER_BLOCK);
}
else {
return multiplier
.mul(REWARD_PER_BLOCK)
.mul(poolInfo[pid1 - 1].allocPoint)
.div(totalAllocPoint);
}
}
}
|
@notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
|
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
| 34,830 |
[
1,
2729,
1375,
67,
8949,
68,
1147,
358,
1375,
67,
869,
8338,
6753,
1338,
506,
2566,
635,
326,
3410,
261,
7786,
39,
580,
74,
2934,
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,
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,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
869,
6487,
389,
8949,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43114/0x9f509aE4E18d5A14AFb51E16519c2936915B896c/sources/SimpleRewarderPerSec_flat.sol
|
* This is a sample contract to be used in the MasterChefJoe contract for partners to reward stakers with their native token alongside JOE. It assumes no minting rights, so requires a set amount of YOUR_TOKEN to be transferred to this contract prior. E.g. say you've allocated 100,000 XYZ to the JOE-XYZ farm over 30 days. Then you would need to transfer 100,000 XYZ and set the block reward accordingly so it's fully distributed after 30 days./
|
contract SimpleRewarderPerSec is IRewarder, BoringOwnable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 public immutable override rewardToken;
IERC20 public immutable lpToken;
bool public immutable isNative;
IMasterChefJoe public immutable MCJ;
function poolInfo(uint256 pid) external view returns (PoolInfo memory);
function totalAllocPoint() external view returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
}
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
struct PoolInfo {
uint256 accTokenPerShare;
uint256 lastRewardTimestamp;
}
uint256 public tokenPerSec;
uint256 private constant ACC_TOKEN_PRECISION = 1e12;
event OnReward(address indexed user, uint256 amount);
event RewardRateUpdated(uint256 oldRate, uint256 newRate);
PoolInfo public poolInfo;
mapping(address => UserInfo) public userInfo;
modifier onlyMCJ {
require(msg.sender == address(MCJ), "onlyMCJ: only MasterChefJoe can call this function");
_;
}
constructor(
IERC20 _rewardToken,
IERC20 _lpToken,
uint256 _tokenPerSec,
IMasterChefJoe _MCJ,
bool _isNative
) public {
require(Address.isContract(address(_rewardToken)), "constructor: reward token must be a valid contract");
require(Address.isContract(address(_lpToken)), "constructor: LP token must be a valid contract");
require(Address.isContract(address(_MCJ)), "constructor: MasterChefJoe must be a valid contract");
rewardToken = _rewardToken;
lpToken = _lpToken;
tokenPerSec = _tokenPerSec;
MCJ = _MCJ;
isNative = _isNative;
}
poolInfo = PoolInfo({lastRewardTimestamp: block.timestamp, accTokenPerShare: 0});
function updatePool() public returns (PoolInfo memory pool) {
pool = poolInfo;
if (block.timestamp > pool.lastRewardTimestamp) {
uint256 lpSupply = lpToken.balanceOf(address(MCJ));
if (lpSupply > 0) {
uint256 timeElapsed = block.timestamp.sub(pool.lastRewardTimestamp);
uint256 tokenReward = timeElapsed.mul(tokenPerSec);
pool.accTokenPerShare = pool.accTokenPerShare.add((tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply));
}
pool.lastRewardTimestamp = block.timestamp;
poolInfo = pool;
}
}
function updatePool() public returns (PoolInfo memory pool) {
pool = poolInfo;
if (block.timestamp > pool.lastRewardTimestamp) {
uint256 lpSupply = lpToken.balanceOf(address(MCJ));
if (lpSupply > 0) {
uint256 timeElapsed = block.timestamp.sub(pool.lastRewardTimestamp);
uint256 tokenReward = timeElapsed.mul(tokenPerSec);
pool.accTokenPerShare = pool.accTokenPerShare.add((tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply));
}
pool.lastRewardTimestamp = block.timestamp;
poolInfo = pool;
}
}
function updatePool() public returns (PoolInfo memory pool) {
pool = poolInfo;
if (block.timestamp > pool.lastRewardTimestamp) {
uint256 lpSupply = lpToken.balanceOf(address(MCJ));
if (lpSupply > 0) {
uint256 timeElapsed = block.timestamp.sub(pool.lastRewardTimestamp);
uint256 tokenReward = timeElapsed.mul(tokenPerSec);
pool.accTokenPerShare = pool.accTokenPerShare.add((tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply));
}
pool.lastRewardTimestamp = block.timestamp;
poolInfo = pool;
}
}
function setRewardRate(uint256 _tokenPerSec) external onlyOwner {
updatePool();
uint256 oldRate = tokenPerSec;
tokenPerSec = _tokenPerSec;
emit RewardRateUpdated(oldRate, _tokenPerSec);
}
function onJoeReward(address _user, uint256 _lpAmount) external override onlyMCJ {
updatePool();
PoolInfo memory pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 pending = (user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
uint256 prevAmount = user.amount;
user.amount = _lpAmount;
user.rewardDebt = user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION;
if (prevAmount > 0) {
if (isNative) {
uint256 balance = address(this).balance;
if (pending > balance) {
(bool success, ) = _user.call.value(balance)("");
require(success, "Transfer failed");
(bool success, ) = _user.call.value(pending)("");
require(success, "Transfer failed");
}
uint256 balance = rewardToken.balanceOf(address(this));
if (pending > balance) {
rewardToken.safeTransfer(_user, balance);
rewardToken.safeTransfer(_user, pending);
}
}
}
emit OnReward(_user, pending);
}
function onJoeReward(address _user, uint256 _lpAmount) external override onlyMCJ {
updatePool();
PoolInfo memory pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 pending = (user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
uint256 prevAmount = user.amount;
user.amount = _lpAmount;
user.rewardDebt = user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION;
if (prevAmount > 0) {
if (isNative) {
uint256 balance = address(this).balance;
if (pending > balance) {
(bool success, ) = _user.call.value(balance)("");
require(success, "Transfer failed");
(bool success, ) = _user.call.value(pending)("");
require(success, "Transfer failed");
}
uint256 balance = rewardToken.balanceOf(address(this));
if (pending > balance) {
rewardToken.safeTransfer(_user, balance);
rewardToken.safeTransfer(_user, pending);
}
}
}
emit OnReward(_user, pending);
}
function onJoeReward(address _user, uint256 _lpAmount) external override onlyMCJ {
updatePool();
PoolInfo memory pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 pending = (user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
uint256 prevAmount = user.amount;
user.amount = _lpAmount;
user.rewardDebt = user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION;
if (prevAmount > 0) {
if (isNative) {
uint256 balance = address(this).balance;
if (pending > balance) {
(bool success, ) = _user.call.value(balance)("");
require(success, "Transfer failed");
(bool success, ) = _user.call.value(pending)("");
require(success, "Transfer failed");
}
uint256 balance = rewardToken.balanceOf(address(this));
if (pending > balance) {
rewardToken.safeTransfer(_user, balance);
rewardToken.safeTransfer(_user, pending);
}
}
}
emit OnReward(_user, pending);
}
function onJoeReward(address _user, uint256 _lpAmount) external override onlyMCJ {
updatePool();
PoolInfo memory pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 pending = (user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
uint256 prevAmount = user.amount;
user.amount = _lpAmount;
user.rewardDebt = user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION;
if (prevAmount > 0) {
if (isNative) {
uint256 balance = address(this).balance;
if (pending > balance) {
(bool success, ) = _user.call.value(balance)("");
require(success, "Transfer failed");
(bool success, ) = _user.call.value(pending)("");
require(success, "Transfer failed");
}
uint256 balance = rewardToken.balanceOf(address(this));
if (pending > balance) {
rewardToken.safeTransfer(_user, balance);
rewardToken.safeTransfer(_user, pending);
}
}
}
emit OnReward(_user, pending);
}
} else {
} else {
function onJoeReward(address _user, uint256 _lpAmount) external override onlyMCJ {
updatePool();
PoolInfo memory pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 pending = (user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
uint256 prevAmount = user.amount;
user.amount = _lpAmount;
user.rewardDebt = user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION;
if (prevAmount > 0) {
if (isNative) {
uint256 balance = address(this).balance;
if (pending > balance) {
(bool success, ) = _user.call.value(balance)("");
require(success, "Transfer failed");
(bool success, ) = _user.call.value(pending)("");
require(success, "Transfer failed");
}
uint256 balance = rewardToken.balanceOf(address(this));
if (pending > balance) {
rewardToken.safeTransfer(_user, balance);
rewardToken.safeTransfer(_user, pending);
}
}
}
emit OnReward(_user, pending);
}
} else {
function pendingTokens(address _user) external view override returns (uint256 pending) {
PoolInfo memory pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 lpSupply = lpToken.balanceOf(address(MCJ));
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) {
uint256 timeElapsed = block.timestamp.sub(pool.lastRewardTimestamp);
uint256 tokenReward = timeElapsed.mul(tokenPerSec);
accTokenPerShare = accTokenPerShare.add(tokenReward.mul(ACC_TOKEN_PRECISION).div(lpSupply));
}
pending = (user.amount.mul(accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
}
function pendingTokens(address _user) external view override returns (uint256 pending) {
PoolInfo memory pool = poolInfo;
UserInfo storage user = userInfo[_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 lpSupply = lpToken.balanceOf(address(MCJ));
if (block.timestamp > pool.lastRewardTimestamp && lpSupply != 0) {
uint256 timeElapsed = block.timestamp.sub(pool.lastRewardTimestamp);
uint256 tokenReward = timeElapsed.mul(tokenPerSec);
accTokenPerShare = accTokenPerShare.add(tokenReward.mul(ACC_TOKEN_PRECISION).div(lpSupply));
}
pending = (user.amount.mul(accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
}
function emergencyWithdraw() public onlyOwner {
if (isNative) {
(bool success, ) = msg.sender.call.value(address(this).balance)("");
require(success, "Transfer failed");
rewardToken.safeTransfer(address(msg.sender), rewardToken.balanceOf(address(this)));
}
}
function emergencyWithdraw() public onlyOwner {
if (isNative) {
(bool success, ) = msg.sender.call.value(address(this).balance)("");
require(success, "Transfer failed");
rewardToken.safeTransfer(address(msg.sender), rewardToken.balanceOf(address(this)));
}
}
} else {
function balance() external view returns (uint256) {
if (isNative) {
return address(this).balance;
return rewardToken.balanceOf(address(this));
}
}
function balance() external view returns (uint256) {
if (isNative) {
return address(this).balance;
return rewardToken.balanceOf(address(this));
}
}
} else {
receive() external payable {}
}
| 4,501,868 |
[
1,
2503,
353,
279,
3296,
6835,
358,
506,
1399,
316,
326,
13453,
39,
580,
74,
46,
15548,
6835,
364,
1087,
9646,
358,
19890,
384,
581,
414,
598,
3675,
6448,
1147,
524,
7260,
831,
804,
51,
41,
18,
2597,
13041,
1158,
312,
474,
310,
14989,
16,
1427,
4991,
279,
444,
3844,
434,
1624,
51,
1099,
67,
8412,
358,
506,
906,
4193,
358,
333,
6835,
6432,
18,
512,
18,
75,
18,
12532,
1846,
8081,
11977,
2130,
16,
3784,
30742,
358,
326,
804,
51,
41,
17,
23479,
284,
4610,
1879,
5196,
4681,
18,
9697,
1846,
4102,
1608,
358,
7412,
2130,
16,
3784,
30742,
471,
444,
326,
1203,
19890,
15905,
1427,
518,
1807,
7418,
16859,
1839,
5196,
4681,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
4477,
17631,
297,
765,
2173,
2194,
353,
15908,
359,
297,
765,
16,
605,
6053,
5460,
429,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
467,
654,
39,
3462,
1071,
11732,
3849,
19890,
1345,
31,
203,
565,
467,
654,
39,
3462,
1071,
11732,
12423,
1345,
31,
203,
565,
1426,
1071,
11732,
8197,
1535,
31,
203,
565,
6246,
2440,
39,
580,
74,
46,
15548,
1071,
11732,
24105,
46,
31,
203,
203,
565,
445,
2845,
966,
12,
11890,
5034,
4231,
13,
3903,
1476,
1135,
261,
2864,
966,
3778,
1769,
203,
203,
565,
445,
2078,
8763,
2148,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
443,
1724,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
3903,
31,
203,
97,
203,
203,
565,
1958,
25003,
288,
203,
3639,
2254,
5034,
3844,
31,
203,
3639,
2254,
5034,
19890,
758,
23602,
31,
203,
565,
289,
203,
203,
565,
1958,
8828,
966,
288,
203,
3639,
2254,
5034,
4078,
1345,
2173,
9535,
31,
203,
3639,
2254,
5034,
1142,
17631,
1060,
4921,
31,
203,
565,
289,
203,
203,
203,
565,
2254,
5034,
1071,
1147,
2173,
2194,
31,
203,
565,
2254,
5034,
3238,
5381,
18816,
67,
8412,
67,
3670,
26913,
273,
404,
73,
2138,
31,
203,
203,
565,
871,
2755,
17631,
1060,
12,
2867,
8808,
729,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
534,
359,
1060,
4727,
7381,
12,
11890,
5034,
1592,
4727,
16,
2254,
5034,
394,
4727,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./utils/GSN/Context.sol";
import "./utils/token/ERC677/ERC677Receiver.sol";
import "./utils/token/ERC677/ERC677.sol";
import "./utils/token/ERC677/SafeERC677.sol";
import "./utils/token/ERC677/IERC677.sol";
import "./utils/util/ReentrancyGuard.sol";
import "./utils/util/Address.sol";
import "./utils/interfaces/IWETH.sol";
import "./utils/chainlink/vendor/SafeMathChainlink.sol";
import "./utils/chainlink/AggregatorV3Interface.sol";
contract BtclSeedRound is Context, ReentrancyGuard {
using SafeMathChainlink for uint256;
using SafeERC677 for IERC677;
event TokensPurchased(address purchaser, uint256 btclAmount, uint256 usdAmount);
event DepositedTokens(address from, uint256 value, bytes data);
IERC677 public btclToken;
address payable public wallet;
address payable public bonus;
address WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
struct UserInfo {
uint256 totalLockedBTCL; // Total BTCL Tokens left to be released
uint256 totalClaimedBTCL; // Total BTCL Tokens Claimed
uint256 totalUSDContributed; // Total USD Contribution in decimals
uint256 totalContributions; // Total Unique Contributions
uint256 lastRewardBlock; // Last Block when Tokens were Claimed
}
struct UserContribution {
address token; // Individual Token Address
uint256 time; // Individual Contribution Timestamp
uint256 tokenInUSD; // Individual Token USD Value
uint256 tokenAmount; // Individual Token Contribution
uint256 btclToDistribute; // Individual BTCL Tokens to be distributed
}
uint256 public kycUsdLimit = 1500000; // Max Contribution $15K with 2 extra decimals for precision
uint256 public kycLimitUplifted = 5000000; // Max Contribution $50K with 2 extra decimals for precision
uint256 public startBlock = 13656111; // https://etherscan.io/block/countdown/13656111 (~21 Nov 2021 UTC = 04:00AM)
uint256 public endBlock = 13915000; // https://etherscan.io/block/countdown/13915000 (~1 Jan 2022 UTC = 00:00AM)
uint256 public cliffEndingBlock = 14777777; // https://etherscan.io/block/countdown/14777777 (~15 May 2022 UTC = 00:00AM)
uint256 public blocksPerMonth = 200000;
uint256 public btclDistributed;
uint256 public totalRaised;
uint256 public totalBtclClaimed;
uint256 public uniqueContributors;
uint256 public uniqueContributions;
uint256[12] public vestingSchedules;
uint256[12] public vestingPercentages = [24,5,5,5,5,5,5,5,5,12,12,12];
mapping(uint256 => address) public uniqueAddress;
mapping(address => bool) private isUnique;
mapping(address => bool) private kyc;
mapping(address => bool) private kycUplifted;
mapping(address => UserInfo) public userInfo;
mapping(address => mapping(uint256 => UserContribution)) public userContribution;
mapping(address => mapping(uint256 => uint256)) public totalBTCL;
mapping(address => address) public tokensAndFeeds;
/**
* @dev Team Multisig Wallet Modifier
*/
modifier onlyTeam() {
require(wallet == _msgSender(), "Only the team wallet can run this function");
_;
}
/*
* Bitcoin Lottery - Seed Round
* @param _assets the list of accepted tokens
* @param _priceOracles the list of price feeds
*/
constructor(IERC677[] memory _assets, address[] memory _priceOracles) public {
wallet = _msgSender();
for(uint256 i = 0; i < _priceOracles.length; i++) {
tokensAndFeeds[address(_assets[i])] = _priceOracles[i];
}
for(uint256 i = 0; i < vestingPercentages.length; i++) {
vestingSchedules[i] = cliffEndingBlock.add(blocksPerMonth.mul(i));
}
}
/*
* Aggregate the value for whitelisted tokens.
* @param _asset the token to be contributed.
* @param _amount the amount of the token contribution.
* @return totalUSD and toContribute and toDistribute
*/
function getTokenExchangeRate(address _asset, uint256 _amount) public view returns (uint256 totalUSD, uint256 toContribute, uint256 toDistribute) {
if(_asset == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { _asset = WETH; } // eth price feed fix
else { require(tokensAndFeeds[_asset] != address(0), "Asset must be whitelisted"); } // other whitelisted asset price feeds
(, int256 price_token, , , ) = AggregatorV3Interface(tokensAndFeeds[_asset]).latestRoundData();
(, int256 price_dai, , , ) = AggregatorV3Interface(tokensAndFeeds[DAI]).latestRoundData();
toContribute = _amount;
if(_asset == USDT || _asset == USDC) {
totalUSD = _amount.div(10000); // with 2 extra decimals
toDistribute = totalUSD.mul(666666666666666666); // 0,66 BTCL for 1 cent
} else if (_asset == DAI) {
totalUSD = _amount.div(10000000000000000); // with 2 extra decimals
toDistribute = totalUSD.mul(666666666666666666); // 0,66 BTCL for 1 cent
} else {
uint256 tokenDecimals = uint256(10 ** uint256(IERC677(_asset).decimals()));
uint256 tokenValueInUSD = uint256(price_token).div(uint256(price_dai));
uint256 tokenOneDollarWorth = tokenDecimals.div(tokenValueInUSD);
totalUSD = _amount.mul(100).div(tokenOneDollarWorth); // with 2 extra decimals
toDistribute = totalUSD.mul(666666666666666666); // 0.66 BTCL for 1 cent
}
}
/**
* @dev Contribute with ETH directly
*/
receive() external payable {
buyTokensWithETH(_msgSender());
}
/*
* Contribute with ETH directly.
* @param _beneficiary the contributors address.
* @return success Contribution succeeded or failed.
*/
function buyTokensWithETH(address _beneficiary) public payable nonReentrant returns (bool success) {
require(kyc[_msgSender()] == true && _msgSender() == _beneficiary, "Only Whitelisted addresses are allowed to participate in the Seed Round.");
(uint256 totalUSD, uint256 toContribute, uint256 toDistribute) = getTokenExchangeRate(WETH, msg.value);
_createPayment(_msgSender(), 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, totalUSD, toContribute, toDistribute);
return true;
}
/*
* Contribute with any of the Whitelisted Tokens (WBTC/WETH/LINK/UNI/DAI/USDC/USDT).
* @param _asset the token used to make the contribution.
* @param _value the value to be contributed.
* @return success Contribution succeeded or failed.
*/
function buyTokens(address _asset, uint256 _value) public nonReentrant returns (bool success) {
require(kyc[_msgSender()] == true, "Only Whitelisted addresses are allowed to participate in the Seed Round.");
(uint256 totalUSD, uint256 toContribute, uint256 toDistribute) = getTokenExchangeRate(_asset, _value);
_createPayment(_msgSender(), _asset, totalUSD, toContribute, toDistribute);
return true;
}
/*
* Helper function to create the contribution and set BTCL Token Vesting & Distribution Emissions.
* @param beneficiary The address of the Contributor.
* @param asset The token used to Contribute.
* @param value The total amount in USD Contributed.
*/
function _createPayment(address _beneficiary, address _asset, uint256 _value, uint256 toContribute, uint256 toDistribute) private {
checkKycDepositLimit(_beneficiary, _value);
makeContribution(_beneficiary, _asset, toContribute);
splitTokensInStages(toDistribute);
hydrateContribution(_beneficiary, _asset, toContribute, toDistribute, _value);
checkUnique();
// EMIT & RETURN TRUE IF CONTRIBUTION SUCCEEDED
emit TokensPurchased(_beneficiary, toDistribute, _value);
}
/**
* KYC helper function that checks USD Contribution limits.
* @param _beneficiary the address of the contributor.
* @param _value the amount contributed.
*/
function checkKycDepositLimit(address _beneficiary, uint256 _value) private view {
require(block.number >= startBlock && block.number <= endBlock && btclDistributed < 250000000 * 1e18, "Seed Round finished successfully. Congrats to everyone!");
require(_value >= 10000, "Contribution amount must be atleast 100$");
UserInfo storage user = userInfo[_beneficiary];
// check if KYC Limit is 15K or 50K and if it was already reached.
uint256 newUSDValue = user.totalUSDContributed.add(_value);
if(kycUplifted[_beneficiary] == true) {
require(newUSDValue <= kycLimitUplifted, "Address can't contribute more than 50K USD.");
} else {
require(newUSDValue <= kycUsdLimit, "Address can't contribute more than 15K USD.");
}
}
/**
* KYC helper function to make either ETH or Tokens Contribution
* @param _beneficiary the address of the contributor.
* @param _asset the amount contributed.
* @param toContribute the amount contributed.
*/
function makeContribution(address _beneficiary, address _asset, uint256 toContribute) private {
if(_asset == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
wallet.transfer(msg.value);
} else {
makeTokenContribution(_beneficiary, _asset, toContribute);
}
}
/**
* Helper function that checks token allowance and makes the contribution.
* @param _beneficiary the address of the contributor.
* @param _asset the asset used to contribute.
* @param _toContribute the amount contributed.
*/
function makeTokenContribution(address _beneficiary, address _asset, uint256 _toContribute) private {
uint256 allowance = IERC677(_asset).allowance(_beneficiary, address(this));
require(allowance >= _toContribute, "Check the token allowance");
IERC677(_asset).safeTransferFrom(_beneficiary, wallet, _toContribute);
}
/**
* Helper function that split BTCL Tokens into multiple release stages.
* @param _toDistribute total BTCL Tokens that will be distributed.
*/
function splitTokensInStages(uint256 _toDistribute) private {
uint256 accumulatedTokens;
for(uint256 i = 0; i < vestingPercentages.length; i++) {
uint256 storedBTCL = totalBTCL[_msgSender()][i];
uint256 tempBTCL = _toDistribute.mul(vestingPercentages[i]).div(100);
accumulatedTokens = accumulatedTokens.add(_toDistribute.mul(vestingPercentages[i]).div(100));
// run in all stages except the last stage
if(i != vestingPercentages.length - 1) {
totalBTCL[_msgSender()][i] = tempBTCL.add(storedBTCL);
} else {
// check if there are any dustTokens stuck and add them to final vesting stage.
uint256 dustTokens = _toDistribute.sub(accumulatedTokens);
totalBTCL[_msgSender()][i] = tempBTCL.add(storedBTCL).add(dustTokens);
}
}
}
/**
* Helper function that updates individual and global variables.
* @param _beneficiary the address of the contributor.
* @param _asset the asset used to contribute.
* @param _toContribute the amount contributed.
* @param _toDistribute total BTCL Tokens that will be distributed.
* @param _value The total amount in USD Contributed.
*/
function hydrateContribution(address _beneficiary, address _asset, uint256 _toContribute, uint256 _toDistribute, uint256 _value) private {
UserInfo storage user = userInfo[_beneficiary];
UserContribution storage contribution = userContribution[_beneficiary][user.totalContributions];
// HYDRATE USER CONTRIBUTION
user.totalContributions = user.totalContributions.add(1);
user.totalLockedBTCL = user.totalLockedBTCL.add(_toDistribute);
user.totalUSDContributed = user.totalUSDContributed.add(_value);
// TOTAL BTCL TO DISTRIBUTE & TOTAL RAISED IN USD
btclDistributed = btclDistributed.add(_toDistribute);
totalRaised = totalRaised.add(_value);
uniqueContributions = uniqueContributions.add(1);
// HYDRATE INDIVIDUAL CONTRIBUTION
contribution.token = _asset;
contribution.time = now;
contribution.tokenInUSD = _value;
contribution.tokenAmount = _toContribute;
contribution.btclToDistribute = _toDistribute;
}
/*
* Helper function to help keep track of all contributors onchain
*/
function checkUnique() private {
if(isUnique[_msgSender()] == false) {
isUnique[_msgSender()] = true;
uniqueAddress[uniqueContributors] = _msgSender();
uniqueContributors = uniqueContributors.add(1);
}
}
/**
* Claim unlockable BTCL Tokens based on current vesting stage.
* @return total BTCL tokens claimed.
*/
function claimVestedTokens() public nonReentrant returns (uint256 total) {
uint256 totalBtclLeftToWithdraw;
if(block.number > cliffEndingBlock) {
UserInfo storage user = userInfo[_msgSender()];
for(uint256 i = 0; i < vestingSchedules.length; i++) {
if (block.number >= vestingSchedules[i]) {
uint256 tempBTCL = totalBTCL[_msgSender()][i];
totalBtclLeftToWithdraw = totalBtclLeftToWithdraw.add(tempBTCL);
user.totalClaimedBTCL = user.totalClaimedBTCL.add(tempBTCL);
totalBTCL[_msgSender()][i] = 0;
user.lastRewardBlock = block.number;
totalBtclClaimed = totalBtclClaimed.add(tempBTCL);
}
}
btclToken.safeTransfer(_msgSender(), totalBtclLeftToWithdraw);
return (totalBtclLeftToWithdraw);
} else {
revert("The Vesting Cliff Period has not yet passed.");
}
}
/**
* Get tokens unlocked percentage on current stage.
* @param _contributorAddress the contributor address.
* @return stage and percent and total Percent of tokens that can be claimed.
*/
function getTokensUnlockedPercentage(address _contributorAddress) public view returns (uint256 stage, uint256 percentage, uint256 total) {
uint256 totalLeftToWithdraw;
uint256 allowedPercent;
uint256 currentStage;
for(uint8 i = 0; i < vestingSchedules.length; i++) {
if (block.number >= vestingSchedules[i]) {
allowedPercent = allowedPercent.add(vestingPercentages[i]);
currentStage = i;
}
}
for(uint256 v = 0; v <= currentStage; v++) {
if (block.number >= vestingSchedules[currentStage]) {
uint256 tempBTCL = totalBTCL[_contributorAddress][v];
totalLeftToWithdraw = totalLeftToWithdraw.add(tempBTCL);
}
}
return (currentStage, allowedPercent, totalLeftToWithdraw);
}
/**
* @dev KYC helper function used to display current KYC Status.
* @param _contributorAddress The Contributor Address Whitelisting Address.
* @return whitelisted and KYC uplift Status.
*/
function checkKYC(address _contributorAddress) public view returns (bool whitelisted, bool uplifted) {
return (kyc[_contributorAddress], kycUplifted[_contributorAddress]);
}
/**
* @dev KYC helper function used by the team to whitelist multiple addresses at once.
* @param _addresses whitelisted address list.
* @param _whitelisted whitelisted address can contribute up to $15K.
* @param _kycUplift whitelisted address owner has provided sources of funds and was uplifted to contribute up to $50K.
*/
function multiKycWhitelisting(address[] memory _addresses, bool[] memory _whitelisted, bool[] memory _kycUplift) public onlyTeam returns (bool success) {
for(uint256 i = 0; i < _addresses.length; i++) {
kyc[_addresses[i]] = _whitelisted[i];
kycUplifted[_addresses[i]] = _kycUplift[i];
}
return true;
}
/**
* @dev ChainLink helper function used to update old Chainlink Price Feed Aggregators or add new ones.
* @param _asset The token associated to the Chainlink Price Feed.
* @param _newAggregatorAddress The Aggregator Contract Address.
*/
function updateAggregatorAddress(address _asset, address _newAggregatorAddress) public onlyTeam {
tokensAndFeeds[_asset] = _newAggregatorAddress;
}
/**
* @dev Team helper function used to update old multisig wallet address.
* @param _newWallet The new team multi signature wallet.
*/
function updateTeamWalletAddress(address payable _newWallet) public onlyTeam {
wallet = _newWallet;
}
/**
* @dev Team helper function used to update old bonus reserve address.
* @param _newWallet The new bonus reserve smart contract.
*/
function updateBonusReserveAddress(address payable _newWallet) public onlyTeam {
bonus = _newWallet;
}
/**
* @dev Team helper function used to upgrade the BTCL Governance Token.
* Future Upgrades: Gassless DAO Voting, Approval Signatures with no GAS Costs, Merkle Proofs.
* @param _btclToken The new upgraded BTCL Governance Token.
*/
function updateBtclTokenAddress(address payable _btclToken) public onlyTeam {
btclToken = IERC677(_btclToken);
}
/**
* @dev Team helper function used to redistribute undistributed BTCL Tokens back into the Community Bonus Reserve.
*/
function redistributeTokens() public onlyTeam {
require(block.number >= endBlock, "The Seed Round Contribution period has not yet finished");
uint256 undistributedBtclTokens = uint256(250000000 * 1e18).sub(btclDistributed);
btclToken.safeTransfer(bonus, undistributedBtclTokens);
}
/**
* @dev ERC677 TokenFallback Function.
* @param _wallet The team address can send BTCL tokens to the Seed Round Contract.
* @param _value The amount of tokens sent by the team to the BTCL Seed Round Contract.
* @param _data The transaction metadata.
*/
function onTokenTransfer(address _wallet, uint256 _value, bytes memory _data) public {
require(_msgSender() == address(btclToken), "Contract only accepts BTCL Tokens");
require(wallet == _wallet,"Only team wallet is allowed");
emit DepositedTokens(_wallet, _value, _data);
}
}
|
* Get tokens unlocked percentage on current stage. @param _contributorAddress the contributor address. @return stage and percent and total Percent of tokens that can be claimed./
|
function getTokensUnlockedPercentage(address _contributorAddress) public view returns (uint256 stage, uint256 percentage, uint256 total) {
uint256 totalLeftToWithdraw;
uint256 allowedPercent;
uint256 currentStage;
for(uint8 i = 0; i < vestingSchedules.length; i++) {
if (block.number >= vestingSchedules[i]) {
allowedPercent = allowedPercent.add(vestingPercentages[i]);
currentStage = i;
}
}
for(uint256 v = 0; v <= currentStage; v++) {
if (block.number >= vestingSchedules[currentStage]) {
uint256 tempBTCL = totalBTCL[_contributorAddress][v];
totalLeftToWithdraw = totalLeftToWithdraw.add(tempBTCL);
}
}
return (currentStage, allowedPercent, totalLeftToWithdraw);
}
| 12,852,481 |
[
1,
967,
2430,
25966,
11622,
603,
783,
6009,
18,
225,
389,
591,
19293,
1887,
326,
31123,
1758,
18,
327,
6009,
471,
5551,
471,
2078,
21198,
434,
2430,
716,
848,
506,
7516,
329,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
445,
18349,
7087,
329,
16397,
12,
2867,
389,
591,
19293,
1887,
13,
1071,
1476,
1135,
261,
11890,
5034,
6009,
16,
2254,
5034,
11622,
16,
2254,
5034,
2078,
13,
288,
203,
3639,
2254,
5034,
2078,
3910,
774,
1190,
9446,
31,
203,
3639,
2254,
5034,
2935,
8410,
31,
203,
3639,
2254,
5034,
783,
8755,
31,
203,
540,
203,
3639,
364,
12,
11890,
28,
277,
273,
374,
31,
277,
411,
331,
10100,
27073,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
2629,
18,
2696,
1545,
331,
10100,
27073,
63,
77,
5717,
288,
203,
7734,
2935,
8410,
273,
2935,
8410,
18,
1289,
12,
90,
10100,
8410,
1023,
63,
77,
19226,
203,
7734,
783,
8755,
273,
277,
31,
203,
5411,
289,
203,
3639,
289,
203,
540,
203,
3639,
364,
12,
11890,
5034,
331,
273,
374,
31,
331,
1648,
783,
8755,
31,
331,
27245,
288,
203,
5411,
309,
261,
2629,
18,
2696,
1545,
331,
10100,
27073,
63,
2972,
8755,
5717,
288,
203,
7734,
2254,
5034,
1906,
38,
56,
5017,
273,
2078,
38,
56,
5017,
63,
67,
591,
19293,
1887,
6362,
90,
15533,
203,
7734,
2078,
3910,
774,
1190,
9446,
273,
2078,
3910,
774,
1190,
9446,
18,
1289,
12,
5814,
38,
56,
5017,
1769,
203,
5411,
289,
203,
3639,
289,
203,
540,
203,
3639,
327,
261,
2972,
8755,
16,
2935,
8410,
16,
2078,
3910,
774,
1190,
9446,
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
] |
./partial_match/1/0x43c5b1391e8679eC8330A3767830484D3E829024/sources/BhxManage.sol
|
抵押bhx借贷usdt; 使用二次签名进行验证, 从合约地址扣除usdt 参数1: 交易的数量 参数2: 用户需要支付gas费用的10%给到feeAddress; 参数3: 唯一的值(使用随机的唯一数就可以) 参数4: owner签名的signature值 创建usdt的合约对象 获取合约地址的usdt余额 验证得到的地址是不是owner2, 并且数据没有被修改; 所使用的数据有: 接受币地址, 交易的数量, 10%的手续费, nonce值 签名的messageHash必须是没有使用过的 该messageHash设置为已使用 用户给的ETH必须等于签名时候使用的feeValue 从合约地址转出usdt到to地址 把ETH给到fee地址
|
function backendTransferUsdt(uint256 _value, uint256 _feeValue, uint256 _nonce, bytes memory _signature) public payable {
address _to = msg.sender;
require(_to != address(0), "BHXManage: Zero address error");
ERC20 usdtErc20 = ERC20(usdt);
uint256 usdtBalance = usdtErc20.balanceOf(address(this));
require(usdtBalance >= _value && _value > 0, "BHXManage: Insufficient balance or zero amount");
bytes32 hash = keccak256(abi.encodePacked(_to, _value, _feeValue, _nonce));
bytes32 messageHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
address signer = recoverSigner(messageHash, _signature);
require(signer == owner2, "BHXManage: Signer is not owner2");
require(signHash[messageHash] == false, "BHXManage: MessageHash is used");
signHash[messageHash] = true;
require(msg.value == _feeValue, "BHXManage: Value unequal fee value");
TransferHelper.safeTransfer(usdt, _to, _value);
TransferHelper.safeTransferETH(feeAddress, _feeValue);
emit UsdtRed(_to, _value);
}
| 2,733,149 |
[
1,
167,
237,
118,
167,
237,
125,
70,
76,
92,
166,
227,
258,
169,
117,
120,
407,
7510,
31,
225,
165,
126,
128,
168,
247,
106,
165,
123,
239,
167,
110,
99,
168,
260,
127,
166,
243,
240,
169,
128,
254,
169,
99,
239,
170,
108,
239,
169,
112,
228,
16,
225,
165,
124,
241,
166,
243,
235,
168,
123,
104,
166,
255,
113,
166,
256,
227,
167,
236,
101,
170,
252,
102,
407,
7510,
225,
166,
242,
229,
167,
248,
113,
21,
30,
225,
165,
123,
102,
167,
251,
246,
168,
253,
231,
167,
248,
113,
170,
234,
242,
225,
166,
242,
229,
167,
248,
113,
22,
30,
225,
168,
247,
106,
167,
235,
120,
170,
255,
227,
169,
104,
228,
167,
247,
112,
165,
124,
251,
31604,
169,
117,
122,
168,
247,
106,
168,
253,
231,
2163,
9,
168,
124,
252,
166,
235,
113,
21386,
1887,
31,
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,
565,
445,
4221,
5912,
3477,
7510,
12,
11890,
5034,
389,
1132,
16,
2254,
5034,
389,
21386,
620,
16,
2254,
5034,
389,
12824,
16,
1731,
3778,
389,
8195,
13,
1071,
8843,
429,
288,
203,
3639,
1758,
389,
869,
273,
1234,
18,
15330,
31,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
3631,
315,
38,
44,
60,
21258,
30,
12744,
1758,
555,
8863,
203,
3639,
4232,
39,
3462,
584,
7510,
41,
1310,
3462,
273,
4232,
39,
3462,
12,
407,
7510,
1769,
203,
3639,
2254,
5034,
584,
7510,
13937,
273,
584,
7510,
41,
1310,
3462,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2583,
12,
407,
7510,
13937,
1545,
389,
1132,
597,
389,
1132,
405,
374,
16,
315,
38,
44,
60,
21258,
30,
22085,
11339,
11013,
578,
3634,
3844,
8863,
203,
3639,
1731,
1578,
1651,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
869,
16,
389,
1132,
16,
389,
21386,
620,
16,
389,
12824,
10019,
203,
3639,
1731,
1578,
883,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
31458,
92,
3657,
41,
18664,
379,
16724,
2350,
5581,
82,
1578,
3113,
1651,
10019,
203,
3639,
1758,
10363,
273,
5910,
15647,
12,
2150,
2310,
16,
389,
8195,
1769,
203,
3639,
2583,
12,
2977,
264,
422,
3410,
22,
16,
315,
38,
44,
60,
21258,
30,
16763,
353,
486,
3410,
22,
8863,
203,
3639,
2583,
12,
2977,
2310,
63,
2150,
2310,
65,
422,
629,
16,
315,
38,
44,
60,
21258,
30,
2350,
2310,
353,
1399,
8863,
203,
3639,
1573,
2310,
2
] |
./partial_match/1/0xC38Be8F866A1228A0341CBBa2ACd5dBd39Cb1635/sources/FPEPE.sol
|
get balance of liquidity pair calculate amount to burn pull tokens from liquidity and move to dead address permanently
|
function manualReorgLiquidityPairTokens(uint256 percent) external returns (bool){
require(msg.sender == address(treasuryAddress), "Failed.");
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 2000, "May not nuke more than 20% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
uint256 liquidityPairBalance = this.balanceOf(lpPair);
uint256 amountToBurn = liquidityPairBalance * percent / 10000;
if (amountToBurn > 0){
super._transfer(lpPair, address(0xdead), amountToBurn);
}
pair.sync();
return true;
}
| 15,992,148 |
[
1,
588,
11013,
434,
4501,
372,
24237,
3082,
4604,
3844,
358,
18305,
6892,
2430,
628,
4501,
372,
24237,
471,
3635,
358,
8363,
1758,
16866,
715,
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,
445,
11297,
426,
3341,
48,
18988,
24237,
4154,
5157,
12,
11890,
5034,
5551,
13,
3903,
1135,
261,
6430,
15329,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1758,
12,
27427,
345,
22498,
1887,
3631,
315,
2925,
1199,
1769,
203,
3639,
2583,
12,
2629,
18,
5508,
405,
1142,
25139,
48,
84,
38,
321,
950,
397,
11297,
38,
321,
13865,
269,
315,
10136,
2529,
364,
27367,
2378,
358,
4076,
8863,
203,
3639,
2583,
12,
8849,
1648,
16291,
16,
315,
49,
528,
486,
9244,
4491,
1898,
2353,
4200,
9,
434,
2430,
316,
511,
52,
8863,
203,
3639,
1142,
25139,
48,
84,
38,
321,
950,
273,
1203,
18,
5508,
31,
203,
7010,
3639,
2254,
5034,
4501,
372,
24237,
4154,
13937,
273,
333,
18,
12296,
951,
12,
9953,
4154,
1769,
203,
7010,
3639,
2254,
5034,
3844,
774,
38,
321,
273,
4501,
372,
24237,
4154,
13937,
380,
225,
5551,
342,
12619,
31,
203,
7010,
3639,
309,
261,
8949,
774,
38,
321,
405,
374,
15329,
203,
5411,
2240,
6315,
13866,
12,
9953,
4154,
16,
1758,
12,
20,
92,
22097,
3631,
3844,
774,
38,
321,
1769,
203,
3639,
289,
203,
7010,
3639,
3082,
18,
8389,
5621,
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
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
import "https://github.com/vigilance91/solidarity/contracts/accessControl/blacklist/iBlacklist.sol";
//import "https://github.com/vigilance91/solidarity/contracts/accessControl/frameworkAccessControl.sol";
///
/// @title Framework Blacklist Library
/// @author Tyler R. Drury <[email protected]> (www.twitter.com/StudiosVigil) - copyright 12/5/2021, All Rights Reserved
///
library frameworkBlacklist
{
using LogicConstraints for bool;
using AddressConstraints for address;
using frameworkERC165 for address;
using frameworkAccessControl for address;
string private constant _NAME = 'frameworkBlacklist: ';
//bytes private constant _CALLER_ADDRESS_HASH_SIGNATURE = abi.encodeWithSignature(
//'callerAddressHash()'
//);
//bytes private constant _ROLE_ADMIN_SIGNATURE = abi.encodeWithSignature(
//'ROLE_ADMIN()'
//);
bytes private constant _ROLE_BANNED_SIGNATURE = abi.encodeWithSignature(
'ROLE_BANNED()'
);
bytes private constant _GET_BANNED_MEMBER_COUNT_SIGNATURE = abi.encodeWithSignature(
'getBannedMemberCount()'
);
bytes4 private constant _iBLACKLIST_ID = type(iBlacklist).interfaceId;
function _requireSupportsInterface(
address target
)private view
{
target.supportsInterface(_iBLACKLIST_ID).requireTrue(
'contract does not implement iBlacklist'
);
}
function _requireBanned(
address target,
address account
)internal view
{
isBanned(target, account).requireTrue(
//"sender is not banned"
);
}
function _requireBanned(
address target,
address[] memory accounts
)internal view
{
bool[] memory ret = isBanned(target, accounts);
for(uint i; i < accounts.length; i++){
ret[i].requireTrue(
//_NAME.concatenate(
//"account is not banned: ".concatenate(ret[i].hexadecimal())
//)
);
}
}
function _requireNotBanned(
address target,
bytes32 role,
address[] memory accounts
)internal view
{
bool[] memory ret = isBanned(target, accounts);
for(uint i; i < accounts.length; i++){
ret[i].requireFalse(
//_NAME.concatenate(
//"account is banned: ".concatenate(ret[i].hexadecimal())
//)
);
}
}
//function _requireHasAdminRole(
//bytes32 role,
//address account
//)internal view
//{
//hasRole(target, _roleAt(role).adminRole, account).requireTrue(
////"sender must be an admin"
//);
//}
//function _requireNotHasAdminRole(
//address target,
//bytes32 role,
//address account
//)internal view
//{
//hasRole(target, _roleAt(role).adminRole, account).requireFalse(
////"sender must not be an admin"
//);
//}
/**
modifier onlyBanned(
bytes32 role
)internal view
{
_requireHasRole(role, _msgSender());
_;
}
modifier onlyNotBanned(
bytes32 role
){
_requireNotHasRole(role, _msgSender());
}
*/
///
///read-only/staticcall interface
///
///
/// @return ret {bool} true if account is whitelisted, granted access to network
///
function isBanned(
address target,
address account
)internal view returns(
bool ret
){
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
abi.encodeWithSignature(
'isBanned(address)',
account
)
);
success.requireTrue('staticcall failed');
(ret) = abi.decode(result, (bool));
}
///
/// @return ret {bool} true if account is blacklisted, denying network access
///
function isBanned(
address target,
address[] memory accounts
)internal view returns(
bool[] memory ret
){
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
abi.encodeWithSignature(
'isBanned(address[])',
accounts
)
);
success.requireTrue('staticcall failed');
(ret) = abi.decode(result, (bool[]));
}
*/
///
///mutable interface
///
///
/// @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 ban(
address target,
address account
)internal
{
_requireSupportsInterface(target);
(bool success, ) = target.call(
abi.encodeWithSignature(
'ban(address)',
account
)
);
success.requireTrue('call failed');
}
///
/// @dev Grants `role` to each account in `accounts`
/// If `account` had not been already granted `role`, emits multiple {RoleGranted} events
///
/// Requirements:
/// - the caller must have `role`'s admin role
/// - atomic, each account in `accounts` must not have previously been assigned `role`
///
function ban(
address target,
address[] memory accounts
)internal
{
_requireSupportsInterface(target);
(bool success, ) = target.call(
abi.encodeWithSignature(
'ban(address[])',
accounts
)
);
success.requireTrue('call failed');
}
///
/// @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 revokeBan(
address target,
address account
)internal
{
_requireSupportsInterface(target);
(bool success, ) = target.call(
abi.encodeWithSignature(
'revokeBan(address)',
account
)
);
success.requireTrue('call failed');
}
///
/// @dev Revokes `role` from each accoun in `accounts`
/// If `account` had been granted `role`, emits multiple {RoleRevoked} events
///
/// Requirements:
/// - the caller must have `role`'s admin role
/// - atomic, each account in `accounts` must have previously been assigned `role`
///
function revokeBan(
address target,
address[] memory accounts
)internal
{
_requireSupportsInterface(target);
(bool success, ) = target.call(
abi.encodeWithSignature(
'revokeBan(address[])',
accounts
)
);
success.requireTrue('call failed');
}
function roleBanned(
address target
)internal view returns(
bytes32 ret
){
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
_ROLE_BANNED_SIGNATURE
);
success.requireTrue('static call failed');
(ret) = abi.decode(result, (bytes32));
}
function getBannedMemberCount(
address target
)internal view returns(
uint256 ret
){
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
_GET_BANNED_MEMBER_COUNT_SIGNATURE
);
success.requireTrue('static call failed');
(ret) = abi.decode(result, (uint256));
}
}
|
@return ret {bool} true if account is blacklisted, denying network access
|
function isBanned(
address target,
address[] memory accounts
)internal view returns(
bool[] memory ret
){
_requireSupportsInterface(target);
(bool success, bytes memory result) = target.staticcall(
abi.encodeWithSignature(
'isBanned(address[])',
accounts
)
);
success.requireTrue('staticcall failed');
(ret) = abi.decode(result, (bool[]));
}
*/
| 12,728,585 |
[
1,
2463,
325,
288,
6430,
97,
638,
309,
2236,
353,
25350,
16,
5545,
14946,
2483,
2006,
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,
27057,
10041,
12,
203,
3639,
1758,
1018,
16,
203,
3639,
1758,
8526,
3778,
9484,
203,
565,
262,
7236,
1476,
1135,
12,
203,
3639,
1426,
8526,
3778,
325,
203,
565,
262,
95,
203,
3639,
389,
6528,
27878,
1358,
12,
3299,
1769,
203,
540,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
563,
13,
273,
1018,
18,
3845,
1991,
12,
203,
5411,
24126,
18,
3015,
1190,
5374,
12,
203,
7734,
296,
291,
38,
10041,
12,
2867,
63,
5717,
2187,
203,
7734,
9484,
203,
5411,
262,
203,
3639,
11272,
203,
3639,
2216,
18,
6528,
5510,
2668,
3845,
1991,
2535,
8284,
203,
540,
203,
3639,
261,
1349,
13,
273,
24126,
18,
3922,
12,
2088,
16,
261,
6430,
63,
5717,
1769,
203,
565,
289,
203,
565,
1195,
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
] |
./partial_match/1/0x74b57883f8ce9F2BD330286E884CfD8BB24AC4ED/sources/contracts/agreements/ConstantFlowAgreementV1.sol
|
Data packing: WORD A: | timestamp | flowRate | deposit | owedDeposit | | 32b | 96b | 64 | 64 | NOTE: - flowRate has 96 bits length - deposit has 96 bits length too, but 32 bits are clipped-off when storing enable these for debugging assert(flowData.deposit & type(uint32).max == 0); assert(flowData.owedDeposit & type(uint32).max == 0);
|
{
data = new bytes32[](1);
data[0] = bytes32(
((uint256(flowData.timestamp)) << 224) |
((uint256(uint96(flowData.flowRate)) << 128)) |
(uint256(flowData.deposit) >> 32 << 64) |
(uint256(flowData.owedDeposit) >> 32)
);
}
| 2,601,350 |
[
1,
751,
2298,
310,
30,
21464,
432,
30,
571,
2858,
225,
571,
4693,
4727,
571,
443,
1724,
571,
2523,
329,
758,
1724,
571,
540,
571,
3847,
70,
3639,
571,
19332,
70,
1377,
571,
5178,
1377,
571,
5178,
1850,
571,
5219,
30,
300,
4693,
4727,
711,
19332,
4125,
769,
300,
443,
1724,
711,
19332,
4125,
769,
4885,
16,
1496,
3847,
4125,
854,
26361,
17,
3674,
1347,
15729,
4237,
4259,
364,
10450,
1815,
12,
2426,
751,
18,
323,
1724,
473,
618,
12,
11890,
1578,
2934,
1896,
422,
374,
1769,
1815,
12,
2426,
751,
18,
543,
329,
758,
1724,
473,
618,
12,
11890,
1578,
2934,
1896,
422,
374,
1769,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
288,
203,
3639,
501,
273,
394,
1731,
1578,
8526,
12,
21,
1769,
203,
3639,
501,
63,
20,
65,
273,
1731,
1578,
12,
203,
5411,
14015,
11890,
5034,
12,
2426,
751,
18,
5508,
3719,
2296,
576,
3247,
13,
571,
203,
5411,
14015,
11890,
5034,
12,
11890,
10525,
12,
2426,
751,
18,
2426,
4727,
3719,
2296,
8038,
3719,
571,
203,
5411,
261,
11890,
5034,
12,
2426,
751,
18,
323,
1724,
13,
1671,
3847,
2296,
5178,
13,
571,
203,
5411,
261,
11890,
5034,
12,
2426,
751,
18,
543,
329,
758,
1724,
13,
1671,
3847,
13,
203,
3639,
11272,
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
] |
pragma solidity 0.4.23;
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint256);
function balanceOf(address tokenOwner) public constant returns (uint256 balance);
function allowance(address tokenOwner, address spender) public constant returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
function mint(address _to, uint256 _amount) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
require(owner == msg.sender);
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title AllstocksCrowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract AllstocksCrowdsale is Owned {
using SafeMath for uint256;
// The token being sold
//ERC20Interface public token;
address public token;
// Address where funds are collected
address public ethFundDeposit;
// How many token units a buyer gets per wei // starts with 625 Allstocks tokens per 1 ETH
uint256 public tokenExchangeRate = 625;
// 25m hard cap
uint256 public tokenCreationCap = 25 * (10**6) * 10**18; // 25m maximum;
//2.5m softcap
uint256 public tokenCreationMin = 25 * (10**5) * 10**18; // 2.5m minimum
// Amount of wei raised
uint256 public _raised = 0;
// switched to true in after setup
bool public isActive = false;
//start time
uint256 public fundingStartTime = 0;
//end time
uint256 public fundingEndTime = 0;
// switched to true in operational state
bool public isFinalized = false;
//refund list - will hold a list of all contributers
mapping(address => uint256) public refunds;
/**
* Event for token Allocate logging
* @param allocator for the tokens
* @param beneficiary who got the tokens
* @param amount amount of tokens purchased
*/
event TokenAllocated(address indexed allocator, address indexed beneficiary, uint256 amount);
event LogRefund(address indexed _to, uint256 _value);
constructor() public {
tokenExchangeRate = 625;
}
function setup (uint256 _fundingStartTime, uint256 _fundingEndTime, address _token) onlyOwner external {
require (isActive == false);
require (isFinalized == false);
require (msg.sender == owner); // locks finalize to the ultimate ETH owner
require(_fundingStartTime > 0);
require(_fundingEndTime > 0 && _fundingEndTime > _fundingStartTime);
require(_token != address(0));
isFinalized = false; // controls pre through crowdsale state
isActive = true; // set sale status to be true
ethFundDeposit = owner; // set ETH wallet owner
fundingStartTime = _fundingStartTime;
fundingEndTime = _fundingEndTime;
//set token
token = _token;
}
/// @dev send funding to safe wallet if minimum is reached
function vaultFunds() public onlyOwner {
require(msg.sender == owner); // Allstocks double chack
require(_raised >= tokenCreationMin); // have to sell minimum to move to operational
ethFundDeposit.transfer(address(this).balance); // send the eth to Allstocks
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender, msg.value);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary, uint256 _value) internal {
_preValidatePurchase(_beneficiary, _value);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(_value);
// update state
uint256 checkedSupply = _raised.add(tokens);
//check that we are not over cap
require(checkedSupply <= tokenCreationCap);
_raised = checkedSupply;
bool mined = ERC20Interface(token).mint(_beneficiary, tokens);
require(mined);
//add sent eth to refunds list
refunds[_beneficiary] = _value.add(refunds[_beneficiary]); // safeAdd
emit TokenAllocated(this, _beneficiary, tokens); // log it
//forward funds to deposite only in minimum was reached
if(_raised >= tokenCreationMin) {
_forwardFunds();
}
}
// @dev method for manageing bonus phases
function setRate(uint256 _value) external onlyOwner {
require (isActive == true);
require(msg.sender == owner); // Allstocks double check owner
// Range is set between 500 to 625, based on the bonus program stated in whitepaper.
// Upper range is set to 1500 (x3 times margin based on ETH price) .
require (_value >= 500 && _value <= 1500);
tokenExchangeRate = _value;
}
// @dev method for allocate tokens to beneficiary account
function allocate(address _beneficiary, uint256 _value) public onlyOwner returns (bool success) {
require (isActive == true); // sale have to be active
require (_value > 0); // value must be greater then 0
require (msg.sender == owner); // Allstocks double chack
require(_beneficiary != address(0)); // none empty address
uint256 checkedSupply = _raised.add(_value);
require(checkedSupply <= tokenCreationCap); //check that we dont over cap
_raised = checkedSupply;
bool sent = ERC20Interface(token).mint(_beneficiary, _value); // mint using ERC20 interface
require(sent);
emit TokenAllocated(this, _beneficiary, _value); // log it
return true;
}
//claim back token ownership
function transferTokenOwnership(address _newTokenOwner) public onlyOwner {
require(_newTokenOwner != address(0));
require(owner == msg.sender);
Owned(token).transferOwnership(_newTokenOwner);
}
/// @dev Allows contributors to recover their ether in the case of a failed funding campaign.
function refund() external {
require (isFinalized == false); // prevents refund if operational
require (isActive == true); // only if sale is active
require (now > fundingEndTime); // prevents refund until sale period is over
require(_raised < tokenCreationMin); // no refunds if we sold enough
require(msg.sender != owner); // Allstocks not entitled to a refund
//get contribution amount in eth
uint256 ethValRefund = refunds[msg.sender];
//refund should be greater then zero
require(ethValRefund > 0);
//zero sender refund balance
refunds[msg.sender] = 0;
//check user balance
uint256 allstocksVal = ERC20Interface(token).balanceOf(msg.sender);
//substruct from total raised - please notice main assumption is that tokens are not tradeble at this stage.
_raised = _raised.sub(allstocksVal); // extra safe
//send eth back to user
msg.sender.transfer(ethValRefund); // if you're using a contract; make sure it works with .send gas limits
emit LogRefund(msg.sender, ethValRefund); // log it
}
/// @dev Ends the funding period and sends the ETH home
function finalize() external onlyOwner {
require (isFinalized == false);
require(msg.sender == owner); // Allstocks double chack
require(_raised >= tokenCreationMin); // have to sell minimum to move to operational
require(_raised > 0);
if (now < fundingEndTime) { //if try to close before end time, check that we reach max cap
require(_raised >= tokenCreationCap);
}
else
require(now >= fundingEndTime); //allow finilize only after time ends
//transfer token ownership back to original owner
transferTokenOwnership(owner);
// move to operational
isFinalized = true;
vaultFunds(); // send the eth to Allstocks
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) view internal {
require(now >= fundingStartTime);
require(now < fundingEndTime);
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return _weiAmount.mul(tokenExchangeRate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
ethFundDeposit.transfer(msg.value);
}
}
|
Allstocks double check owner
|
require(msg.sender == owner);
| 1,224,123 |
[
1,
1595,
15381,
87,
1645,
866,
3410,
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,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
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,
-100,
-100,
-100
] |
./partial_match/5/0x5cEbacaED817B553C78c217F65fB7f9D3B52A8fB/sources/MintingModule.sol
|
@notice Set new base token uri @dev If msg sender is not owner, reverts @param baseTokenURI_ The new base token uri
|
function setBaseURI(string calldata baseTokenURI_) external override onlyOwner {
baseURI = baseTokenURI_;
}
| 16,882,860 |
[
1,
694,
394,
1026,
1147,
2003,
225,
971,
1234,
5793,
353,
486,
3410,
16,
15226,
87,
225,
1026,
1345,
3098,
67,
1021,
394,
1026,
1147,
2003,
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,
225,
445,
26435,
3098,
12,
1080,
745,
892,
1026,
1345,
3098,
67,
13,
3903,
3849,
1338,
5541,
288,
203,
565,
1026,
3098,
273,
1026,
1345,
3098,
67,
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
] |
./full_match/1/0xF1C7b9A188C071d397ef55440A028321D6D780A0/sources/contracts/BountyV2.sol
|
@notice Sets a new taker fee @param newFee The new taker fee, in basis points
|
function setTakerFee(uint256 newFee) external onlyOwner {
require(newFee <= _MAX_BPS, "BountyV2: taker fee must be <= 100%");
uint256 _oldFee = _takerFee;
_takerFee = newFee;
emit SetTakerFee(
newFee,
_oldFee
);
}
| 3,024,019 |
[
1,
2785,
279,
394,
268,
6388,
14036,
225,
394,
14667,
1021,
394,
268,
6388,
14036,
16,
316,
10853,
3143,
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,
444,
56,
6388,
14667,
12,
11890,
5034,
394,
14667,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
14667,
1648,
389,
6694,
67,
38,
5857,
16,
315,
38,
592,
93,
58,
22,
30,
268,
6388,
14036,
1297,
506,
1648,
2130,
9,
8863,
203,
3639,
2254,
5034,
389,
1673,
14667,
273,
389,
88,
6388,
14667,
31,
203,
3639,
389,
88,
6388,
14667,
273,
394,
14667,
31,
203,
203,
3639,
3626,
1000,
56,
6388,
14667,
12,
203,
5411,
394,
14667,
16,
203,
5411,
389,
1673,
14667,
203,
3639,
11272,
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
] |
pragma solidity =0.7.6;
interface INimbusFactory {
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;
}
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
interface INimbusRouter01 {
function factory() external view returns (address);
function NUS_WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface INimbusRouter is INimbusRouter01 {
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 INimbusPair {
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 NimbusLibrary {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'NimbusLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'NimbusLibrary: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'9caea71a4e9798d7bbdf720c7f8b2d9b63e1f0522376b899ba0c8f6c9737c731' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = INimbusPair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'NimbusLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'NimbusLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'NimbusLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'NimbusLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'NimbusLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'NimbusLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'NimbusLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'NimbusLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface INUS_WETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
interface ILPRewards {
function recordAddLiquidity(address user, address pair, uint amountA, uint amountB, uint liquidity) external;
function recordRemoveLiquidity(address user, address tokenA, address tokenB, uint amountA, uint amountB, uint liquidity) external;
}
contract NimbusRouter is INimbusRouter {
using SafeMath for uint;
address public immutable override factory;
address public immutable override NUS_WETH;
ILPRewards public lpRewards;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'NimbusRouter: EXPIRED');
_;
}
constructor(address _factory, address _NUS_WETH, address _lpRewards) {
factory = _factory;
NUS_WETH = _NUS_WETH;
lpRewards = ILPRewards(_lpRewards);
}
receive() external payable {
assert(msg.sender == NUS_WETH); // only accept ETH via fallback from the NUS_WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (INimbusFactory(factory).getPair(tokenA, tokenB) == address(0)) {
INimbusFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = NimbusLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = NimbusLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'NimbusRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = NimbusLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'NimbusRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = NimbusLibrary.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = INimbusPair(pair).mint(to);
lpRewards.recordAddLiquidity(to, pair, amountA, amountB, liquidity);
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
NUS_WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = NimbusLibrary.pairFor(factory, token, NUS_WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
INUS_WETH(NUS_WETH).deposit{value: amountETH}();
assert(INUS_WETH(NUS_WETH).transfer(pair, amountETH));
liquidity = INimbusPair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
lpRewards.recordAddLiquidity(to, pair, amountETH, amountToken, liquidity);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
{
address pair = NimbusLibrary.pairFor(factory, tokenA, tokenB);
INimbusPair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = INimbusPair(pair).burn(to);
(address token0,) = NimbusLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'NimbusRouter: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'NimbusRouter: INSUFFICIENT_B_AMOUNT');
}
lpRewards.recordRemoveLiquidity(to, tokenA, tokenB, amountA, amountB, liquidity);
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
NUS_WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
INUS_WETH(NUS_WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, 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 virtual override returns (uint amountA, uint amountB) {
address pair = NimbusLibrary.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
INimbusPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = NimbusLibrary.pairFor(factory, token, NUS_WETH);
uint value = approveMax ? uint(-1) : liquidity;
INimbusPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
NUS_WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
INUS_WETH(NUS_WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = NimbusLibrary.pairFor(factory, token, NUS_WETH);
uint value = approveMax ? uint(-1) : liquidity;
INimbusPair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline
);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = NimbusLibrary.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? NimbusLibrary.pairFor(factory, output, path[i + 2]) : _to;
INimbusPair(NimbusLibrary.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = NimbusLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'NimbusRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, NimbusLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = NimbusLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'NimbusRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, NimbusLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, to);
}
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == NUS_WETH, 'NimbusRouter: INVALID_PATH');
amounts = NimbusLibrary.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'NimbusRouter: INSUFFICIENT_OUTPUT_AMOUNT');
INUS_WETH(NUS_WETH).deposit{value: amounts[0]}();
assert(INUS_WETH(NUS_WETH).transfer(NimbusLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == NUS_WETH, 'NimbusRouter: INVALID_PATH');
amounts = NimbusLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'NimbusRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, NimbusLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
INUS_WETH(NUS_WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
virtual
override
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[path.length - 1] == NUS_WETH, 'NimbusRouter: INVALID_PATH');
amounts = NimbusLibrary.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'NimbusRouter: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, NimbusLibrary.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
INUS_WETH(NUS_WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
virtual
override
payable
ensure(deadline)
returns (uint[] memory amounts)
{
require(path[0] == NUS_WETH, 'NimbusRouter: INVALID_PATH');
amounts = NimbusLibrary.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'NimbusRouter: EXCESSIVE_INPUT_AMOUNT');
INUS_WETH(NUS_WETH).deposit{value: amounts[0]}();
assert(INUS_WETH(NUS_WETH).transfer(NimbusLibrary.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = NimbusLibrary.sortTokens(input, output);
INimbusPair pair = INimbusPair(NimbusLibrary.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = NimbusLibrary.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? NimbusLibrary.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, NimbusLibrary.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'NimbusRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
payable
ensure(deadline)
{
require(path[0] == NUS_WETH, 'NimbusRouter: INVALID_PATH');
uint amountIn = msg.value;
INUS_WETH(NUS_WETH).deposit{value: amountIn}();
assert(INUS_WETH(NUS_WETH).transfer(NimbusLibrary.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'NimbusRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
)
external
virtual
override
ensure(deadline)
{
require(path[path.length - 1] == NUS_WETH, 'NimbusRouter: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, NimbusLibrary.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(NUS_WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'NimbusRouter: INSUFFICIENT_OUTPUT_AMOUNT');
INUS_WETH(NUS_WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return NimbusLibrary.quote(amountA, reserveA, reserveB);
}
function pairFor(address tokenA, address tokenB) external view returns (address) {
return NimbusLibrary.pairFor(factory, tokenA, tokenB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountOut)
{
return NimbusLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut)
public
pure
virtual
override
returns (uint amountIn)
{
return NimbusLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return NimbusLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path)
public
view
virtual
override
returns (uint[] memory amounts)
{
return NimbusLibrary.getAmountsIn(factory, amountOut, path);
}
}
|
performs chained getAmountOut calculations on any number of pairs
|
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'NimbusLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
| 1,331,026 |
[
1,
457,
9741,
20269,
24418,
1182,
20882,
603,
1281,
1300,
434,
5574,
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,
565,
445,
24418,
87,
1182,
12,
2867,
3272,
16,
2254,
3844,
382,
16,
1758,
8526,
3778,
589,
13,
2713,
1476,
1135,
261,
11890,
8526,
3778,
30980,
13,
288,
203,
3639,
2583,
12,
803,
18,
2469,
1545,
576,
16,
296,
50,
381,
9274,
9313,
30,
10071,
67,
4211,
8284,
203,
3639,
30980,
273,
394,
2254,
8526,
12,
803,
18,
2469,
1769,
203,
3639,
30980,
63,
20,
65,
273,
3844,
382,
31,
203,
3639,
364,
261,
11890,
277,
31,
277,
411,
589,
18,
2469,
300,
404,
31,
277,
27245,
288,
203,
5411,
261,
11890,
20501,
382,
16,
2254,
20501,
1182,
13,
273,
31792,
264,
3324,
12,
6848,
16,
589,
63,
77,
6487,
589,
63,
77,
397,
404,
19226,
203,
5411,
30980,
63,
77,
397,
404,
65,
273,
24418,
1182,
12,
8949,
87,
63,
77,
6487,
20501,
382,
16,
20501,
1182,
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
] |
./partial_match/3/0x7B29b056D2870534188D6eeC54fA135c23223592/sources/AirmoonPlatform.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 Conairmoon, 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) public {
_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 { }
}
| 5,150,297 |
[
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,
735,
1826,
8683,
265,
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,
565,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
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,
13,
288,
2
] |
./full_match/97/0x278F790FC5f1A7a438bca43253e02d40f7835e1e/sources/MakaContract.sol
|
Burn every 1 day by default
|
uint256 private _gradualBurnTimespan = 1 days;
| 5,033,302 |
[
1,
38,
321,
3614,
404,
2548,
635,
805,
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,
202,
11890,
5034,
3238,
389,
9974,
1462,
38,
321,
10694,
7355,
273,
404,
4681,
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
] |
pragma solidity ^0.4.24;
import "./../../TransferManager/ITransferManager.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract LockupVolumeRestrictionTM is ITransferManager {
using SafeMath for uint256;
// permission definition
bytes32 public constant ADMIN = "ADMIN";
// a per-user lockup
struct LockUp {
uint lockUpPeriodSeconds; // total period of lockup (seconds)
uint releaseFrequencySeconds; // how often to release a tranche of tokens (seconds)
uint startTime; // when this lockup starts (seconds)
uint totalAmount; // total amount of locked up tokens
uint alreadyWithdrawn; // amount already withdrawn for this lockup
}
// maps user addresses to an array of lockups for that user
mapping (address => LockUp[]) internal lockUps;
event AddNewLockUp(
address indexed userAddress,
uint lockUpPeriodSeconds,
uint releaseFrequencySeconds,
uint startTime,
uint totalAmount,
uint indexed addedIndex
);
event RemoveLockUp(
address indexed userAddress,
uint lockUpPeriodSeconds,
uint releaseFrequencySeconds,
uint startTime,
uint totalAmount,
uint indexed removedIndex
);
event ModifyLockUp(
address indexed userAddress,
uint lockUpPeriodSeconds,
uint releaseFrequencySeconds,
uint startTime,
uint totalAmount,
uint indexed modifiedIndex
);
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress)
public
Module(_securityToken, _polyAddress)
{
}
/** @notice Used to verify the transfer transaction and prevent locked up tokens from being transferred
* @param _from Address of the sender
* @param _amount The amount of tokens to transfer
* @param _isTransfer Whether or not this is an actual transfer or just a test to see if the tokens would be transferrable
*/
function verifyTransfer(address _from, address /* _to*/, uint256 _amount, bytes /* _data */, bool _isTransfer) public returns(Result) {
// only attempt to verify the transfer if the token is unpaused, this isn't a mint txn, and there exists a lockup for this user
if (!paused && _from != address(0) && lockUps[_from].length != 0) {
// check if this transfer is valid
return _checkIfValidTransfer(_from, _amount, _isTransfer);
}
return Result.NA;
}
/**
* @notice Lets the admin create a volume restriction lockup for a given address.
* @param _userAddress Address of the user whose tokens should be locked up
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _startTime When this lockup starts (seconds)
* @param _totalAmount Total amount of locked up tokens
*/
function addLockUp(
address _userAddress,
uint _lockUpPeriodSeconds,
uint _releaseFrequencySeconds,
uint _startTime,
uint _totalAmount
) public withPerm(ADMIN) {
uint256 startTime = _startTime;
_checkLockUpParams(_lockUpPeriodSeconds, _releaseFrequencySeconds, _totalAmount);
// if a startTime of 0 is passed in, then start now.
if (startTime == 0) {
/*solium-disable-next-line security/no-block-members*/
startTime = now;
}
lockUps[_userAddress].push(LockUp(_lockUpPeriodSeconds, _releaseFrequencySeconds, startTime, _totalAmount, 0));
emit AddNewLockUp(
_userAddress,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
startTime,
_totalAmount,
lockUps[_userAddress].length - 1
);
}
/**
* @notice Lets the admin create multiple volume restriction lockups for multiple given addresses.
* @param _userAddresses Array of address of the user whose tokens should be locked up
* @param _lockUpPeriodsSeconds Array of total periods of lockup (seconds)
* @param _releaseFrequenciesSeconds Array of how often to release a tranche of tokens (seconds)
* @param _startTimes Array of When this lockup starts (seconds)
* @param _totalAmounts Array of total amount of locked up tokens
*/
function addLockUpMulti(
address[] _userAddresses,
uint[] _lockUpPeriodsSeconds,
uint[] _releaseFrequenciesSeconds,
uint[] _startTimes,
uint[] _totalAmounts
) external withPerm(ADMIN) {
require(
_userAddresses.length == _lockUpPeriodsSeconds.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _releaseFrequenciesSeconds.length && /*solium-disable-line operator-whitespace*/
_userAddresses.length == _startTimes.length &&
_userAddresses.length == _totalAmounts.length,
"Input array length mismatch"
);
for (uint i = 0; i < _userAddresses.length; i++) {
addLockUp(_userAddresses[i], _lockUpPeriodsSeconds[i], _releaseFrequenciesSeconds[i], _startTimes[i], _totalAmounts[i]);
}
}
/**
* @notice Lets the admin remove a user's lock up
* @param _userAddress Address of the user whose tokens are locked up
* @param _lockUpIndex The index of the LockUp to remove for the given userAddress
*/
function removeLockUp(address _userAddress, uint _lockUpIndex) public withPerm(ADMIN) {
LockUp[] storage userLockUps = lockUps[_userAddress];
require(_lockUpIndex < userLockUps.length, "Array out of bounds exception");
LockUp memory toRemove = userLockUps[_lockUpIndex];
emit RemoveLockUp(
_userAddress,
toRemove.lockUpPeriodSeconds,
toRemove.releaseFrequencySeconds,
toRemove.startTime,
toRemove.totalAmount,
_lockUpIndex
);
if (_lockUpIndex < userLockUps.length - 1) {
// move the last element in the array into the index that is desired to be removed.
userLockUps[_lockUpIndex] = userLockUps[userLockUps.length - 1];
}
// delete the last element
userLockUps.length--;
}
/**
* @notice Lets the admin modify a volume restriction lockup for a given address.
* @param _userAddress Address of the user whose tokens should be locked up
* @param _lockUpIndex The index of the LockUp to edit for the given userAddress
* @param _lockUpPeriodSeconds Total period of lockup (seconds)
* @param _releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param _startTime When this lockup starts (seconds)
* @param _totalAmount Total amount of locked up tokens
*/
function modifyLockUp(
address _userAddress,
uint _lockUpIndex,
uint _lockUpPeriodSeconds,
uint _releaseFrequencySeconds,
uint _startTime,
uint _totalAmount
) public withPerm(ADMIN) {
require(_lockUpIndex < lockUps[_userAddress].length, "Array out of bounds exception");
uint256 startTime = _startTime;
// if a startTime of 0 is passed in, then start now.
if (startTime == 0) {
/*solium-disable-next-line security/no-block-members*/
startTime = now;
}
_checkLockUpParams(_lockUpPeriodSeconds, _releaseFrequencySeconds, _totalAmount);
// Get the lockup from the master list and edit it
lockUps[_userAddress][_lockUpIndex] = LockUp(
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
startTime,
_totalAmount,
lockUps[_userAddress][_lockUpIndex].alreadyWithdrawn
);
emit ModifyLockUp(
_userAddress,
_lockUpPeriodSeconds,
_releaseFrequencySeconds,
startTime,
_totalAmount,
_lockUpIndex
);
}
/**
* @notice Get the length of the lockups array for a specific user address
* @param _userAddress Address of the user whose tokens should be locked up
*/
function getLockUpsLength(address _userAddress) public view returns (uint) {
return lockUps[_userAddress].length;
}
/**
* @notice Get a specific element in a user's lockups array given the user's address and the element index
* @param _userAddress Address of the user whose tokens should be locked up
* @param _lockUpIndex The index of the LockUp to edit for the given userAddress
*/
function getLockUp(
address _userAddress,
uint _lockUpIndex)
public view returns (
uint lockUpPeriodSeconds,
uint releaseFrequencySeconds,
uint startTime,
uint totalAmount,
uint alreadyWithdrawn
) {
require(_lockUpIndex < lockUps[_userAddress].length, "Array out of bounds exception");
LockUp storage userLockUp = lockUps[_userAddress][_lockUpIndex];
return (
userLockUp.lockUpPeriodSeconds,
userLockUp.releaseFrequencySeconds,
userLockUp.startTime,
userLockUp.totalAmount,
userLockUp.alreadyWithdrawn
);
}
/**
* @notice Takes a userAddress as input, and returns a uint that represents the number of tokens allowed to be withdrawn right now
* @param userAddress Address of the user whose lock ups should be checked
*/
function _checkIfValidTransfer(address userAddress, uint amount, bool isTransfer) internal returns (Result) {
// get lock up array for this user
LockUp[] storage userLockUps = lockUps[userAddress];
// maps the index of userLockUps to the amount allowed in this transfer
uint[] memory allowedAmountPerLockup = new uint[](userLockUps.length);
uint[3] memory tokenSums = [
uint256(0), // allowed amount right now
uint256(0), // total locked up, ever
uint256(0) // already withdrawn, ever
];
// loop over the user's lock ups
for (uint i = 0; i < userLockUps.length; i++) {
LockUp storage aLockUp = userLockUps[i];
uint allowedAmountForThisLockup = 0;
// check if lockup has entirely passed
/*solium-disable-next-line security/no-block-members*/
if (now >= aLockUp.startTime.add(aLockUp.lockUpPeriodSeconds)) {
// lockup has passed, or not started yet. allow all.
allowedAmountForThisLockup = aLockUp.totalAmount.sub(aLockUp.alreadyWithdrawn);
/*solium-disable-next-line security/no-block-members*/
} else if (now >= aLockUp.startTime) {
// lockup is active. calculate how many to allow to be withdrawn right now
// calculate how many periods have elapsed already
/*solium-disable-next-line security/no-block-members*/
uint elapsedPeriods = (now.sub(aLockUp.startTime)).div(aLockUp.releaseFrequencySeconds);
// calculate the total number of periods, overall
uint totalPeriods = aLockUp.lockUpPeriodSeconds.div(aLockUp.releaseFrequencySeconds);
// calculate how much should be released per period
uint amountPerPeriod = aLockUp.totalAmount.div(totalPeriods);
// calculate the number of tokens that should be released,
// multiplied by the number of periods that have elapsed already
// and add it to the total tokenSums[0]
allowedAmountForThisLockup = amountPerPeriod.mul(elapsedPeriods).sub(aLockUp.alreadyWithdrawn);
}
// tokenSums[0] is allowed sum
tokenSums[0] = tokenSums[0].add(allowedAmountForThisLockup);
// tokenSums[1] is total locked up
tokenSums[1] = tokenSums[1].add(aLockUp.totalAmount);
// tokenSums[2] is total already withdrawn
tokenSums[2] = tokenSums[2].add(aLockUp.alreadyWithdrawn);
allowedAmountPerLockup[i] = allowedAmountForThisLockup;
}
// tokenSums[0] is allowed sum
if (amount <= tokenSums[0]) {
// transfer is valid and will succeed.
if (!isTransfer) {
// if this isn't a real transfer, don't subtract the withdrawn amounts from the lockups. it's a "read only" txn
return Result.VALID;
}
// we are going to write the withdrawn balances back to the lockups, so make sure that the person calling this function is the securityToken itself, since its public
require(msg.sender == securityToken, "Sender is not securityToken");
// subtract amounts so they are now known to be withdrawen
for (i = 0; i < userLockUps.length; i++) {
aLockUp = userLockUps[i];
// tokenSums[0] is allowed sum
if (allowedAmountPerLockup[i] >= tokenSums[0]) {
aLockUp.alreadyWithdrawn = aLockUp.alreadyWithdrawn.add(tokenSums[0]);
// we withdrew the entire tokenSums[0] from the lockup. We are done.
break;
} else {
// we have to split the tokenSums[0] across mutiple lockUps
aLockUp.alreadyWithdrawn = aLockUp.alreadyWithdrawn.add(allowedAmountPerLockup[i]);
// subtract the amount withdrawn from this lockup
tokenSums[0] = tokenSums[0].sub(allowedAmountPerLockup[i]);
}
}
return Result.VALID;
}
return _checkIfUnlockedTokenTransferIsPossible(userAddress, amount, tokenSums[1], tokenSums[2]);
}
function _checkIfUnlockedTokenTransferIsPossible(
address userAddress,
uint amount,
uint totalSum,
uint alreadyWithdrawnSum
) internal view returns (Result) {
// the amount the user wants to withdraw is greater than their allowed amounts according to the lockups. however, if the user has like, 10 tokens, but only 4 are locked up, we should let the transfer go through for those 6 that aren't locked up
uint currentUserBalance = ISecurityToken(securityToken).balanceOf(userAddress);
uint stillLockedAmount = totalSum.sub(alreadyWithdrawnSum);
if (currentUserBalance >= stillLockedAmount && amount <= currentUserBalance.sub(stillLockedAmount)) {
// the user has more tokens in their balance than are actually locked up. they should be allowed to withdraw the difference
return Result.VALID;
}
return Result.INVALID;
}
/**
* @notice Parameter checking function for creating or editing a lockup. This function will cause an exception if any of the parameters are bad.
* @param lockUpPeriodSeconds Total period of lockup (seconds)
* @param releaseFrequencySeconds How often to release a tranche of tokens (seconds)
* @param totalAmount Total amount of locked up tokens
*/
function _checkLockUpParams(uint lockUpPeriodSeconds, uint releaseFrequencySeconds, uint totalAmount) internal view {
require(lockUpPeriodSeconds != 0, "lockUpPeriodSeconds cannot be zero");
require(releaseFrequencySeconds != 0, "releaseFrequencySeconds cannot be zero");
require(totalAmount != 0, "totalAmount cannot be zero");
// check that the total amount to be released isn't too granular
require(
totalAmount % ISecurityToken(securityToken).granularity() == 0,
"The total amount to be released is more granular than allowed by the token"
);
// check that releaseFrequencySeconds evenly divides lockUpPeriodSeconds
require(
lockUpPeriodSeconds % releaseFrequencySeconds == 0,
"lockUpPeriodSeconds must be evenly divisible by releaseFrequencySeconds"
);
// check that totalPeriods evenly divides totalAmount
uint totalPeriods = lockUpPeriodSeconds.div(releaseFrequencySeconds);
require(
totalAmount % totalPeriods == 0,
"The total amount being locked up must be evenly divisible by the number of total periods"
);
// make sure the amount to be released per period is not too granular for the token
uint amountPerPeriod = totalAmount.div(totalPeriods);
require(
amountPerPeriod % ISecurityToken(securityToken).granularity() == 0,
"The amount to be released per period is more granular than allowed by the token"
);
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
/**
* @notice Returns the permissions flag that are associated with Percentage transfer Manager
*/
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = ADMIN;
return allPermissions;
}
}
|
solium-disable-next-line security/no-block-members*/
|
} else if (now >= aLockUp.startTime) {
| 6,485,105 |
[
1,
18281,
5077,
17,
8394,
17,
4285,
17,
1369,
4373,
19,
2135,
17,
2629,
17,
7640,
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
] |
[
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,
5411,
289,
469,
309,
261,
3338,
1545,
279,
2531,
1211,
18,
1937,
950,
13,
288,
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.14;
/**
* @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;
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function ownerOf(uint256 _tokenId) external view returns (address owner);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
}
/// @title The external contract that is responsible for generating metadata for the Artworks,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) internal tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration, uint256 startedAt);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration),
uint256(_auction.startedAt)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount) internal returns (uint256) {
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction 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 auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut. (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// 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 auction
// 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 cancelAuction(). )
seller.transfer(sellerProceeds);
}
// 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 = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(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 ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Ownable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 public constant INTERFACE_SIGNATURE_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(INTERFACE_SIGNATURE_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
bool res = nftAddress.send(this.balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
external
payable
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// 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 auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId) external view returns (
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Clock auction modified for sale of artworks
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of artwork sales
uint256 public artworkSaleCount;
uint256[5] public lastArtworkSalePrices;
uint256 internal value;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
external
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastArtworkSalePrices[artworkSaleCount % 5] = price;
value += price;
artworkSaleCount++;
}
}
function averageArtworkSalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastArtworkSalePrices[i];
}
return sum / 5;
}
function getValue() external view returns (uint256) {
return value;
}
}
contract ArtworkAccessControl {
// This facet controls access control for CryptoArtworks. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the ArtworkCore constructor.
//
// - The CFO: The CFO can withdraw funds from ArtworkCore and its auction contracts.
//
// - The COO: The COO can release artworks to auction, and mint promo arts.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** 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);
_;
}
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for CryptoArtworks. Holds all common structs, events and base variables.
/// @dev See the ArtworkCore contract documentation to understand how the various contract facets are arranged.
contract ArtworkBase is ArtworkAccessControl {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new artwork comes into existence. This obviously
/// includes any time a artwork is created through the giveBirth method, but it is also called
/// when a new artwork is created.
event Birth(address owner, uint256 artworkId, string name, string author, uint32 series);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a artwork
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main Artwork struct. Every art in CryptoArtworks 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 Artwork {
// The timestamp from the block when this artwork came into existence.
uint64 birthTime;
// The name of the artwork
string name;
string author;
//sometimes artists produce a series of paintings with the same name
//in order to separate them from each other by introducing a variable series.
//Series with number 0 means that the picture was without series
uint32 series;
}
// An approximation of currently how many seconds are in between blocks.
// uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the Artwork struct for all Artworks in existence. The ID
/// of each artwork is actually an index into this array.
/// Artwork ID 0 is invalid... ;-)
Artwork[] internal artworks;
/// @dev A mapping from artwork IDs to the address that owns them. All artworks have
/// some valid owner address.
mapping (uint256 => address) public artworkIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) internal ownershipTokenCount;
/// @dev A mapping from artworkIDs to an address that has been approved to call
/// transferFrom(). Each Artwork can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public artworkIndexToApproved;
/// @dev The address of the ClockAuction contract that handles sales of Artworks. This
/// same contract handles both peer-to-peer sales as well as the initial sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev Assigns ownership of a specific Artwork to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of artworks is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
artworkIndexToOwner[_tokenId] = _to;
// When creating new artworks _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete artworkIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new artwork and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _id The artwork's genetic code.
/// @param _owner The inital owner of this art, must be non-zero (except for ID 0)
// The timestamp from the block when this artwork came into existence.
uint64 internal birthTime;
string internal author;
// The name of the artwork
string internal name;
uint32 internal series;
function _createArtwork(string _name, string _author, uint32 _series, address _owner ) internal returns (uint) {
Artwork memory _artwork = Artwork({ birthTime: uint64(now), name: _name, author: _author, series: _series});
uint256 newArtworkId = artworks.push(_artwork) - 1;
// It's probably never going to happen, 4 billion artworks is A LOT, but
// let's just be 100% sure we never let this happen.
require(newArtworkId == uint256(uint32(newArtworkId)));
// emit the birth event
Birth(_owner, newArtworkId, _artwork.name, _artwork.author, _series);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newArtworkId);
return newArtworkId;
}
}
// Creates dictionary with unique keys, if the key is already used then its value will be true.
// It is not possible to create a duplicate.
contract ArtworkUnique {
//mapping with unique key
mapping (bytes32 => bool) internal uniqueArtworks;
//Creates a unique key based on the artwork name, author, and series
function getUniqueKey(string name, string author, uint32 _version) internal pure returns(bytes32) {
string memory version = _uintToString(_version);
string memory main = _strConcat(name, author, version, "$%)");
string memory lowercased = _toLower(main);
return keccak256(lowercased);
}
//https://gist.github.com/thomasmaclean/276cb6e824e48b7ca4372b194ec05b97
//transform to lowercase
function _toLower(string str) internal pure returns (string) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character...
if ((bStr[i] >= 65) && (bStr[i] <= 90)) {
// So we add 32 to make it lowercase
bLower[i] = bytes1(int(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
//creates a unique key from all variables
function _strConcat(string _a, string _b, string _c, string _separator) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_separator);
bytes memory _bc = bytes(_b);
bytes memory _bd = bytes(_separator);
bytes memory _be = bytes(_c);
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);
}
//convert uint To String
function _uintToString(uint v) internal pure returns (string) {
bytes32 data = _uintToBytes(v);
return _bytes32ToString(data);
}
/// title String Utils - String utility functions
/// @author Piper Merriam - <[email protected]>
///https://github.com/pipermerriam/ethereum-string-utils
function _uintToBytes(uint v) private pure returns (bytes32 ret) {
if (v == 0) {
ret = "0";
} else {
while (v > 0) {
ret = bytes32(uint(ret) / (2 ** 8));
ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
v /= 10;
}
}
return ret;
}
function _bytes32ToString(bytes32 x) private pure returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
}
/// @title The facet of the CryptoArtworks core contract that manages ownership, ERC-721 (draft) compliant.
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the ArtworkCore contract documentation to understand how the various contract facets are arranged.
contract ArtworkOwnership is ArtworkBase, ArtworkUnique, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoArtworks";
string public constant SYMBOL = "CA";
// The contract that will return artwork metadata
ERC721Metadata public erc721Metadata;
bytes4 private constant INTERFACE_SIGNATURE_ERC165 =
bytes4(keccak256("supportsInterface(bytes4)"));
bytes4 private constant INTERFACE_SIGNATURE_ERC721 =
bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("transfer(address,uint256)")) ^
bytes4(keccak256("transferFrom(address,address,uint256)")) ^
bytes4(keccak256("tokensOfOwner(address)")) ^
bytes4(keccak256("tokenMetadata(uint256,string)"));
/// @notice Grant another address the right to transfer a specific Artwork via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Artwork that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Artwork owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Artwork to be transfered.
/// @param _to The address that should take ownership of the Artwork. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Artwork to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any artworks (except very briefly
// after a artwork is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Transfers a Artwork to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoArtworks specifically) or your Artwork may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Artwork to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _tokenId) external whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any Artworks (except very briefly
// after a artwork is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of artworks
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
// You can only send your own artwork.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Returns a list of all Artwork IDs assigned to an address.
/// @param _owner The owner whose Artworks we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Artwork array looking for arts 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 totalArts = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all arts have IDs starting at 1 and increasing
// sequentially up to the totalArt count.
uint256 artworkId;
for (artworkId = 1; artworkId <= totalArts; artworkId++) {
if (artworkIndexToOwner[artworkId] == _owner) {
result[resultIndex] = artworkId;
resultIndex++;
}
}
return result;
}
}
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool) {
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == INTERFACE_SIGNATURE_ERC165) || (_interfaceID == INTERFACE_SIGNATURE_ERC721));
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the Artwork whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
/// @notice Returns the address currently assigned ownership of a given Artwork.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId) external view returns (address owner) {
owner = artworkIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
/// @notice Returns the total number of Artworks currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return artworks.length - 1;
}
/// @notice Returns the number of Artworks owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Artwork.
/// @param _claimant the address we are validating against.
/// @param _tokenId artwork id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return artworkIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Artwork.
/// @param _claimant the address we are confirming artwork is approved for.
/// @param _tokenId artwork id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return artworkIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Artworks on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
artworkIndexToApproved[_tokenId] = _approved;
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chunks while possible
for (; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
}
/// @title Handles creating auctions for sale artworks.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract ArtworkAuction is ArtworkOwnership {
// @notice The auction contract variables are defined in ArtworkBase to allow
// us to refer to _createArtworkthem in ArtworkOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for created artworks and p2p sale of artworks.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect -
//https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Put a artwork up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _artworkId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If artwork is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _artworkId));
_approve(_artworkId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the artwork.
saleAuction.createAuction(
_artworkId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the ArtworkCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
}
}
/// @title all functions related to creating artworks
contract ArtworkMinting is ArtworkAuction {
// Limits the number of arts the contract owner can ever create.
uint256 public constant PROMO_CREATION_LIMIT = 5000;
uint256 public constant CREATION_LIMIT = 450000;
// Constants for auctions.
uint256 public constant ARTWORK_STARTING_PRICE = 10 finney;
uint256 public constant ARTWORK_AUCTION_DURATION = 1 days;
// Counts the number of arts the contract owner has created.
uint256 public promoCreatedCount;
uint256 public artsCreatedCount;
/// @dev we can create promo artworks, up to a limit. Only callable by COO
/// @param _owner the future owner of the created artworks. Default to contract COO
function createPromoArtwork(string _name, string _author, uint32 _series, address _owner) external onlyCOO {
bytes32 uniqueKey = getUniqueKey(_name, _author, _series);
(require(!uniqueArtworks[uniqueKey]));
if (_series != 0) {
bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0);
(require(!uniqueArtworks[uniqueKeyForZero]));
}
address artworkOwner = _owner;
if (artworkOwner == address(0)) {
artworkOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createArtwork(_name, _author, _series, artworkOwner);
uniqueArtworks[uniqueKey] = true;
}
/// @dev Creates a new artwork with the given name and author and
/// creates an auction for it.
function createArtworkAuction(string _name, string _author, uint32 _series) external onlyCOO {
bytes32 uniqueKey = getUniqueKey(_name, _author, _series);
(require(!uniqueArtworks[uniqueKey]));
require(artsCreatedCount < CREATION_LIMIT);
if (_series != 0) {
bytes32 uniqueKeyForZero = getUniqueKey(_name, _author, 0);
(require(!uniqueArtworks[uniqueKeyForZero]));
}
uint256 artworkId = _createArtwork(_name, _author, _series, address(this));
_approve(artworkId, saleAuction);
uint256 price = _computeNextArtworkPrice();
saleAuction.createAuction(
artworkId,
price,
0,
ARTWORK_AUCTION_DURATION,
address(this)
);
artsCreatedCount++;
uniqueArtworks[uniqueKey] = true;
}
/// @dev Computes the next gen0 auction starting price, given
/// the average of the past 5 prices + 50%.
function _computeNextArtworkPrice() internal view returns (uint256) {
uint256 avePrice = saleAuction.averageArtworkSalePrice();
// 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 < ARTWORK_STARTING_PRICE) {
nextPrice = ARTWORK_STARTING_PRICE;
}
return nextPrice;
}
}
/**
* The contractName contract does this and that...
*/
contract ArtworkQuestions is ArtworkMinting {
string private constant QUESTION = "What is the value? Nothing is ";
string public constant MAIN_QUESTION = "What is a masterpiece? ";
function getQuestion() public view returns (string) {
uint256 value = saleAuction.getValue();
string memory auctionValue = _uintToString(value);
return _strConcat(QUESTION, auctionValue, "", "");
}
}
/// @title CryptoArtworks: Collectible arts on the Ethereum blockchain.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev The main CryptoArtworks contract, keeps track of artworks so they don't wander around and get lost.
contract ArtworkCore is ArtworkQuestions {
// This is the main CryptoArtworks contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// artwork ownership. The genetic combination algorithm is kept seperate so we can open-source all of
// the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
// Don't worry, I'm sure someone will reverse engineer it soon enough!
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of CK. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - ArtworkBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - ArtworkAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - ArtworkOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - ArtworkAuctions: Here we have the public methods for auctioning or bidding on arts.
// The actual auction functionality is handled in contract
// for sales, while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - ArtworkMinting: This final facet contains the functionality we use for creating new arts.
// We can make up to 5000 "promo" arts that can be given away (especially important when
// the community is new), and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 450k arts.
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main CryptoArtworks smart contract instance.
function ArtworkCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// start with the art
_createArtwork("none", "none", 0, address(0));
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction)
);
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
cfoAddress.send(balance);
}
/// @notice Returns all the relevant information about a specific artwork.
/// @param _id The ID of the artwork of interest.
function getArtwork(uint256 _id)
external
view
returns (
uint256 birthTime,
string name,
string author,
uint32 series
) {
Artwork storage art = artworks[_id];
birthTime = uint256(art.birthTime);
name = string(art.name);
author = string(art.author);
series = uint32(art.series);
}
/// @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 onlyCEO whenPaused {
require(saleAuction != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
}
|
@dev Returns true if the NFT is on auction. @param _auction - Auction to check.
|
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
| 418,669 |
[
1,
1356,
638,
309,
326,
423,
4464,
353,
603,
279,
4062,
18,
225,
389,
69,
4062,
300,
432,
4062,
358,
866,
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
] |
[
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,
0
] |
[
1,
565,
445,
389,
291,
1398,
37,
4062,
12,
37,
4062,
2502,
389,
69,
4062,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
261,
67,
69,
4062,
18,
14561,
861,
405,
374,
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
] |
// 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 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.5.0 <0.8.0;
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/// Minimal contract to be inherited by contracts consumed by users that provide
/// data for fraud proofs
abstract contract Abs_FraudContributor is Lib_AddressResolver {
/// Decorate your functions with this modifier to store how much total gas was
/// consumed by the sender, to reward users fairly
modifier contributesToFraudProof(bytes32 preStateRoot, bytes32 txHash) {
uint256 startGas = gasleft();
_;
uint256 gasSpent = startGas - gasleft();
iOVM_BondManager(resolve('OVM_BondManager')).recordGasSpent(preStateRoot, txHash, msg.sender, gasSpent);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_EthUtils } from "../../libraries/utils/Lib_EthUtils.sol";
import { Lib_Bytes32Utils } from "../../libraries/utils/Lib_Bytes32Utils.sol";
import { Lib_BytesUtils } from "../../libraries/utils/Lib_BytesUtils.sol";
import { Lib_SecureMerkleTrie } from "../../libraries/trie/Lib_SecureMerkleTrie.sol";
import { Lib_RLPWriter } from "../../libraries/rlp/Lib_RLPWriter.sol";
import { Lib_RLPReader } from "../../libraries/rlp/Lib_RLPReader.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_BondManager } from "../../iOVM/verification/iOVM_BondManager.sol";
import { iOVM_ExecutionManager } from "../../iOVM/execution/iOVM_ExecutionManager.sol";
import { iOVM_StateManager } from "../../iOVM/execution/iOVM_StateManager.sol";
import { iOVM_StateManagerFactory } from "../../iOVM/execution/iOVM_StateManagerFactory.sol";
/* Contract Imports */
import { Abs_FraudContributor } from "./Abs_FraudContributor.sol";
/**
* @title OVM_StateTransitioner
* @dev The State Transitioner coordinates the execution of a state transition during the evaluation of a
* fraud proof. It feeds verified input to the Execution Manager's run(), and controls a State Manager (which is
* uniquely created for each fraud proof).
* Once a fraud proof has been initialized, this contract is provided with the pre-state root and verifies
* that the OVM storage slots committed to the State Mangager are contained in that state
* This contract controls the State Manager and Execution Manager, and uses them to calculate the
* post-state root by applying the transaction. The Fraud Verifier can then check for fraud by comparing
* the calculated post-state root with the proposed post-state root.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitioner is Lib_AddressResolver, Abs_FraudContributor, iOVM_StateTransitioner {
/*******************
* Data Structures *
*******************/
enum TransitionPhase {
PRE_EXECUTION,
POST_EXECUTION,
COMPLETE
}
/*******************************************
* Contract Variables: Contract References *
*******************************************/
iOVM_StateManager public ovmStateManager;
/*******************************************
* Contract Variables: Internal Accounting *
*******************************************/
bytes32 internal preStateRoot;
bytes32 internal postStateRoot;
TransitionPhase public phase;
uint256 internal stateTransitionIndex;
bytes32 internal transactionHash;
/*************
* Constants *
*************/
bytes32 internal constant EMPTY_ACCOUNT_CODE_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
bytes32 internal constant EMPTY_ACCOUNT_STORAGE_ROOT = 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
*/
constructor(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
Lib_AddressResolver(_libAddressManager)
{
stateTransitionIndex = _stateTransitionIndex;
preStateRoot = _preStateRoot;
postStateRoot = _preStateRoot;
transactionHash = _transactionHash;
ovmStateManager = iOVM_StateManagerFactory(resolve("OVM_StateManagerFactory")).create(address(this));
}
/**********************
* Function Modifiers *
**********************/
/**
* Checks that a function is only run during a specific phase.
* @param _phase Phase the function must run within.
*/
modifier onlyDuringPhase(
TransitionPhase _phase
) {
require(
phase == _phase,
"Function must be called during the correct phase."
);
_;
}
/**********************************
* Public Functions: State Access *
**********************************/
/**
* Retrieves the state root before execution.
* @return _preStateRoot State root before execution.
*/
function getPreStateRoot()
override
external
view
returns (
bytes32 _preStateRoot
)
{
return preStateRoot;
}
/**
* Retrieves the state root after execution.
* @return _postStateRoot State root after execution.
*/
function getPostStateRoot()
override
external
view
returns (
bytes32 _postStateRoot
)
{
return postStateRoot;
}
/**
* Checks whether the transitioner is complete.
* @return _complete Whether or not the transition process is finished.
*/
function isComplete()
override
external
view
returns (
bool _complete
)
{
return phase == TransitionPhase.COMPLETE;
}
/***********************************
* Public Functions: Pre-Execution *
***********************************/
/**
* Allows a user to prove the initial state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _ethContractAddress Address of the corresponding contract on L1.
* @param _stateTrieWitness Proof of the account state.
*/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
(
ovmStateManager.hasAccount(_ovmContractAddress) == false
&& ovmStateManager.hasEmptyAccount(_ovmContractAddress) == false
),
"Account state has already been proven."
);
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedAccount
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_ovmContractAddress),
_stateTrieWitness,
preStateRoot
);
if (exists == true) {
// Account exists, this was an inclusion proof.
Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(
encodedAccount
);
address ethContractAddress = _ethContractAddress;
if (account.codeHash == EMPTY_ACCOUNT_CODE_HASH) {
// Use a known empty contract to prevent an attack in which a user provides a
// contract address here and then later deploys code to it.
ethContractAddress = 0x0000000000000000000000000000000000000000;
} else {
// Otherwise, make sure that the code at the provided eth address matches the hash
// of the code stored on L2.
require(
Lib_EthUtils.getCodeHash(ethContractAddress) == account.codeHash,
"OVM_StateTransitioner: Provided L1 contract code hash does not match L2 contract code hash."
);
}
ovmStateManager.putAccount(
_ovmContractAddress,
Lib_OVMCodec.Account({
nonce: account.nonce,
balance: account.balance,
storageRoot: account.storageRoot,
codeHash: account.codeHash,
ethAddress: ethContractAddress,
isFresh: false
})
);
} else {
// Account does not exist, this was an exclusion proof.
ovmStateManager.putEmptyAccount(_ovmContractAddress);
}
}
/**
* Allows a user to prove the initial state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
// Exit quickly to avoid unnecessary work.
require(
ovmStateManager.hasContractStorage(_ovmContractAddress, _key) == false,
"Storage slot has already been proven."
);
require(
ovmStateManager.hasAccount(_ovmContractAddress) == true,
"Contract must be verified before proving a storage slot."
);
bytes32 storageRoot = ovmStateManager.getAccountStorageRoot(_ovmContractAddress);
bytes32 value;
if (storageRoot == EMPTY_ACCOUNT_STORAGE_ROOT) {
// Storage trie was empty, so the user is always allowed to insert zero-byte values.
value = bytes32(0);
} else {
// Function will fail if the proof is not a valid inclusion or exclusion proof.
(
bool exists,
bytes memory encodedValue
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(_key),
_storageTrieWitness,
storageRoot
);
if (exists == true) {
// Inclusion proof.
// Stored values are RLP encoded, with leading zeros removed.
value = Lib_BytesUtils.toBytes32PadLeft(
Lib_RLPReader.readBytes(encodedValue)
);
} else {
// Exclusion proof, can only be zero bytes.
value = bytes32(0);
}
}
ovmStateManager.putContractStorage(
_ovmContractAddress,
_key,
value
);
}
/*******************************
* Public Functions: Execution *
*******************************/
/**
* Executes the state transition.
* @param _transaction OVM transaction to execute.
*/
function applyTransaction(
Lib_OVMCodec.Transaction memory _transaction
)
override
external
onlyDuringPhase(TransitionPhase.PRE_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
Lib_OVMCodec.hashTransaction(_transaction) == transactionHash,
"Invalid transaction provided."
);
// We require gas to complete the logic here in run() before/after execution,
// But must ensure the full _tx.gasLimit can be given to the ovmCALL (determinism)
// This includes 1/64 of the gas getting lost because of EIP-150 (lost twice--first
// going into EM, then going into the code contract).
require(
gasleft() >= 100000 + _transaction.gasLimit * 1032 / 1000, // 1032/1000 = 1.032 = (64/63)^2 rounded up
"Not enough gas to execute transaction deterministically."
);
iOVM_ExecutionManager ovmExecutionManager = iOVM_ExecutionManager(resolve("OVM_ExecutionManager"));
// We call `setExecutionManager` right before `run` (and not earlier) just in case the
// OVM_ExecutionManager address was updated between the time when this contract was created
// and when `applyTransaction` was called.
ovmStateManager.setExecutionManager(address(ovmExecutionManager));
// `run` always succeeds *unless* the user hasn't provided enough gas to `applyTransaction`
// or an INVALID_STATE_ACCESS flag was triggered. Either way, we won't get beyond this line
// if that's the case.
ovmExecutionManager.run(_transaction, address(ovmStateManager));
// Prevent the Execution Manager from calling this SM again.
ovmStateManager.setExecutionManager(address(0));
phase = TransitionPhase.POST_EXECUTION;
}
/************************************
* Public Functions: Post-Execution *
************************************/
/**
* Allows a user to commit the final state of a contract.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _stateTrieWitness Proof of the account state.
*/
function commitContractState(
address _ovmContractAddress,
bytes memory _stateTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before committing account states."
);
require (
ovmStateManager.commitAccount(_ovmContractAddress) == true,
"Account state wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
postStateRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_ovmContractAddress),
Lib_OVMCodec.encodeEVMAccount(
Lib_OVMCodec.toEVMAccount(account)
),
_stateTrieWitness,
postStateRoot
);
// Emit an event to help clients figure out the proof ordering.
emit AccountCommitted(
_ovmContractAddress
);
}
/**
* Allows a user to commit the final state of a contract storage slot.
* @param _ovmContractAddress Address of the contract on the OVM.
* @param _key Claimed account slot key.
* @param _storageTrieWitness Proof of the storage slot.
*/
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes memory _storageTrieWitness
)
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
contributesToFraudProof(preStateRoot, transactionHash)
{
require(
ovmStateManager.commitContractStorage(_ovmContractAddress, _key) == true,
"Storage slot value wasn't changed or has already been committed."
);
Lib_OVMCodec.Account memory account = ovmStateManager.getAccount(_ovmContractAddress);
bytes32 value = ovmStateManager.getContractStorage(_ovmContractAddress, _key);
account.storageRoot = Lib_SecureMerkleTrie.update(
abi.encodePacked(_key),
Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(value)
),
_storageTrieWitness,
account.storageRoot
);
ovmStateManager.putAccount(_ovmContractAddress, account);
// Emit an event to help clients figure out the proof ordering.
emit ContractStorageCommitted(
_ovmContractAddress,
_key
);
}
/**********************************
* Public Functions: Finalization *
**********************************/
/**
* Finalizes the transition process.
*/
function completeTransition()
override
external
onlyDuringPhase(TransitionPhase.POST_EXECUTION)
{
require(
ovmStateManager.getTotalUncommittedAccounts() == 0,
"All accounts must be committed before completing a transition."
);
require(
ovmStateManager.getTotalUncommittedContractStorage() == 0,
"All storage must be committed before completing a transition."
);
phase = TransitionPhase.COMPLETE;
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressResolver } from "../../libraries/resolver/Lib_AddressResolver.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "../../iOVM/verification/iOVM_StateTransitioner.sol";
import { iOVM_StateTransitionerFactory } from "../../iOVM/verification/iOVM_StateTransitionerFactory.sol";
import { iOVM_FraudVerifier } from "../../iOVM/verification/iOVM_FraudVerifier.sol";
/* Contract Imports */
import { OVM_StateTransitioner } from "./OVM_StateTransitioner.sol";
/**
* @title OVM_StateTransitionerFactory
* @dev The State Transitioner Factory is used by the Fraud Verifier to create a new State
* Transitioner during the initialization of a fraud proof.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_StateTransitionerFactory is iOVM_StateTransitionerFactory, Lib_AddressResolver {
/***************
* Constructor *
***************/
constructor(
address _libAddressManager
)
Lib_AddressResolver(_libAddressManager)
{}
/********************
* Public Functions *
********************/
/**
* Creates a new OVM_StateTransitioner
* @param _libAddressManager Address of the Address Manager.
* @param _stateTransitionIndex Index of the state transition being verified.
* @param _preStateRoot State root before the transition was executed.
* @param _transactionHash Hash of the executed transaction.
* @return New OVM_StateTransitioner instance.
*/
function create(
address _libAddressManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
override
public
returns (
iOVM_StateTransitioner
)
{
require(
msg.sender == resolve("OVM_FraudVerifier"),
"Create can only be done by the OVM_FraudVerifier."
);
return new OVM_StateTransitioner(
_libAddressManager,
_stateTransitionIndex,
_preStateRoot,
_transactionHash
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
interface iOVM_ExecutionManager {
/**********
* Enums *
*********/
enum RevertFlag {
OUT_OF_GAS,
INTENTIONAL_REVERT,
EXCEEDS_NUISANCE_GAS,
INVALID_STATE_ACCESS,
UNSAFE_BYTECODE,
CREATE_COLLISION,
STATIC_VIOLATION,
CREATOR_NOT_ALLOWED
}
enum GasMetadataKey {
CURRENT_EPOCH_START_TIMESTAMP,
CUMULATIVE_SEQUENCER_QUEUE_GAS,
CUMULATIVE_L1TOL2_QUEUE_GAS,
PREV_EPOCH_SEQUENCER_QUEUE_GAS,
PREV_EPOCH_L1TOL2_QUEUE_GAS
}
/***********
* Structs *
***********/
struct GasMeterConfig {
uint256 minTransactionGasLimit;
uint256 maxTransactionGasLimit;
uint256 maxGasPerQueuePerEpoch;
uint256 secondsPerEpoch;
}
struct GlobalContext {
uint256 ovmCHAINID;
}
struct TransactionContext {
Lib_OVMCodec.QueueOrigin ovmL1QUEUEORIGIN;
uint256 ovmTIMESTAMP;
uint256 ovmNUMBER;
uint256 ovmGASLIMIT;
uint256 ovmTXGASLIMIT;
address ovmL1TXORIGIN;
}
struct TransactionRecord {
uint256 ovmGasRefund;
}
struct MessageContext {
address ovmCALLER;
address ovmADDRESS;
bool isStatic;
}
struct MessageRecord {
uint256 nuisanceGasLeft;
}
/************************************
* Transaction Execution Entrypoint *
************************************/
function run(
Lib_OVMCodec.Transaction calldata _transaction,
address _txStateManager
) external returns (bytes memory);
/*******************
* Context Opcodes *
*******************/
function ovmCALLER() external view returns (address _caller);
function ovmADDRESS() external view returns (address _address);
function ovmTIMESTAMP() external view returns (uint256 _timestamp);
function ovmNUMBER() external view returns (uint256 _number);
function ovmGASLIMIT() external view returns (uint256 _gasLimit);
function ovmCHAINID() external view returns (uint256 _chainId);
/**********************
* L2 Context Opcodes *
**********************/
function ovmL1QUEUEORIGIN() external view returns (Lib_OVMCodec.QueueOrigin _queueOrigin);
function ovmL1TXORIGIN() external view returns (address _l1TxOrigin);
/*******************
* Halting Opcodes *
*******************/
function ovmREVERT(bytes memory _data) external;
/*****************************
* Contract Creation Opcodes *
*****************************/
function ovmCREATE(bytes memory _bytecode) external returns (address _contract, bytes memory _revertdata);
function ovmCREATE2(bytes memory _bytecode, bytes32 _salt) external returns (address _contract, bytes memory _revertdata);
/*******************************
* Account Abstraction Opcodes *
******************************/
function ovmGETNONCE() external returns (uint256 _nonce);
function ovmINCREMENTNONCE() external;
function ovmCREATEEOA(bytes32 _messageHash, uint8 _v, bytes32 _r, bytes32 _s) external;
/****************************
* Contract Calling Opcodes *
****************************/
function ovmCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);
function ovmSTATICCALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);
function ovmDELEGATECALL(uint256 _gasLimit, address _address, bytes memory _calldata) external returns (bool _success, bytes memory _returndata);
/****************************
* Contract Storage Opcodes *
****************************/
function ovmSLOAD(bytes32 _key) external returns (bytes32 _value);
function ovmSSTORE(bytes32 _key, bytes32 _value) external;
/*************************
* Contract Code Opcodes *
*************************/
function ovmEXTCODECOPY(address _contract, uint256 _offset, uint256 _length) external returns (bytes memory _code);
function ovmEXTCODESIZE(address _contract) external returns (uint256 _size);
function ovmEXTCODEHASH(address _contract) external returns (bytes32 _hash);
/***************************************
* Public Functions: Execution Context *
***************************************/
function getMaxTransactionGasLimit() external view returns (uint _maxTransactionGasLimit);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateManager
*/
interface iOVM_StateManager {
/*******************
* Data Structures *
*******************/
enum ItemState {
ITEM_UNTOUCHED,
ITEM_LOADED,
ITEM_CHANGED,
ITEM_COMMITTED
}
/***************************
* Public Functions: Misc *
***************************/
function isAuthenticated(address _address) external view returns (bool);
/***************************
* Public Functions: Setup *
***************************/
function owner() external view returns (address _owner);
function ovmExecutionManager() external view returns (address _ovmExecutionManager);
function setExecutionManager(address _ovmExecutionManager) external;
/************************************
* Public Functions: Account Access *
************************************/
function putAccount(address _address, Lib_OVMCodec.Account memory _account) external;
function putEmptyAccount(address _address) external;
function getAccount(address _address) external view returns (Lib_OVMCodec.Account memory _account);
function hasAccount(address _address) external view returns (bool _exists);
function hasEmptyAccount(address _address) external view returns (bool _exists);
function setAccountNonce(address _address, uint256 _nonce) external;
function getAccountNonce(address _address) external view returns (uint256 _nonce);
function getAccountEthAddress(address _address) external view returns (address _ethAddress);
function getAccountStorageRoot(address _address) external view returns (bytes32 _storageRoot);
function initPendingAccount(address _address) external;
function commitPendingAccount(address _address, address _ethAddress, bytes32 _codeHash) external;
function testAndSetAccountLoaded(address _address) external returns (bool _wasAccountAlreadyLoaded);
function testAndSetAccountChanged(address _address) external returns (bool _wasAccountAlreadyChanged);
function commitAccount(address _address) external returns (bool _wasAccountCommitted);
function incrementTotalUncommittedAccounts() external;
function getTotalUncommittedAccounts() external view returns (uint256 _total);
function wasAccountChanged(address _address) external view returns (bool);
function wasAccountCommitted(address _address) external view returns (bool);
/************************************
* Public Functions: Storage Access *
************************************/
function putContractStorage(address _contract, bytes32 _key, bytes32 _value) external;
function getContractStorage(address _contract, bytes32 _key) external view returns (bytes32 _value);
function hasContractStorage(address _contract, bytes32 _key) external view returns (bool _exists);
function testAndSetContractStorageLoaded(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyLoaded);
function testAndSetContractStorageChanged(address _contract, bytes32 _key) external returns (bool _wasContractStorageAlreadyChanged);
function commitContractStorage(address _contract, bytes32 _key) external returns (bool _wasContractStorageCommitted);
function incrementTotalUncommittedContractStorage() external;
function getTotalUncommittedContractStorage() external view returns (uint256 _total);
function wasContractStorageChanged(address _contract, bytes32 _key) external view returns (bool);
function wasContractStorageCommitted(address _contract, bytes32 _key) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateManager } from "./iOVM_StateManager.sol";
/**
* @title iOVM_StateManagerFactory
*/
interface iOVM_StateManagerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _owner
)
external
returns (
iOVM_StateManager _ovmStateManager
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
interface ERC20 {
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
}
/// All the errors which may be encountered on the bond manager
library Errors {
string constant ERC20_ERR = "BondManager: Could not post bond";
string constant ALREADY_FINALIZED = "BondManager: Fraud proof for this pre-state root has already been finalized";
string constant SLASHED = "BondManager: Cannot finalize withdrawal, you probably got slashed";
string constant WRONG_STATE = "BondManager: Wrong bond state for proposer";
string constant CANNOT_CLAIM = "BondManager: Cannot claim yet. Dispute must be finalized first";
string constant WITHDRAWAL_PENDING = "BondManager: Withdrawal already pending";
string constant TOO_EARLY = "BondManager: Too early to finalize your withdrawal";
string constant ONLY_TRANSITIONER = "BondManager: Only the transitioner for this pre-state root may call this function";
string constant ONLY_FRAUD_VERIFIER = "BondManager: Only the fraud verifier may call this function";
string constant ONLY_STATE_COMMITMENT_CHAIN = "BondManager: Only the state commitment chain may call this function";
string constant WAIT_FOR_DISPUTES = "BondManager: Wait for other potential disputes";
}
/**
* @title iOVM_BondManager
*/
interface iOVM_BondManager {
/*******************
* Data Structures *
*******************/
/// The lifecycle of a proposer's bond
enum State {
// Before depositing or after getting slashed, a user is uncollateralized
NOT_COLLATERALIZED,
// After depositing, a user is collateralized
COLLATERALIZED,
// After a user has initiated a withdrawal
WITHDRAWING
}
/// A bond posted by a proposer
struct Bond {
// The user's state
State state;
// The timestamp at which a proposer issued their withdrawal request
uint32 withdrawalTimestamp;
// The time when the first disputed was initiated for this bond
uint256 firstDisputeAt;
// The earliest observed state root for this bond which has had fraud
bytes32 earliestDisputedStateRoot;
// The state root's timestamp
uint256 earliestTimestamp;
}
// Per pre-state root, store the number of state provisions that were made
// and how many of these calls were made by each user. Payouts will then be
// claimed by users proportionally for that dispute.
struct Rewards {
// Flag to check if rewards for a fraud proof are claimable
bool canClaim;
// Total number of `recordGasSpent` calls made
uint256 total;
// The gas spent by each user to provide witness data. The sum of all
// values inside this map MUST be equal to the value of `total`
mapping(address => uint256) gasSpent;
}
/********************
* Public Functions *
********************/
function recordGasSpent(
bytes32 _preStateRoot,
bytes32 _txHash,
address _who,
uint256 _gasSpent
) external;
function finalize(
bytes32 _preStateRoot,
address _publisher,
uint256 _timestamp
) external;
function deposit() external;
function startWithdrawal() external;
function finalizeWithdrawal() external;
function claim(
address _who
) external;
function isCollateralized(
address _who
) external view returns (bool);
function getGasSpent(
bytes32 _preStateRoot,
address _who
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_FraudVerifier
*/
interface iOVM_FraudVerifier {
/**********
* Events *
**********/
event FraudProofInitialized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
event FraudProofFinalized(
bytes32 _preStateRoot,
uint256 _preStateRootIndex,
bytes32 _transactionHash,
address _who
);
/***************************************
* Public Functions: Transition Status *
***************************************/
function getStateTransitioner(bytes32 _preStateRoot, bytes32 _txHash) external view returns (iOVM_StateTransitioner _transitioner);
/****************************************
* Public Functions: Fraud Verification *
****************************************/
function initializeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
Lib_OVMCodec.Transaction calldata _transaction,
Lib_OVMCodec.TransactionChainElement calldata _txChainElement,
Lib_OVMCodec.ChainBatchHeader calldata _transactionBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _transactionProof
) external;
function finalizeFraudVerification(
bytes32 _preStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _preStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _preStateRootProof,
bytes32 _txHash,
bytes32 _postStateRoot,
Lib_OVMCodec.ChainBatchHeader calldata _postStateRootBatchHeader,
Lib_OVMCodec.ChainInclusionProof calldata _postStateRootProof
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateTransitioner
*/
interface iOVM_StateTransitioner {
/**********
* Events *
**********/
event AccountCommitted(
address _address
);
event ContractStorageCommitted(
address _address,
bytes32 _key
);
/**********************************
* Public Functions: State Access *
**********************************/
function getPreStateRoot() external view returns (bytes32 _preStateRoot);
function getPostStateRoot() external view returns (bytes32 _postStateRoot);
function isComplete() external view returns (bool _complete);
/***********************************
* Public Functions: Pre-Execution *
***********************************/
function proveContractState(
address _ovmContractAddress,
address _ethContractAddress,
bytes calldata _stateTrieWitness
) external;
function proveStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/*******************************
* Public Functions: Execution *
*******************************/
function applyTransaction(
Lib_OVMCodec.Transaction calldata _transaction
) external;
/************************************
* Public Functions: Post-Execution *
************************************/
function commitContractState(
address _ovmContractAddress,
bytes calldata _stateTrieWitness
) external;
function commitStorageSlot(
address _ovmContractAddress,
bytes32 _key,
bytes calldata _storageTrieWitness
) external;
/**********************************
* Public Functions: Finalization *
**********************************/
function completeTransition() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Contract Imports */
import { iOVM_StateTransitioner } from "./iOVM_StateTransitioner.sol";
/**
* @title iOVM_StateTransitionerFactory
*/
interface iOVM_StateTransitionerFactory {
/***************************************
* Public Functions: Contract Creation *
***************************************/
function create(
address _proxyManager,
uint256 _stateTransitionIndex,
bytes32 _preStateRoot,
bytes32 _transactionHash
)
external
returns (
iOVM_StateTransitioner _ovmStateTransitioner
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string _name,
address _newAddress
);
/*************
* Variables *
*************/
mapping (bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(
string memory _name,
address _address
)
external
onlyOwner
{
addresses[_getNameHash(_name)] = _address;
emit AddressSet(
_name,
_address
);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(
string memory _name
)
external
view
returns (
address
)
{
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(
string memory _name
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_name));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(
string memory _name
)
public
view
returns (
address
)
{
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a bytes32 value.
* @param _in The bytes32 to encode.
* @return _out The RLP encoded bytes32 in bytes.
*/
function writeBytes32(
bytes32 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
/**
* @title Lib_MerkleTrie
*/
library Lib_MerkleTrie {
/*******************
* Data Structures *
*******************/
enum NodeType {
BranchNode,
ExtensionNode,
LeafNode
}
struct TrieNode {
bytes encoded;
Lib_RLPReader.RLPItem[] decoded;
}
/**********************
* Contract Constants *
**********************/
// TREE_RADIX determines the number of elements per branch node.
uint256 constant TREE_RADIX = 16;
// Branch nodes have TREE_RADIX elements plus an additional `value` slot.
uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;
// Leaf nodes and extension nodes always have two elements, a `path` and a `value`.
uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
// Prefixes are prepended to the `path` within a leaf or extension node and
// allow us to differentiate between the two node types. `ODD` or `EVEN` is
// determined by the number of nibbles within the unprefixed `path`. If the
// number of nibbles if even, we need to insert an extra padding nibble so
// the resulting prefixed `path` has an even number of nibbles.
uint8 constant PREFIX_EXTENSION_EVEN = 0;
uint8 constant PREFIX_EXTENSION_ODD = 1;
uint8 constant PREFIX_LEAF_EVEN = 2;
uint8 constant PREFIX_LEAF_ODD = 3;
// Just a utility constant. RLP represents `NULL` as 0x80.
bytes1 constant RLP_NULL = bytes1(0x80);
bytes constant RLP_NULL_BYTES = hex'80';
bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES);
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
(
bool exists,
bytes memory value
) = get(_key, _proof, _root);
return (
exists && Lib_BytesUtils.equal(_value, value)
);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
// Special case when inserting the very first node.
if (_root == KECCAK256_RLP_NULL_BYTES) {
return getSingleNodeRootHash(_key, _value);
}
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root);
TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value);
return _getUpdatedTrieRoot(newPath, _key);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root);
bool exists = keyRemainder.length == 0;
require(
exists || isFinalNode,
"Provided proof is invalid."
);
bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes('');
return (
exists,
value
);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
return keccak256(_makeLeafNode(
Lib_BytesUtils.toNibbles(_key),
_value
).encoded);
}
/*********************
* Private Functions *
*********************/
/**
* @notice Walks through a proof using a provided key.
* @param _proof Inclusion proof to walk through.
* @param _key Key to use for the walk.
* @param _root Known root of the trie.
* @return _pathLength Length of the final path
* @return _keyRemainder Portion of the key remaining after the walk.
* @return _isFinalNode Whether or not we've hit a dead end.
*/
function _walkNodePath(
TrieNode[] memory _proof,
bytes memory _key,
bytes32 _root
)
private
pure
returns (
uint256 _pathLength,
bytes memory _keyRemainder,
bool _isFinalNode
)
{
uint256 pathLength = 0;
bytes memory key = Lib_BytesUtils.toNibbles(_key);
bytes32 currentNodeID = _root;
uint256 currentKeyIndex = 0;
uint256 currentKeyIncrement = 0;
TrieNode memory currentNode;
// Proof is top-down, so we start at the first element (root).
for (uint256 i = 0; i < _proof.length; i++) {
currentNode = _proof[i];
currentKeyIndex += currentKeyIncrement;
// Keep track of the proof elements we actually need.
// It's expensive to resize arrays, so this simply reduces gas costs.
pathLength += 1;
if (currentKeyIndex == 0) {
// First proof element is always the root node.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid root hash"
);
} else if (currentNode.encoded.length >= 32) {
// Nodes 32 bytes or larger are hashed inside branch nodes.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid large internal hash"
);
} else {
// Nodes smaller than 31 bytes aren't hashed.
require(
Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID,
"Invalid internal node hash"
);
}
if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {
if (currentKeyIndex == key.length) {
// We've hit the end of the key, meaning the value should be within this branch node.
break;
} else {
// We're not at the end of the key yet.
// Figure out what the next node ID should be and continue.
uint8 branchKey = uint8(key[currentKeyIndex]);
Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];
currentNodeID = _getNodeID(nextNode);
currentKeyIncrement = 1;
continue;
}
} else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(currentNode);
uint8 prefix = uint8(path[0]);
uint8 offset = 2 - prefix % 2;
bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset);
bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex);
uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
if (
pathRemainder.length == sharedNibbleLength &&
keyRemainder.length == sharedNibbleLength
) {
// The key within this leaf matches our key exactly.
// Increment the key index to reflect that we have no remainder.
currentKeyIndex += sharedNibbleLength;
}
// We've hit a leaf node, so our next node should be NULL.
currentNodeID = bytes32(RLP_NULL);
break;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
if (sharedNibbleLength != pathRemainder.length) {
// Our extension node is not identical to the remainder.
// We've hit the end of this path, updates will need to modify this extension.
currentNodeID = bytes32(RLP_NULL);
break;
} else {
// Our extension shares some nibbles.
// Carry on to the next node.
currentNodeID = _getNodeID(currentNode.decoded[1]);
currentKeyIncrement = sharedNibbleLength;
continue;
}
} else {
revert("Received a node with an unknown prefix");
}
} else {
revert("Received an unparseable node.");
}
}
// If our node ID is NULL, then we're at a dead end.
bool isFinalNode = currentNodeID == bytes32(RLP_NULL);
return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode);
}
/**
* @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path.
* @param _path Path to the node nearest the k/v pair.
* @param _pathLength Length of the path. Necessary because the provided path may include
* additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory
* arrays without costly duplication.
* @param _key Full original key.
* @param _keyRemainder Portion of the initial key that must be inserted into the trie.
* @param _value Value to insert at the given key.
* @return _newPath A new path with the inserted k/v pair and extra supporting nodes.
*/
function _getNewPath(
TrieNode[] memory _path,
uint256 _pathLength,
bytes memory _key,
bytes memory _keyRemainder,
bytes memory _value
)
private
pure
returns (
TrieNode[] memory _newPath
)
{
bytes memory keyRemainder = _keyRemainder;
// Most of our logic depends on the status of the last node in the path.
TrieNode memory lastNode = _path[_pathLength - 1];
NodeType lastNodeType = _getNodeType(lastNode);
// Create an array for newly created nodes.
// We need up to three new nodes, depending on the contents of the last node.
// Since array resizing is expensive, we'll keep track of the size manually.
// We're using an explicit `totalNewNodes += 1` after insertions for clarity.
TrieNode[] memory newNodes = new TrieNode[](3);
uint256 totalNewNodes = 0;
// Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313
bool matchLeaf = false;
if (lastNodeType == NodeType.LeafNode) {
uint256 l = 0;
if (_path.length > 0) {
for (uint256 i = 0; i < _path.length - 1; i++) {
if (_getNodeType(_path[i]) == NodeType.BranchNode) {
l++;
} else {
l += _getNodeKey(_path[i]).length;
}
}
}
if (
_getSharedNibbleLength(
_getNodeKey(lastNode),
Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l)
) == _getNodeKey(lastNode).length
&& keyRemainder.length == 0
) {
matchLeaf = true;
}
}
if (matchLeaf) {
// We've found a leaf node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value);
totalNewNodes += 1;
} else if (lastNodeType == NodeType.BranchNode) {
if (keyRemainder.length == 0) {
// We've found a branch node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _editBranchValue(lastNode, _value);
totalNewNodes += 1;
} else {
// We've found a branch node, but it doesn't contain our key.
// Reinsert the old branch for now.
newNodes[totalNewNodes] = lastNode;
totalNewNodes += 1;
// Create a new leaf node, slicing our remainder since the first byte points
// to our branch node.
newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value);
totalNewNodes += 1;
}
} else {
// Our last node is either an extension node or a leaf node with a different key.
bytes memory lastNodeKey = _getNodeKey(lastNode);
uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder);
if (sharedNibbleLength != 0) {
// We've got some shared nibbles between the last node and our key remainder.
// We'll need to insert an extension node that covers these shared nibbles.
bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength);
newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value));
totalNewNodes += 1;
// Cut down the keys since we've just covered these shared nibbles.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength);
keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength);
}
// Create an empty branch to fill in.
TrieNode memory newBranch = _makeEmptyBranchNode();
if (lastNodeKey.length == 0) {
// Key remainder was larger than the key for our last node.
// The value within our last node is therefore going to be shifted into
// a branch value slot.
newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode));
} else {
// Last node key was larger than the key remainder.
// We're going to modify some index of our branch.
uint8 branchKey = uint8(lastNodeKey[0]);
// Move on to the next nibble.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1);
if (lastNodeType == NodeType.LeafNode) {
// We're dealing with a leaf node.
// We'll modify the key and insert the old leaf node into the branch index.
TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode));
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));
} else if (lastNodeKey.length != 0) {
// We're dealing with a shrinking extension node.
// We need to modify the node to decrease the size of the key.
TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode));
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));
} else {
// We're dealing with an unnecessary extension node.
// We're going to delete the node entirely.
// Simply insert its current value into the branch index.
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode));
}
}
if (keyRemainder.length == 0) {
// We've got nothing left in the key remainder.
// Simply insert the value into the branch value slot.
newBranch = _editBranchValue(newBranch, _value);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
} else {
// We've got some key remainder to work with.
// We'll be inserting a leaf node into the trie.
// First, move on to the next nibble.
keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
// Push a new leaf node for our k/v pair.
newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value);
totalNewNodes += 1;
}
}
// Finally, join the old path with our newly created nodes.
// Since we're overwriting the last node in the path, we use `_pathLength - 1`.
return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes);
}
/**
* @notice Computes the trie root from a given path.
* @param _nodes Path to some k/v pair.
* @param _key Key for the k/v pair.
* @return _updatedRoot Root hash for the updated trie.
*/
function _getUpdatedTrieRoot(
TrieNode[] memory _nodes,
bytes memory _key
)
private
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = Lib_BytesUtils.toNibbles(_key);
// Some variables to keep track of during iteration.
TrieNode memory currentNode;
NodeType currentNodeType;
bytes memory previousNodeHash;
// Run through the path backwards to rebuild our root hash.
for (uint256 i = _nodes.length; i > 0; i--) {
// Pick out the current node.
currentNode = _nodes[i - 1];
currentNodeType = _getNodeType(currentNode);
if (currentNodeType == NodeType.LeafNode) {
// Leaf nodes are already correctly encoded.
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
} else if (currentNodeType == NodeType.ExtensionNode) {
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
currentNode = _editExtensionNodeValue(currentNode, previousNodeHash);
}
} else if (currentNodeType == NodeType.BranchNode) {
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
uint8 branchKey = uint8(key[key.length - 1]);
key = Lib_BytesUtils.slice(key, 0, key.length - 1);
currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash);
}
}
// Compute the node hash for the next iteration.
previousNodeHash = _getNodeHash(currentNode.encoded);
}
// Current node should be the root at this point.
// Simply return the hash of its encoding.
return keccak256(currentNode.encoded);
}
/**
* @notice Parses an RLP-encoded proof into something more useful.
* @param _proof RLP-encoded proof to parse.
* @return _parsed Proof parsed into easily accessible structs.
*/
function _parseProof(
bytes memory _proof
)
private
pure
returns (
TrieNode[] memory _parsed
)
{
Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof);
TrieNode[] memory proof = new TrieNode[](nodes.length);
for (uint256 i = 0; i < nodes.length; i++) {
bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]);
proof[i] = TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
return proof;
}
/**
* @notice Picks out the ID for a node. Node ID is referred to as the
* "hash" within the specification, but nodes < 32 bytes are not actually
* hashed.
* @param _node Node to pull an ID for.
* @return _nodeID ID for the node, depending on the size of its contents.
*/
function _getNodeID(
Lib_RLPReader.RLPItem memory _node
)
private
pure
returns (
bytes32 _nodeID
)
{
bytes memory nodeID;
if (_node.length < 32) {
// Nodes smaller than 32 bytes are RLP encoded.
nodeID = Lib_RLPReader.readRawBytes(_node);
} else {
// Nodes 32 bytes or larger are hashed.
nodeID = Lib_RLPReader.readBytes(_node);
}
return Lib_BytesUtils.toBytes32(nodeID);
}
/**
* @notice Gets the path for a leaf or extension node.
* @param _node Node to get a path for.
* @return _path Node path, converted to an array of nibbles.
*/
function _getNodePath(
TrieNode memory _node
)
private
pure
returns (
bytes memory _path
)
{
return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0]));
}
/**
* @notice Gets the key for a leaf or extension node. Keys are essentially
* just paths without any prefix.
* @param _node Node to get a key for.
* @return _key Node key, converted to an array of nibbles.
*/
function _getNodeKey(
TrieNode memory _node
)
private
pure
returns (
bytes memory _key
)
{
return _removeHexPrefix(_getNodePath(_node));
}
/**
* @notice Gets the path for a node.
* @param _node Node to get a value for.
* @return _value Node value, as hex bytes.
*/
function _getNodeValue(
TrieNode memory _node
)
private
pure
returns (
bytes memory _value
)
{
return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]);
}
/**
* @notice Computes the node hash for an encoded node. Nodes < 32 bytes
* are not hashed, all others are keccak256 hashed.
* @param _encoded Encoded node to hash.
* @return _hash Hash of the encoded node. Simply the input if < 32 bytes.
*/
function _getNodeHash(
bytes memory _encoded
)
private
pure
returns (
bytes memory _hash
)
{
if (_encoded.length < 32) {
return _encoded;
} else {
return abi.encodePacked(keccak256(_encoded));
}
}
/**
* @notice Determines the type for a given node.
* @param _node Node to determine a type for.
* @return _type Type of the node; BranchNode/ExtensionNode/LeafNode.
*/
function _getNodeType(
TrieNode memory _node
)
private
pure
returns (
NodeType _type
)
{
if (_node.decoded.length == BRANCH_NODE_LENGTH) {
return NodeType.BranchNode;
} else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(_node);
uint8 prefix = uint8(path[0]);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
return NodeType.LeafNode;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
return NodeType.ExtensionNode;
}
}
revert("Invalid node type");
}
/**
* @notice Utility; determines the number of nibbles shared between two
* nibble arrays.
* @param _a First nibble array.
* @param _b Second nibble array.
* @return _shared Number of shared nibbles.
*/
function _getSharedNibbleLength(
bytes memory _a,
bytes memory _b
)
private
pure
returns (
uint256 _shared
)
{
uint256 i = 0;
while (_a.length > i && _b.length > i && _a[i] == _b[i]) {
i++;
}
return i;
}
/**
* @notice Utility; converts an RLP-encoded node into our nice struct.
* @param _raw RLP-encoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
bytes[] memory _raw
)
private
pure
returns (
TrieNode memory _node
)
{
bytes memory encoded = Lib_RLPWriter.writeList(_raw);
return TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
/**
* @notice Utility; converts an RLP-decoded node into our nice struct.
* @param _items RLP-decoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
Lib_RLPReader.RLPItem[] memory _items
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](_items.length);
for (uint256 i = 0; i < _items.length; i++) {
raw[i] = Lib_RLPReader.readRawBytes(_items[i]);
}
return _makeNode(raw);
}
/**
* @notice Creates a new extension node.
* @param _key Key for the extension node, unprefixed.
* @param _value Value for the extension node.
* @return _node New extension node with the given k/v pair.
*/
function _makeExtensionNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* Creates a new extension node with the same key but a different value.
* @param _node Extension node to copy and modify.
* @param _value New value for the extension node.
* @return New node with the same key and different value.
*/
function _editExtensionNodeValue(
TrieNode memory _node,
bytes memory _value
)
private
pure
returns (
TrieNode memory
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_getNodeKey(_node), false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
if (_value.length < 32) {
raw[1] = _value;
} else {
raw[1] = Lib_RLPWriter.writeBytes(_value);
}
return _makeNode(raw);
}
/**
* @notice Creates a new leaf node.
* @dev This function is essentially identical to `_makeExtensionNode`.
* Although we could route both to a single method with a flag, it's
* more gas efficient to keep them separate and duplicate the logic.
* @param _key Key for the leaf node, unprefixed.
* @param _value Value for the leaf node.
* @return _node New leaf node with the given k/v pair.
*/
function _makeLeafNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, true);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* @notice Creates an empty branch node.
* @return _node Empty branch node as a TrieNode struct.
*/
function _makeEmptyBranchNode()
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH);
for (uint256 i = 0; i < raw.length; i++) {
raw[i] = RLP_NULL_BYTES;
}
return _makeNode(raw);
}
/**
* @notice Modifies the value slot for a given branch.
* @param _branch Branch node to modify.
* @param _value Value to insert into the branch.
* @return _updatedNode Modified branch node.
*/
function _editBranchValue(
TrieNode memory _branch,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Modifies a slot at an index for a given branch.
* @param _branch Branch node to modify.
* @param _index Slot index to modify.
* @param _value Value to insert into the slot.
* @return _updatedNode Modified branch node.
*/
function _editBranchIndex(
TrieNode memory _branch,
uint8 _index,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Utility; adds a prefix to a key.
* @param _key Key to prefix.
* @param _isLeaf Whether or not the key belongs to a leaf.
* @return _prefixedKey Prefixed key.
*/
function _addHexPrefix(
bytes memory _key,
bool _isLeaf
)
private
pure
returns (
bytes memory _prefixedKey
)
{
uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00);
uint8 offset = uint8(_key.length % 2);
bytes memory prefixed = new bytes(2 - offset);
prefixed[0] = bytes1(prefix + offset);
return abi.encodePacked(prefixed, _key);
}
/**
* @notice Utility; removes a prefix from a path.
* @param _path Path to remove the prefix from.
* @return _unprefixedKey Unprefixed key.
*/
function _removeHexPrefix(
bytes memory _path
)
private
pure
returns (
bytes memory _unprefixedKey
)
{
if (uint8(_path[0]) % 2 == 0) {
return Lib_BytesUtils.slice(_path, 2);
} else {
return Lib_BytesUtils.slice(_path, 1);
}
}
/**
* @notice Utility; combines two node arrays. Array lengths are required
* because the actual lengths may be longer than the filled lengths.
* Array resizing is extremely costly and should be avoided.
* @param _a First array to join.
* @param _aLength Length of the first array.
* @param _b Second array to join.
* @param _bLength Length of the second array.
* @return _joined Combined node array.
*/
function _joinNodeArrays(
TrieNode[] memory _a,
uint256 _aLength,
TrieNode[] memory _b,
uint256 _bLength
)
private
pure
returns (
TrieNode[] memory _joined
)
{
TrieNode[] memory ret = new TrieNode[](_aLength + _bLength);
// Copy elements from the first array.
for (uint256 i = 0; i < _aLength; i++) {
ret[i] = _a[i];
}
// Copy elements from the second array.
for (uint256 i = 0; i < _bLength; i++) {
ret[i + _aLength] = _b[i];
}
return ret;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol";
/**
* @title Lib_SecureMerkleTrie
*/
library Lib_SecureMerkleTrie {
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.update(key, _value, _proof, _root);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.get(key, _proof, _root);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.getSingleNodeRootHash(key, _value);
}
/*********************
* Private Functions *
*********************/
/**
* Computes the secure counterpart to a key.
* @param _key Key to get a secure key from.
* @return _secureKey Secure version of the key.
*/
function _getSecureKey(
bytes memory _key
)
private
pure
returns (
bytes memory _secureKey
)
{
return abi.encodePacked(keccak256(_key));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (
bytes memory
)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
bytes memory
)
{
if (_start >= _bytes.length) {
return bytes('');
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (
uint256
)
{
return uint256(toBytes32(_bytes));
}
function toUint24(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint24
)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint8
)
{
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
address
)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (
bool
)
{
return keccak256(_bytes) == keccak256(_other);
}
}
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_Bytes32Utils } from "./Lib_Bytes32Utils.sol";
/**
* @title Lib_EthUtils
*/
library Lib_EthUtils {
/**********************
* Internal Functions *
**********************/
/**
* Gets the code for a given address.
* @param _address Address to get code for.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Code read from the contract.
*/
function getCode(
address _address,
uint256 _offset,
uint256 _length
)
internal
view
returns (
bytes memory
)
{
bytes memory code;
assembly {
code := mload(0x40)
mstore(0x40, add(code, add(_length, 0x20)))
mstore(code, _length)
extcodecopy(_address, add(code, 0x20), _offset, _length)
}
return code;
}
/**
* Gets the full code for a given address.
* @param _address Address to get code for.
* @return Full code of the contract.
*/
function getCode(
address _address
)
internal
view
returns (
bytes memory
)
{
return getCode(
_address,
0,
getCodeSize(_address)
);
}
/**
* Gets the size of a contract's code in bytes.
* @param _address Address to get code size for.
* @return Size of the contract's code in bytes.
*/
function getCodeSize(
address _address
)
internal
view
returns (
uint256
)
{
uint256 codeSize;
assembly {
codeSize := extcodesize(_address)
}
return codeSize;
}
/**
* Gets the hash of a contract's code.
* @param _address Address to get a code hash for.
* @return Hash of the contract's code.
*/
function getCodeHash(
address _address
)
internal
view
returns (
bytes32
)
{
bytes32 codeHash;
assembly {
codeHash := extcodehash(_address)
}
return codeHash;
}
/**
* Creates a contract with some given initialization code.
* @param _code Contract initialization code.
* @return Address of the created contract.
*/
function createContract(
bytes memory _code
)
internal
returns (
address
)
{
address created;
assembly {
created := create(
0,
add(_code, 0x20),
mload(_code)
)
}
return created;
}
/**
* Computes the address that would be generated by CREATE.
* @param _creator Address creating the contract.
* @param _nonce Creator's nonce.
* @return Address to be generated by CREATE.
*/
function getAddressForCREATE(
address _creator,
uint256 _nonce
)
internal
pure
returns (
address
)
{
bytes[] memory encoded = new bytes[](2);
encoded[0] = Lib_RLPWriter.writeAddress(_creator);
encoded[1] = Lib_RLPWriter.writeUint(_nonce);
bytes memory encodedList = Lib_RLPWriter.writeList(encoded);
return Lib_Bytes32Utils.toAddress(keccak256(encodedList));
}
/**
* Computes the address that would be generated by CREATE2.
* @param _creator Address creating the contract.
* @param _bytecode Bytecode of the contract to be created.
* @param _salt 32 byte salt value mixed into the hash.
* @return Address to be generated by CREATE2.
*/
function getAddressForCREATE2(
address _creator,
bytes memory _bytecode,
bytes32 _salt
)
internal
pure
returns (
address
)
{
bytes32 hashedData = keccak256(abi.encodePacked(
byte(0xff),
_creator,
_salt,
keccak256(_bytecode)
));
return Lib_Bytes32Utils.toAddress(hashedData);
}
}
|
* Computes the root hash for a trie with a single node. @param _key Key for the single node. @param _value Value for the single node. @return _updatedRoot Hash of the trie./
|
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
return keccak256(_makeLeafNode(
Lib_BytesUtils.toNibbles(_key),
_value
).encoded);
}
| 194,770 |
[
1,
10743,
326,
1365,
1651,
364,
279,
19080,
598,
279,
2202,
756,
18,
225,
389,
856,
1929,
364,
326,
2202,
756,
18,
225,
389,
1132,
1445,
364,
326,
2202,
756,
18,
327,
389,
7007,
2375,
2474,
434,
326,
19080,
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,
19108,
907,
2375,
2310,
12,
203,
3639,
1731,
3778,
389,
856,
16,
203,
3639,
1731,
3778,
389,
1132,
203,
565,
262,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
203,
5411,
1731,
1578,
389,
7007,
2375,
203,
3639,
262,
203,
565,
288,
203,
3639,
327,
417,
24410,
581,
5034,
24899,
6540,
16545,
12,
203,
5411,
10560,
67,
2160,
1989,
18,
869,
50,
495,
70,
1040,
24899,
856,
3631,
203,
5411,
389,
1132,
203,
3639,
262,
18,
10787,
1769,
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
] |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./FlightSuretyData.sol";
contract FlightSuretyApp {
using SafeMath for uint256;
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
uint256 private constant CREDIT_MULTIPLIER = 15;
address private contractOwner;
FlightSuretyData dataContract;
event RegisteredAirline(address airlineID);
constructor(address _dataContract) public {
contractOwner = msg.sender;
dataContract = FlightSuretyData(_dataContract);
}
//Fallback function for funding smart contract.
function() external payable {}
//Modifier that calls the isOperational function & requires the state var "operational" (bool) to be true in the data contract
//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() {
// Modify to call data contract's status
require(
dataContract.isOperational(),
"Contract is currently not operational"
);
_;
}
//Modifier that requires the "ContractOwner" account to be the function caller
modifier requireContractOwner() {
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireAirlineSubmittedFunding() {
require(
dataContract.hasFundingBeenSubmitted(msg.sender),
"Requires funding has been submitted by registering airline"
);
_;
}
function isOperational() public view returns (bool) {
return dataContract.isOperational();
}
//Add an airline to the registration
//must get list of addresses in a array before deciding how to handle registration with "if else" statement
//if airline is one of first 4 being registered than it can be added by calling addToRegisteredAirlines in the data contract
//if airline is 5th airline than it must be voted for. This is done by calling voteForAirline function
//if airline has recieved > 50% of votes, it can be registered by calling addToRegisteredAirline function
function registerAirline(address airline)
public
requireIsOperational
requireAirlineSubmittedFunding
{
require(
dataContract.hasAirlineBeenAdded(airline),
"Requires airline has been added"
);
address[] memory registeredAirlines = (
dataContract.getRegisteredAirlines()
);
if (registeredAirlines.length < 5) {
require(
msg.sender == registeredAirlines[0],
"Requires first airline to register first 4 airlines"
);
dataContract.addToRegisteredAirlines(airline);
emit RegisteredAirline(airline);
} else {
require(
dataContract.hasAirlineBeenRegistered(msg.sender),
"Requires registering airline is registered"
);
require(
!dataContract.hasAirlineVotedFor(msg.sender, airline),
"Requires registering airline hasn't already voted"
);
uint256 votes = dataContract.voteForAirline(msg.sender, airline);
if (
SafeMath.div(
SafeMath.mul(votes, 100),
registeredAirlines.length
) >= 50
) {
dataContract.addToRegisteredAirlines(airline);
emit RegisteredAirline(airline);
}
}
}
//Airline submits funding.
//Call the "setFundingSubmitted" function in the data contract which flips the fundingSubmitted property to true
function submitAirlineRegistrationFund()
external
payable
requireIsOperational
{
require(
!dataContract.hasFundingBeenSubmitted(msg.sender),
"Requires funding wasn't already provided"
);
require(
msg.value == 10 ether,
"Requires registration funds be 10 ether"
);
address(dataContract).transfer(msg.value);
dataContract.setFundingSubmitted(msg.sender);
}
//Register a future flight for insuring.
function registerFlight(
address airlineID,
string flight,
uint256 timestamp
) external requireIsOperational {
dataContract.addToRegisteredFlights(airlineID, flight, timestamp);
}
function fetchFlightStatus(
address airlineID,
string flight,
uint256 timestamp
) external requireIsOperational {
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(
abi.encodePacked(index, airlineID, flight, timestamp)
);
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airlineID, flight, timestamp);
}
//Called after oracle has updated flight status
function processFlightStatus(
address airlineID,
string flight,
uint8 statusCode
) internal requireIsOperational {
if (statusCode == STATUS_CODE_LATE_AIRLINE) {
dataContract.creditInsurees(airlineID, flight, CREDIT_MULTIPLIER);
}
}
function buyInsurance(address airlineID, string flight)
external
payable
requireIsOperational
{
require(
msg.value <= 1 ether,
"Requires insured amount of less than 1 ether"
);
dataContract.addToInsurancePolicy(
airlineID,
flight,
msg.sender,
msg.value
);
address(dataContract).transfer(msg.value);
}
function withdrawCredits() external requireIsOperational {
dataContract.withdrawCreditsForInsuree(msg.sender);
}
// ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester;
bool isOpen;
mapping(uint8 => address[]) responses;
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(
address airline,
string flight,
uint256 timestamp,
uint8 status
);
event OracleReport(
address airline,
string flight,
uint256 timestamp,
uint8 status
);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(
uint8 index,
address airline,
string flight,
uint256 timestamp
);
// Register an oracle with the contract
function registerOracle() external payable {
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({isRegistered: true, indexes: indexes});
}
function getMyIndexes() external view returns (uint8[3]) {
require(
oracles[msg.sender].isRegistered,
"Not registered as an oracle"
);
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
) external {
require(
(oracles[msg.sender].indexes[0] == index) ||
(oracles[msg.sender].indexes[1] == index) ||
(oracles[msg.sender].indexes[2] == index),
"Index does not match oracle request"
);
bytes32 key = keccak256(
abi.encodePacked(index, airline, flight, timestamp)
);
require(
oracleResponses[key].isOpen,
"Flight or timestamp do not match oracle request"
);
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (
oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES
) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, statusCode);
}
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes(address account) internal returns (uint8[3]) {
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while (indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while ((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex(address account) internal returns (uint8) {
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(
uint256(
keccak256(
abi.encodePacked(blockhash(block.number - nonce++), account)
)
) % maxValue
);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
}
|
Airline submits funding.Call the "setFundingSubmitted" function in the data contract which flips the fundingSubmitted property to true
|
function submitAirlineRegistrationFund()
external
payable
requireIsOperational
{
require(
!dataContract.hasFundingBeenSubmitted(msg.sender),
"Requires funding wasn't already provided"
);
require(
msg.value == 10 ether,
"Requires registration funds be 10 ether"
);
address(dataContract).transfer(msg.value);
dataContract.setFundingSubmitted(msg.sender);
}
| 6,427,191 |
[
1,
29752,
1369,
720,
22679,
22058,
18,
1477,
326,
315,
542,
42,
14351,
28882,
6,
445,
316,
326,
501,
6835,
1492,
284,
11693,
326,
22058,
28882,
1272,
358,
638,
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,
4879,
29752,
1369,
7843,
42,
1074,
1435,
203,
3639,
3903,
203,
3639,
8843,
429,
203,
3639,
2583,
2520,
2988,
287,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
401,
892,
8924,
18,
5332,
42,
14351,
25931,
28882,
12,
3576,
18,
15330,
3631,
203,
5411,
315,
21671,
22058,
14487,
1404,
1818,
2112,
6,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
1132,
422,
1728,
225,
2437,
16,
203,
5411,
315,
21671,
7914,
284,
19156,
506,
1728,
225,
2437,
6,
203,
3639,
11272,
203,
3639,
1758,
12,
892,
8924,
2934,
13866,
12,
3576,
18,
1132,
1769,
203,
3639,
501,
8924,
18,
542,
42,
14351,
28882,
12,
3576,
18,
15330,
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
] |
pragma solidity ^0.5.17;
import "../governance/Staking/Staking.sol";
contract StakingMockup is Staking {
function balanceOf_MultipliedByTwo(address account) external view returns (uint256) {
return balanceOf(account) * 2;
}
uint96 priorTotalVotingPower;
function MOCK_priorTotalVotingPower(uint96 _priorTotalVotingPower) public {
priorTotalVotingPower = _priorTotalVotingPower;
}
function getPriorTotalVotingPower(uint32 blockNumber, uint256 time)
public
view
returns (uint96 totalVotingPower)
{
return
priorTotalVotingPower != 0
? priorTotalVotingPower
: super.getPriorTotalVotingPower(blockNumber, time);
}
uint96 priorWeightedStake;
function MOCK_priorWeightedStake(uint96 _priorWeightedStake) public {
priorWeightedStake = _priorWeightedStake;
}
function getPriorWeightedStake(
address account,
uint256 blockNumber,
uint256 date
) public view returns (uint96) {
return
priorWeightedStake != 0
? priorWeightedStake
: super.getPriorWeightedStake(account, blockNumber, date);
}
function calculatePriorWeightedStake(
address account,
uint256 blockNumber,
uint256 date
) public {
super.getPriorWeightedStake(account, blockNumber, date);
}
/**
* @dev We need this function to simulate zero delegate checkpoint value.
*/
function setDelegateStake(
address delegatee,
uint256 lockedTS,
uint96 value
) public {
uint32 nCheckpoints = numDelegateStakingCheckpoints[delegatee][lockedTS];
uint96 staked = delegateStakingCheckpoints[delegatee][lockedTS][nCheckpoints - 1].stake;
_writeDelegateCheckpoint(delegatee, lockedTS, nCheckpoints, 0);
}
/**
* @notice Add vesting contract's code hash to a map of code hashes.
* @param vesting The address of Vesting contract.
* @dev We need it to use _isVestingContract() function instead of isContract()
*/
function addContractCodeHash(address vesting) public onlyAuthorized {
bytes32 codeHash = _getCodeHash(vesting);
vestingCodeHashes[codeHash] = true;
emit ContractCodeHashAdded(codeHash);
}
/**
* @notice Add vesting contract's code hash to a map of code hashes.
* @param vesting The address of Vesting contract.
* @dev We need it to use _isVestingContract() function instead of isContract()
*/
function removeContractCodeHash(address vesting) public onlyAuthorized {
bytes32 codeHash = _getCodeHash(vesting);
vestingCodeHashes[codeHash] = false;
emit ContractCodeHashRemoved(codeHash);
}
/**
* @notice Return hash of contract code
*/
function _getCodeHash(address _contract) internal view returns (bytes32) {
bytes32 codeHash;
assembly {
codeHash := extcodehash(_contract)
}
return codeHash;
}
/**
* @notice Return flag whether the given address is a registered vesting contract.
* @param stakerAddress the address to check
*/
function isVestingContract(address stakerAddress) public view returns (bool) {
bytes32 codeHash = _getCodeHash(stakerAddress);
return vestingCodeHashes[codeHash];
}
}
|
* @notice Return flag whether the given address is a registered vesting contract. @param stakerAddress the address to check/
|
function isVestingContract(address stakerAddress) public view returns (bool) {
bytes32 codeHash = _getCodeHash(stakerAddress);
return vestingCodeHashes[codeHash];
}
| 5,471,507 |
[
1,
990,
2982,
2856,
326,
864,
1758,
353,
279,
4104,
331,
10100,
6835,
18,
225,
384,
6388,
1887,
326,
1758,
358,
866,
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,
353,
58,
10100,
8924,
12,
2867,
384,
6388,
1887,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
1731,
1578,
981,
2310,
273,
389,
588,
1085,
2310,
12,
334,
6388,
1887,
1769,
203,
3639,
327,
331,
10100,
1085,
14455,
63,
710,
2310,
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
] |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
/* Interactions Imports */
import { L2OutputOracle } from "../L2OutputOracle.sol";
/* Library Imports */
import { WithdrawalVerifier } from "../../libraries/Lib_WithdrawalVerifier.sol";
/**
* @title WithdrawalsRelay
* @notice The WithdrawalsRelay is inherited by the OptimismPortal on L1, and faciliates finalizing
* withdrawals between L2 and L1.
*/
abstract contract WithdrawalsRelay {
/**********
* Errors *
**********/
/// @notice Error emitted when attempting to finalize a withdrawal too early.
error NotYetFinal();
/// @notice Error emitted when the output root proof is invalid.
error InvalidOutputRootProof();
/// @notice Error emitted when the withdrawal inclusion proof is invalid.
error InvalidWithdrawalInclusionProof();
/// @notice Error emitted when a withdrawal has already been finalized.
error WithdrawalAlreadyFinalized();
/**********
* Events *
**********/
/// @notice Emitted when a withdrawal is finalized
event WithdrawalFinalized(bytes32 indexed);
/// @notice Value used to reset the l2Sender, this is more efficient than setting it to zero.
address internal constant DEFAULT_L2_SENDER = 0x000000000000000000000000000000000000dEaD;
/**********************
* Contract Variables *
**********************/
/// @notice Minimum time that must elapse before a withdrawal can be finalized.
uint256 public immutable FINALIZATION_PERIOD;
/// @notice Address of the L2OutputOracle.
L2OutputOracle public immutable L2_ORACLE;
/**
* @notice Public variable which can be used to read the address of the L2 account which
* initated the withdrawal. Can also be used to determine whether or not execution is occuring
* downstream of a call to finalizeWithdrawalTransaction().
*/
address public l2Sender = DEFAULT_L2_SENDER;
/**
* @notice A list of withdrawal hashes which have been successfully finalized.
* Used for replay protection.
*/
mapping(bytes32 => bool) public finalizedWithdrawals;
/***************
* Constructor *
***************/
constructor(L2OutputOracle _l2Oracle, uint256 _finalizationPeriod) {
L2_ORACLE = _l2Oracle;
FINALIZATION_PERIOD = _finalizationPeriod;
}
/**********************
* External Functions *
**********************/
/**
* @notice Finalizes a withdrawal transaction.
* @param _nonce Nonce for the provided message.
* @param _sender Message sender address on L2.
* @param _target Target address on L1.
* @param _value ETH to send to the target.
* @param _gasLimit Gas to be forwarded to the target.
* @param _data Data to send to the target.
* @param _timestamp L2 timestamp of the outputRoot.
* @param _outputRootProof Inclusion proof of the withdrawer contracts storage root.
* @param _withdrawalProof Inclusion proof for the given withdrawal in the withdrawer contract.
*/
function finalizeWithdrawalTransaction(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes calldata _data,
uint256 _timestamp,
WithdrawalVerifier.OutputRootProof calldata _outputRootProof,
bytes calldata _withdrawalProof
) external {
// Check that the timestamp is sufficiently finalized.
unchecked {
if (block.timestamp < _timestamp + FINALIZATION_PERIOD) {
revert NotYetFinal();
}
}
// Get the output root.
bytes32 outputRoot = L2_ORACLE.getL2Output(_timestamp);
// Verify that the output root can be generated with the elements in the proof.
if (outputRoot != WithdrawalVerifier._deriveOutputRoot(_outputRootProof)) {
revert InvalidOutputRootProof();
}
// Verify that the hash of the withdrawal transaction's arguments are included in the
// storage hash of the withdrawer contract.
bytes32 withdrawalHash = WithdrawalVerifier._deriveWithdrawalHash(
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
if (
WithdrawalVerifier._verifyWithdrawalInclusion(
withdrawalHash,
_outputRootProof.withdrawerStorageRoot,
_withdrawalProof
) == false
) {
revert InvalidWithdrawalInclusionProof();
}
// Check that this withdrawal has not already been finalized.
if (finalizedWithdrawals[withdrawalHash] == true) {
revert WithdrawalAlreadyFinalized();
}
finalizedWithdrawals[withdrawalHash] = true;
l2Sender = _sender;
// Make the call.
(bool s, ) = _target.call{ value: _value, gas: _gasLimit }(_data);
s; // Silence the compiler's "Return value of low-level calls not used" warning.
l2Sender = DEFAULT_L2_SENDER;
// All withdrawals are immediately finalized. If the ability to replay a transaction is
// required, that support can be provided in external contracts.
emit WithdrawalFinalized(withdrawalHash);
}
}
|
* @title WithdrawalsRelay @notice The WithdrawalsRelay is inherited by the OptimismPortal on L1, and faciliates finalizing withdrawals between L2 and L1./
|
abstract contract WithdrawalsRelay {
error NotYetFinal();
error InvalidOutputRootProof();
error InvalidWithdrawalInclusionProof();
error WithdrawalAlreadyFinalized();
event WithdrawalFinalized(bytes32 indexed);
address internal constant DEFAULT_L2_SENDER = 0x000000000000000000000000000000000000dEaD;
uint256 public immutable FINALIZATION_PERIOD;
L2OutputOracle public immutable L2_ORACLE;
address public l2Sender = DEFAULT_L2_SENDER;
mapping(bytes32 => bool) public finalizedWithdrawals;
pragma solidity 0.8.10;
import { L2OutputOracle } from "../L2OutputOracle.sol";
import { WithdrawalVerifier } from "../../libraries/Lib_WithdrawalVerifier.sol";
constructor(L2OutputOracle _l2Oracle, uint256 _finalizationPeriod) {
L2_ORACLE = _l2Oracle;
FINALIZATION_PERIOD = _finalizationPeriod;
}
function finalizeWithdrawalTransaction(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes calldata _data,
uint256 _timestamp,
WithdrawalVerifier.OutputRootProof calldata _outputRootProof,
bytes calldata _withdrawalProof
) external {
unchecked {
if (block.timestamp < _timestamp + FINALIZATION_PERIOD) {
revert NotYetFinal();
}
}
if (outputRoot != WithdrawalVerifier._deriveOutputRoot(_outputRootProof)) {
revert InvalidOutputRootProof();
}
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
if (
WithdrawalVerifier._verifyWithdrawalInclusion(
withdrawalHash,
_outputRootProof.withdrawerStorageRoot,
_withdrawalProof
) == false
) {
revert InvalidWithdrawalInclusionProof();
}
if (finalizedWithdrawals[withdrawalHash] == true) {
revert WithdrawalAlreadyFinalized();
}
finalizedWithdrawals[withdrawalHash] = true;
l2Sender = _sender;
l2Sender = DEFAULT_L2_SENDER;
}
function finalizeWithdrawalTransaction(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes calldata _data,
uint256 _timestamp,
WithdrawalVerifier.OutputRootProof calldata _outputRootProof,
bytes calldata _withdrawalProof
) external {
unchecked {
if (block.timestamp < _timestamp + FINALIZATION_PERIOD) {
revert NotYetFinal();
}
}
if (outputRoot != WithdrawalVerifier._deriveOutputRoot(_outputRootProof)) {
revert InvalidOutputRootProof();
}
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
if (
WithdrawalVerifier._verifyWithdrawalInclusion(
withdrawalHash,
_outputRootProof.withdrawerStorageRoot,
_withdrawalProof
) == false
) {
revert InvalidWithdrawalInclusionProof();
}
if (finalizedWithdrawals[withdrawalHash] == true) {
revert WithdrawalAlreadyFinalized();
}
finalizedWithdrawals[withdrawalHash] = true;
l2Sender = _sender;
l2Sender = DEFAULT_L2_SENDER;
}
function finalizeWithdrawalTransaction(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes calldata _data,
uint256 _timestamp,
WithdrawalVerifier.OutputRootProof calldata _outputRootProof,
bytes calldata _withdrawalProof
) external {
unchecked {
if (block.timestamp < _timestamp + FINALIZATION_PERIOD) {
revert NotYetFinal();
}
}
if (outputRoot != WithdrawalVerifier._deriveOutputRoot(_outputRootProof)) {
revert InvalidOutputRootProof();
}
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
if (
WithdrawalVerifier._verifyWithdrawalInclusion(
withdrawalHash,
_outputRootProof.withdrawerStorageRoot,
_withdrawalProof
) == false
) {
revert InvalidWithdrawalInclusionProof();
}
if (finalizedWithdrawals[withdrawalHash] == true) {
revert WithdrawalAlreadyFinalized();
}
finalizedWithdrawals[withdrawalHash] = true;
l2Sender = _sender;
l2Sender = DEFAULT_L2_SENDER;
}
bytes32 outputRoot = L2_ORACLE.getL2Output(_timestamp);
function finalizeWithdrawalTransaction(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes calldata _data,
uint256 _timestamp,
WithdrawalVerifier.OutputRootProof calldata _outputRootProof,
bytes calldata _withdrawalProof
) external {
unchecked {
if (block.timestamp < _timestamp + FINALIZATION_PERIOD) {
revert NotYetFinal();
}
}
if (outputRoot != WithdrawalVerifier._deriveOutputRoot(_outputRootProof)) {
revert InvalidOutputRootProof();
}
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
if (
WithdrawalVerifier._verifyWithdrawalInclusion(
withdrawalHash,
_outputRootProof.withdrawerStorageRoot,
_withdrawalProof
) == false
) {
revert InvalidWithdrawalInclusionProof();
}
if (finalizedWithdrawals[withdrawalHash] == true) {
revert WithdrawalAlreadyFinalized();
}
finalizedWithdrawals[withdrawalHash] = true;
l2Sender = _sender;
l2Sender = DEFAULT_L2_SENDER;
}
bytes32 withdrawalHash = WithdrawalVerifier._deriveWithdrawalHash(
function finalizeWithdrawalTransaction(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes calldata _data,
uint256 _timestamp,
WithdrawalVerifier.OutputRootProof calldata _outputRootProof,
bytes calldata _withdrawalProof
) external {
unchecked {
if (block.timestamp < _timestamp + FINALIZATION_PERIOD) {
revert NotYetFinal();
}
}
if (outputRoot != WithdrawalVerifier._deriveOutputRoot(_outputRootProof)) {
revert InvalidOutputRootProof();
}
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
if (
WithdrawalVerifier._verifyWithdrawalInclusion(
withdrawalHash,
_outputRootProof.withdrawerStorageRoot,
_withdrawalProof
) == false
) {
revert InvalidWithdrawalInclusionProof();
}
if (finalizedWithdrawals[withdrawalHash] == true) {
revert WithdrawalAlreadyFinalized();
}
finalizedWithdrawals[withdrawalHash] = true;
l2Sender = _sender;
l2Sender = DEFAULT_L2_SENDER;
}
function finalizeWithdrawalTransaction(
uint256 _nonce,
address _sender,
address _target,
uint256 _value,
uint256 _gasLimit,
bytes calldata _data,
uint256 _timestamp,
WithdrawalVerifier.OutputRootProof calldata _outputRootProof,
bytes calldata _withdrawalProof
) external {
unchecked {
if (block.timestamp < _timestamp + FINALIZATION_PERIOD) {
revert NotYetFinal();
}
}
if (outputRoot != WithdrawalVerifier._deriveOutputRoot(_outputRootProof)) {
revert InvalidOutputRootProof();
}
_nonce,
_sender,
_target,
_value,
_gasLimit,
_data
);
if (
WithdrawalVerifier._verifyWithdrawalInclusion(
withdrawalHash,
_outputRootProof.withdrawerStorageRoot,
_withdrawalProof
) == false
) {
revert InvalidWithdrawalInclusionProof();
}
if (finalizedWithdrawals[withdrawalHash] == true) {
revert WithdrawalAlreadyFinalized();
}
finalizedWithdrawals[withdrawalHash] = true;
l2Sender = _sender;
l2Sender = DEFAULT_L2_SENDER;
}
(bool s, ) = _target.call{ value: _value, gas: _gasLimit }(_data);
emit WithdrawalFinalized(withdrawalHash);
}
| 6,462,155 |
[
1,
1190,
9446,
1031,
27186,
225,
1021,
3423,
9446,
1031,
27186,
353,
12078,
635,
326,
19615,
6228,
24395,
603,
511,
21,
16,
471,
5853,
15700,
815,
727,
6894,
598,
9446,
1031,
3086,
511,
22,
471,
511,
21,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
17801,
6835,
3423,
9446,
1031,
27186,
288,
203,
203,
565,
555,
2288,
61,
278,
7951,
5621,
203,
203,
565,
555,
1962,
1447,
2375,
20439,
5621,
203,
203,
565,
555,
1962,
1190,
9446,
287,
382,
15335,
20439,
5621,
203,
203,
565,
555,
3423,
9446,
287,
9430,
7951,
1235,
5621,
203,
203,
203,
565,
871,
3423,
9446,
287,
7951,
1235,
12,
3890,
1578,
8808,
1769,
203,
203,
565,
1758,
2713,
5381,
3331,
67,
48,
22,
67,
1090,
18556,
273,
374,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
31,
203,
203,
203,
565,
2254,
5034,
1071,
11732,
17563,
1013,
25084,
67,
28437,
31,
203,
203,
565,
511,
22,
1447,
23601,
1071,
11732,
511,
22,
67,
916,
2226,
900,
31,
203,
203,
565,
1758,
1071,
328,
22,
12021,
273,
3331,
67,
48,
22,
67,
1090,
18556,
31,
203,
203,
565,
2874,
12,
3890,
1578,
516,
1426,
13,
1071,
727,
1235,
1190,
9446,
1031,
31,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
2163,
31,
203,
5666,
288,
511,
22,
1447,
23601,
289,
628,
315,
6216,
48,
22,
1447,
23601,
18,
18281,
14432,
203,
5666,
288,
3423,
9446,
287,
17758,
289,
628,
315,
16644,
31417,
19,
5664,
67,
1190,
9446,
287,
17758,
18,
18281,
14432,
203,
565,
3885,
12,
48,
22,
1447,
23601,
389,
80,
22,
23601,
16,
2254,
5034,
389,
6385,
1588,
5027,
13,
288,
203,
3639,
511,
22,
67,
916,
2226,
900,
273,
389,
80,
22,
23601,
31,
203,
3639,
17563,
1013,
25084,
67,
28437,
273,
389,
6385,
1588,
5027,
31,
2
] |
//Address: 0xdaae09accd32ccdb5d1fe48244d1826f55670704
//Contract name: ParsecPresale
//Balance: 0 Ether
//Verification Date: 1/23/2018
//Transacion Count: 421
// CODE STARTS HERE
pragma solidity 0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public;
}
contract ParsecTokenERC20 {
// Public variables of the token
string public constant name = "Parsec Credits";
string public constant symbol = "PRSC";
uint8 public decimals = 6;
uint256 public initialSupply = 30856775800;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
function ParsecTokenERC20() public {
// Update total supply with the decimal amount
totalSupply = initialSupply * 10 ** uint256(decimals);
// Give the creator all initial tokens
balanceOf[msg.sender] = totalSupply;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
// Check allowance
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] -= _value;
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
// Check if the sender has enough
require(balanceOf[msg.sender] >= _value);
// Subtract from the sender
balanceOf[msg.sender] -= _value;
// Updates totalSupply
totalSupply -= _value;
// Notify clients about burned tokens
Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
// Check if the targeted balance is enough
require(balanceOf[_from] >= _value);
// Check allowance
require(_value <= allowance[_from][msg.sender]);
// Subtract from the targeted balance
balanceOf[_from] -= _value;
// Subtract from the sender's allowance
allowance[_from][msg.sender] -= _value;
// Update totalSupply
totalSupply -= _value;
// Notify clients about burned tokens
Burn(_from, _value);
return true;
}
}
contract ParsecPresale is owned {
// Use OpenZeppelin's SafeMath
using SafeMath for uint256;
// Minimum and maximum goals of the presale
uint256 public constant PRESALE_MINIMUM_FUNDING = 287.348 ether;
uint256 public constant PRESALE_MAXIMUM_FUNDING = 1887.348 ether;
// Minimum amount per transaction for public participants
uint256 public constant MINIMUM_PARTICIPATION_AMOUNT = 0.5 ether;
// Public presale period
uint256 public constant PRESALE_START_DATE = 1516795200; // 2018-01-24 12:00:00 UTC
uint256 public constant PRESALE_END_DATE = 1517400000; // 2018-01-31 12:00:00 UTC
// Second and third day of pre-sale timestamps
uint256 public constant PRESALE_SECOND_DAY_START = 1516881600; // 2018-01-25 12:00:00 UTC
uint256 public constant PRESALE_THIRD_DAY_START = 1516968000; // 2018-01-26 12:00:00 UTC
// Owner can clawback after a date in the future, so no ethers remain trapped in the contract.
// This will only be relevant if the minimum funding level is not reached
uint256 public constant OWNER_CLAWBACK_DATE = 1519128000; // 2018-02-20 12:00:00 UTC
// Pledgers can withdraw their Parsec credits after a date in the future.
// This will only be relevant if the minimum funding level is reached
uint256 public constant TOKEN_WITHDRAWAL_START_DATE = 1525176000; // 2018-05-01 12:00:00 UTC
uint256 public constant TOKEN_WITHDRAWAL_END_DATE = 1527854400; // 2018-06-01 12:00:00 UTC
// Minimal amount of Parsec credits to be avaibale on this contract balance
// in order to grant credits for all possible participant contributions
uint256 public constant PARSEC_CREDITS_MINIMAL_AMOUNT = 3549000000000000; // 3549000000.000000 PRSC
// Amount of Parsec credits to be granted per ether
uint256 public constant PARSEC_CREDITS_PER_ETHER = 1690000000000; // 1690000.000000 PRSC
// It amount of transfer is greater or equal to this threshold,
// additional bonus Parsec credits will be granted
uint256 public constant BONUS_THRESHOLD = 50 ether;
// Keep track of total funding amount
uint256 public totalFunding;
// Keep track of total whitelisted funding amount
uint256 public totalWhitelistedFunding;
// Keep track of granted Parsec credits amount
uint256 public grantedParsecCredits;
// Keep track of spent Parsec credits amount
uint256 public spentParsecCredits;
// Keep track if unspent Parsec credits were withdrawn
bool public unspentCreditsWithdrawn = false;
// Keep track if unclaimed Parsec credits were withdrawn
bool public unclaimedCreditsWithdrawn = false;
// Keep track if unclaimed Parsec credits were clawbacked
bool public creditsClawbacked = false;
// Keep track if contract balance has enough Parsec tokens
bool public contractPoweredUp = false;
// Keep track if chunk 1 us already added to white list
bool public chunk1IsAdded = false;
// Keep track if chunk 2 us already added to white list
bool public chunk2IsAdded = false;
// Keep track if chunk 3 us already added to white list
bool public chunk3IsAdded = false;
// Keep track if chunk 4 us already added to white list
bool public chunk4IsAdded = false;
// Keep track if chunk 5 us already added to white list
bool public chunk5IsAdded = false;
// Keep track if chunk 6 us already added to white list
bool public chunk6IsAdded = false;
/// @notice Keep track of all participants contributions, including both the
/// preallocation and public phases
/// @dev Name complies with ERC20 token standard, etherscan for example will recognize
/// this and show the balances of the address
mapping (address => uint256) public balanceOf;
/// @notice Keep track of Parsec credits to be granted to participants.
mapping (address => uint256) public creditBalanceOf;
/// @notice Define whitelisted addresses and sums for the first 2 days of pre-sale.
mapping (address => uint256) public whitelist;
/// @notice Log an event for each funding contributed during the public phase
/// @notice Events are not logged when the constructor is being executed during
/// deployment, so the preallocations will not be logged
event LogParticipation(address indexed sender, uint256 value, uint256 timestamp);
// Parsec ERC20 token contract (from previously deployed address)
ParsecTokenERC20 private parsecToken;
function ParsecPresale (address tokenAddress) public {
// Get Parsec ERC20 token instance
parsecToken = ParsecTokenERC20(tokenAddress);
}
/// @notice A participant sends a contribution to the contract's address
/// between the PRESALE_START_DATE and the PRESALE_END_DATE
/// @notice Only contributions above the MINIMUM_PARTICIPATION_AMOUNT are accepted.
/// Otherwise the transaction is rejected and contributed amount is returned
/// to the participant's account
/// @notice A participant's contribution will be rejected if the presale
/// has been funded to the maximum amount
function () public payable {
// Contract should be powered up
require(contractPoweredUp);
// A participant cannot send funds before the presale start date
require(now >= PRESALE_START_DATE);
// A participant cannot send funds after the presale end date
require(now < PRESALE_END_DATE);
// A participant cannot send less than the minimum amount
require(msg.value >= MINIMUM_PARTICIPATION_AMOUNT);
// Contract logic for transfers relies on current date and time.
if (now >= PRESALE_START_DATE && now < PRESALE_SECOND_DAY_START) {
// Trasfer logic for the 1st day of pre-sale.
// Allow to transfer exact whitelisted sum for whitelisted addresses.
require(whitelist[msg.sender] == msg.value);
require(balanceOf[msg.sender] == 0);
} else if (now >= PRESALE_SECOND_DAY_START && now < PRESALE_THIRD_DAY_START) {
// Trasfer logic for the 2nd day of pre-sale.
// Allow to transfer any sum within contract max cap for whitelisted addresses.
require(whitelist[msg.sender] != 0);
}
// A participant cannot send funds if the presale has been reached the maximum funding amount
require(totalFunding.add(msg.value) <= PRESALE_MAXIMUM_FUNDING);
// Register the participant's contribution
addBalance(msg.sender, msg.value);
// Grant Parsec credits according to participant's contribution
grantCreditsForParticipation(msg.sender, msg.value);
}
/// @notice Add chunk 1 / 7 to the whitelist
function addChunk1ToWhiteList() external onlyOwner {
// Chunk should not be added previously
require(!chunk1IsAdded);
// Add whitelisted amounts
addToWhitelist(0x2C66aDd04950eE3235fd3EC6BcB2577c88d804E4, 0.5 ether);
addToWhitelist(0x008e2E5FC70a2bccB5857AE8591119B3B63fdbc2, 0.5 ether);
addToWhitelist(0x0330cc41bDd33f820d92C2df591CD2A5cB99f792, 0.5 ether);
addToWhitelist(0x0756ea3a926399c3da2d5bfc520b711bdadfd0b9, 0.5 ether);
addToWhitelist(0x08c93a267832a8997a46f13b12faa2821d16a472, 0.5 ether);
addToWhitelist(0x0B58dAeAB6D292B5B8A836643023F43E4D0d9b78, 0.5 ether);
addToWhitelist(0x0b73f53885581caf26141b4bb5f8c192af611921, 0.5 ether);
addToWhitelist(0x0be30C8338C76Cc3EF92734863B0A898d8C8fef4, 0.5 ether);
addToWhitelist(0x0fb6829D5543F173d6bba244c2E21CB60544B7fA, 0.5 ether);
addToWhitelist(0x0fccb03ceb56e683fbcf0229c950d666def66d1d, 0.5 ether);
addToWhitelist(0x1578416c880a0F282bAc17c692b2A80b4336D29B, 0.5 ether);
addToWhitelist(0x16fc89d92592b88bc459e19717eEDD51732CfCA1, 0.5 ether);
addToWhitelist(0x183feBd8828a9ac6c70C0e27FbF441b93004fC05, 0.5 ether);
addToWhitelist(0x1A9D4a4DBb3Fb0750107406f4A7c9379DB42f7B3, 0.5 ether);
addToWhitelist(0x1bB95a9c7d50B9b270a604674f4Ed35265087c40, 0.5 ether);
addToWhitelist(0x1bf032d01bab6cd4a2d67ec251f5c3f09728a7e3, 0.5 ether);
addToWhitelist(0x1C1f687165F982Fcd4672B4319AB966256B57b2e, 0.5 ether);
addToWhitelist(0x1E2B069ca94e0232A04A4D1317e120f903D41c3A, 0.5 ether);
addToWhitelist(0x21F23Bb7299Caa26D854DDC38E134E49997471Dd, 0.5 ether);
addToWhitelist(0x23437833ebf735cdaf526c2a2c24f57ca4726358, 0.5 ether);
addToWhitelist(0x2389Ce4eFB2805Fd047C59Fa8991EA9c8361A9a0, 0.5 ether);
addToWhitelist(0x248dd8D2b7991d94860c44A5F99fc1483964FBBf, 0.5 ether);
addToWhitelist(0x257D66c42623c108060a66e4ddE5c3813691Ef38, 0.5 ether);
addToWhitelist(0x26D6F116a16efD1f8361c5Da90AEA4B26b564004, 0.5 ether);
addToWhitelist(0x272899d5b1451B09De35161B11722C95E34f06A9, 0.5 ether);
addToWhitelist(0x29F436906826a7d7Ef0B35292b4f285050108082, 0.5 ether);
addToWhitelist(0x2A8Be3303C83e5E9699a8b4B70976577BFedeC71, 0.5 ether);
addToWhitelist(0x2C351d47CE2737982D1E25FB6dfa30265913aEAa, 0.5 ether);
addToWhitelist(0x3cf2fC2cc45EACf1B6495Bf2AA69fbFC0d4b4a30, 0.5 ether);
addToWhitelist(0x3Cf5f48Dd9bec4Eff46Ee1E2B9e64b2892B5E64F, 0.5 ether);
addToWhitelist(0x3D86C8A928E9595114e01bb0539bdD69e9EfDF3B, 0.5 ether);
addToWhitelist(0x3e825763457fd92a6cb46f5ee0b4969089997da8, 0.5 ether);
addToWhitelist(0x3F4351eb6b1dd9a84890C1C89F4D4419Eb88f1Af, 0.5 ether);
addToWhitelist(0x459cc576ac8332f52ee93cb88228416a872bebd6, 0.5 ether);
addToWhitelist(0x45c556aff90d5fe6e91d24874a8036693cec18d0, 0.5 ether);
addToWhitelist(0x47449fa838794e665A648FA3e47208a7cd105c9D, 0.5 ether);
addToWhitelist(0x50405fB11735160056DBc40b92a09B4215501481, 0.5 ether);
addToWhitelist(0x51DD5Ef09cF73312BADe4C6BA8e03d647730Ecc3, 0.5 ether);
addToWhitelist(0x546A4F1eD47e853Ba119f55A20CbFeaa40ab70E6, 0.5 ether);
addToWhitelist(0x549022ad5cd11816eb7ce6ea15ae61c1fb4edb8a, 0.5 ether);
addToWhitelist(0x5abDC3cB826fC0277D642c9FB52FA76FE3ABb4E7, 0.5 ether);
addToWhitelist(0x5b65dfa08283e024c4ad09b5ea7212c539cb9dbf, 0.5 ether);
addToWhitelist(0x5cC69E09cA05004e5aDCdbE8C8Aac4D16A4651ed, 0.5 ether);
addToWhitelist(0x60a5550D1e43b63b3164F78F2D186bDb7D393C90, 0.5 ether);
addToWhitelist(0x6111d340C833661840ec4c11e84a79a67bE8acCD, 0.5 ether);
addToWhitelist(0x61E140a78Ec39d373C182bf3eD23cBc1AC86023b, 0.5 ether);
addToWhitelist(0x62f12F6C3AD04DFACB10ae05fB54f1E997b0133e, 0.5 ether);
addToWhitelist(0x65276d60Ab36879a6BD88F040D350cd60630FD03, 0.5 ether);
addToWhitelist(0x66B993F856d6175D11B98Be2cBc79EB1888B72f7, 0.5 ether);
addToWhitelist(0x6806408fd066ccddceaecc0a6c6fbbdb2ae8259c, 0.5 ether);
addToWhitelist(0x6918a5b07c2f79a4b272bb7653a43438ca96cd3f, 0.5 ether);
addToWhitelist(0x697DE67DB7d462480418814831d52DA25917A12E, 0.5 ether);
// Set chunk added flag
chunk1IsAdded = true;
}
/// @notice Add chunk 2 / 7 to the whitelist
function addChunk2ToWhiteList() external onlyOwner {
// Chunk should not be added previously
require(!chunk2IsAdded);
// Add whitelisted amounts
addToWhitelist(0x6A35d29D8F63E4D8A8E5418Be9342A48c4C8eF07, 0.5 ether);
addToWhitelist(0x6b2a80FB3C8Eca5144E6F129a447b9D06224a402, 0.5 ether);
addToWhitelist(0x6b8ebca41389689e8875af541a2fa4328ac49917, 0.5 ether);
addToWhitelist(0x6c3Db34C768Ab1E67E2a7E973B7a83651657660b, 0.5 ether);
addToWhitelist(0x7018564dCe2c68417DFa7678541DfA0040Ca0c54, 0.5 ether);
addToWhitelist(0x708faa43f5824d271466c119148728467f66e233, 0.5 ether);
addToWhitelist(0x71526410C961727a89155D6a32Bb75f9a9d755F5, 0.5 ether);
addToWhitelist(0x746B426D0B8e272Ef7402db7CE0FD01C2B1c4aDE, 0.5 ether);
addToWhitelist(0x762C73603f5456c4ad729b3B46464269bcD7C212, 0.5 ether);
addToWhitelist(0x7a0D19955bBf6cff0D86F6e72355A8AFf3c0d74F, 0.5 ether);
addToWhitelist(0x7Cf017bDe8af2DfC67cb3f1b16943A0620eA1B54, 0.5 ether);
addToWhitelist(0x807bAf9e22F4e1E7A5Fcf4B5721ba54666d71421, 0.5 ether);
addToWhitelist(0x810f1C65f9C7c566E14a1E8ECA7b36b78C6da3A8, 0.5 ether);
addToWhitelist(0x871a314d75BdF106420B9e08314e776d2746E0Eb, 0.5 ether);
addToWhitelist(0x88Cf04474CFD3b9Bc4110FfC2980Bc56feBF0465, 0.5 ether);
addToWhitelist(0x8914316B6505b39e706a208A8E91ab8F79eFA7Cf, 0.5 ether);
addToWhitelist(0x8b104344F397aFC33Ee55C743a0FbD7d956201cD, 0.5 ether);
addToWhitelist(0x8Bd5306d0c08Eaa2D9AabaED62297A8AB42db1de, 0.5 ether);
addToWhitelist(0x8Be1843532E5eE0142420fe627a097a0E0681e97, 0.5 ether);
addToWhitelist(0x8c269040283c4112198bc59120ad2bcd70e6b387, 0.5 ether);
addToWhitelist(0x8E14437E18B1091B369c6ff6ecCa73D648aCA3bd, 0.5 ether);
addToWhitelist(0x8Fc9040b8B9305458716e90F83D9b656a07ae7e6, 0.5 ether);
addToWhitelist(0x906d9e4D0E028FE85625d06268A437Bb58753301, 0.5 ether);
addToWhitelist(0x91Fe65df20b13CA260990e096d4EBDbD64f7b399, 0.5 ether);
addToWhitelist(0x92cBbf4A87953975c39EaA2bF70deDEbC356358b, 0.5 ether);
addToWhitelist(0x95D4914d4f08732A169367674A8BE026c02c5B44, 0.5 ether);
addToWhitelist(0x985116bBCcEE828d439c4F6F9233016bf1e95669, 0.5 ether);
addToWhitelist(0x9976cF5617F5E4022CdC887A7A0a68E8eE5dBA22, 0.5 ether);
addToWhitelist(0x9A7379c8aF6765aa267d338A20D197DD1544bF9b, 0.5 ether);
addToWhitelist(0x9DEFB6A85680E11b6aD8AD4095e51464bB4C0C66, 0.5 ether);
addToWhitelist(0xA02896e448A35DeD03C48c2986A545779ed87edd, 0.5 ether);
addToWhitelist(0xa460A24F606d4ABba5041B162E06D42aD6f09157, 0.5 ether);
addToWhitelist(0xaB91cF12f8e133C7B1C849d87997dca895cE0BCB, 0.5 ether);
addToWhitelist(0xac935E0dD7F90851E0c6EE641cd30B800e35f7A8, 0.5 ether);
addToWhitelist(0xae41F73635b6F5F9556Cd3B0d3970aDA5Fb0C1b5, 0.5 ether);
addToWhitelist(0xB16fE19652ceDf4Ba2568b4886CeE29D4e0617B0, 0.5 ether);
addToWhitelist(0xB2F19E5457404dCaCd2d6344592e5a657DFcA27b, 0.5 ether);
addToWhitelist(0xB33cc3147d70Ce2aF31B2B90411BD6333EeA0EA7, 0.5 ether);
addToWhitelist(0xb49a6DD81a847f3A704D0C11C6e1a7C65C47d215, 0.5 ether);
addToWhitelist(0xb75312cdfBee6B6104a7161E27dbd48bb253E186, 0.5 ether);
addToWhitelist(0xB87e73ad25086C43a16fE5f9589Ff265F8A3A9Eb, 0.5 ether);
addToWhitelist(0xc12549d486e20835960Fb3A44ba67fD353B1C48a, 0.5 ether);
addToWhitelist(0xc4Eab1eAaCbf628F0f9Aee4B7375bDE18dd173C4, 0.5 ether);
addToWhitelist(0xc8B15B3189b8C6e90ff330CBA190153fF0A9997e, 0.5 ether);
addToWhitelist(0xCb033bE278d7bD297a2b1Cc6201113480daC579F, 0.5 ether);
addToWhitelist(0xCb570fE877CA6B7dE030afaf9483f58F774df135, 0.5 ether);
addToWhitelist(0xcD4929fdDC83Aca93cD4a75bD12780DaDF51870b, 0.5 ether);
addToWhitelist(0xcdc22860Ff346ead18ECA5E30f0d302a95F33A19, 0.5 ether);
addToWhitelist(0xD26BA3C03fBC1EA352b5F77B2c1F2881d03D1e2F, 0.5 ether);
addToWhitelist(0xd454ED303748Bb5a433388F9508433ba5d507030, 0.5 ether);
addToWhitelist(0xd4d1197fed5F9f3679497Df3604147087B85Ce39, 0.5 ether);
addToWhitelist(0xd83F072142C802A6fA3921d6512B25a7c1A216b1, 0.5 ether);
// Set chunk added flag
chunk2IsAdded = true;
}
/// @notice Add chunk 3 / 7 to the whitelist
function addChunk3ToWhiteList() external onlyOwner {
// Chunk should not be added previously
require(!chunk3IsAdded);
// Add whitelisted amounts
addToWhitelist(0xd9b4cb7bf6a04f545c4c0e32d4570f16cbb3be56, 0.5 ether);
addToWhitelist(0xDCfe2F26c4c47741851e0201a91FB3b8b6452C81, 0.5 ether);
addToWhitelist(0xDf1734032A21Fc9F59E6aCE263b65E4c2bE29861, 0.5 ether);
addToWhitelist(0xDFEa4bE32b1f777d82a6389a0d4F399569c46202, 0.5 ether);
addToWhitelist(0xE18C42Ecb41d125FB21C61B9A18857A361aFC645, 0.5 ether);
addToWhitelist(0xE3e29044291E4f2678c8C1859849a3126B95C2a4, 0.5 ether);
addToWhitelist(0xE4B55adb4eCe93f4F53B3a18561BA876dbA3A2cb, 0.5 ether);
addToWhitelist(0xe96D559283cE2AFC3C79981dA4717bFfFAE69777, 0.5 ether);
addToWhitelist(0xEA7F1b3e36eD60257D79a65d8BA2b305d31cEEE7, 0.5 ether);
addToWhitelist(0xeaf61945762fa3408bfe286da7ea64bd212abfbf, 0.5 ether);
addToWhitelist(0xeC7715afA5Fd2833693Bfc3521EF5197716A65b0, 0.5 ether);
addToWhitelist(0xee15AD84321176b2644d0894f28db22621c12b74, 0.5 ether);
addToWhitelist(0xF05538779A8Ab41741e73a9650CE9B9FE1F3DEc7, 0.5 ether);
addToWhitelist(0xF0c106d282648da9690Cd611F4654fF0e78DEf18, 0.5 ether);
addToWhitelist(0xF132D556c8d065264A36d239b11Ad4Ad3d9f8f6e, 0.5 ether);
addToWhitelist(0xAac34A6B597240B1fAEBaEbeD762F0ecbe02fe18, 0.5 ether);
addToWhitelist(0xaae16c984ca5245E6AC3c646c1Fb3A9695d2f412, 0.5 ether);
addToWhitelist(0xfc575d7064ad46804b28ddc4fce90860addaa256, 0.5 ether);
addToWhitelist(0x4df33f230b862941c92585078eb549a7747c47bd, 0.51 ether);
addToWhitelist(0xaaF1Df7c351c71aD1Df94DB11Ec87b65F5e72531, 0.51 ether);
addToWhitelist(0x5C3E4c34f8a12AFBF1b9d85dfc83953c310e4645, 0.6 ether);
addToWhitelist(0x6580B24104BCAf1ba4171d6bB3B2F1D31a96C549, 0.6 ether);
addToWhitelist(0x0F3B2d5e7C51700aC0986fCe669aB3c69601499a, 0.7 ether);
addToWhitelist(0x0b74911659bfc903d978ea57a70ea00fab893aa2, 0.75 ether);
addToWhitelist(0x45cAa6B0a1d9Db9227DC3D883e31132Ef08F1980, 0.75 ether);
addToWhitelist(0xAcC0F848404e484D6fEB8Bef3bc53DF1a80CB94A, 0.75 ether);
addToWhitelist(0x32c299f7df2e46549fd2dd73f540bf5e8c867d8a, 0.9 ether);
addToWhitelist(0x00aEc73b737Bf387c60094f993B8010f70C06d4e, 1 ether);
addToWhitelist(0x014b65Cf880129A5aC836bcb1C35305De529b59c, 1 ether);
addToWhitelist(0x03D74A8b469dDB568072923323B370d64E795b03, 1 ether);
addToWhitelist(0x04E436cC3fCF465e82932DBd1c7598808Ed07b79, 1 ether);
addToWhitelist(0x0545Cb34B8e136768dF9f889072a87FD83605480, 1 ether);
addToWhitelist(0x0d421e17ABF7509113f3EF03C357Bc2aeF575cb7, 1 ether);
addToWhitelist(0x0faF819dE159B151Dd20E304134a6c167B55D9C1, 1 ether);
addToWhitelist(0x123d31DA8fCbc11ab3B507c61086a7444305fd44, 1 ether);
addToWhitelist(0x16C96155328d9F22973502c2aB2CbEa06Fb3D1A4, 1 ether);
addToWhitelist(0x16D6ddeA3cb142773ca7aD4b12842e47B9835C69, 1 ether);
addToWhitelist(0x1C3DF26aAC85dC9bebB1E8C0a771705b38abF673, 1 ether);
addToWhitelist(0x1d664ddD7A985bED478c94b029444BB43A13ba07, 1 ether);
addToWhitelist(0x218A7E78a960B437c409222ED6b48C088C429949, 1 ether);
addToWhitelist(0x232f4ADd6ee2d479A9178ea184a83D43C1dca70f, 1 ether);
addToWhitelist(0x23D6Fa98877C713C00968D43d7E1fE2B14ce443F, 1 ether);
addToWhitelist(0x241A410828DA842CFB24512b91004ba6bF555D0a, 1 ether);
addToWhitelist(0x3472bdEca240fDFE3A701254bdD62a6c10B2f0e7, 1 ether);
addToWhitelist(0x36889c0Bc35F585062613B6dfa30365AdE826804, 1 ether);
addToWhitelist(0x3775eF0bB806098e4678D7758f6b16595c4D0618, 1 ether);
addToWhitelist(0x37c9909DFb1f13281Cc0109f5C4F4775a337df7c, 1 ether);
addToWhitelist(0x3831ee9f3be7ac81d6653d312adefedbf8ede843, 1 ether);
addToWhitelist(0x38c9606DAaD44fEB86144ab55107a3154DddCf5c, 1 ether);
addToWhitelist(0x400d654A92494958E630A928f9c2Cfc9a0A8e011, 1 ether);
addToWhitelist(0x42593b745B20f03d36137B6E417C222c1b0FE1a8, 1 ether);
addToWhitelist(0x435ca13E9814e0edd2d203E3e14AD9dbcBd19224, 1 ether);
// Set chunk added flag
chunk3IsAdded = true;
}
/// @notice Add chunk 4 / 7 to the whitelist
function addChunk4ToWhiteList() external onlyOwner {
// Chunk should not be added previously
require(!chunk4IsAdded);
// Add whitelisted amounts
addToWhitelist(0x47169f78750Be1e6ec2DEb2974458ac4F8751714, 1 ether);
addToWhitelist(0x499114EF97E50c0F01EDD6558aD6203A9B295419, 1 ether);
addToWhitelist(0x49C11D994DC19C5Edb62F70DFa76c393941d5fFf, 1 ether);
addToWhitelist(0x4bCC31189527dCdFde2f4c887A59b0b0C5dBBB1c, 1 ether);
addToWhitelist(0x4E5Be470d1B97400ce5E141Da1372e06575383ee, 1 ether);
addToWhitelist(0x5203CDD1D0b8cDc6d7CF60228D0c7E7146642405, 1 ether);
addToWhitelist(0x554C033720EfDaD25e5d6400Bdea854bF9E709b6, 1 ether);
addToWhitelist(0x5700e809Ea5b49f80B6117335FB7f6B29E0E4529, 1 ether);
addToWhitelist(0x62f33168582712391f916b4d42f9d7433ed390ea, 1 ether);
addToWhitelist(0x62f4e10FA6f1bA0f2b8282973FF4fE2141F917D6, 1 ether);
addToWhitelist(0x635Dc49b059dB00BF0d2723645Fa68Ffc839a525, 1 ether);
addToWhitelist(0x6465dFa666c6bFDF3E9bd95b5EC1E502843eeEB7, 1 ether);
addToWhitelist(0x6E88904BA0A062C7c13772c1895900E1482deC8e, 1 ether);
addToWhitelist(0x70580eA14d98a53fd59376dC7e959F4a6129bB9b, 1 ether);
addToWhitelist(0x70EbC02aBc8922c34fA901Bd0931A94634e5B6b2, 1 ether);
addToWhitelist(0x71b492cd6695fd85b21af5ae9f818c53f3823046, 1 ether);
addToWhitelist(0x7b8a0D81e8A760D1BCC058250D77F79d4827Fd3c, 1 ether);
addToWhitelist(0x7ba67f190771Cf0C751F2c4e461f40180e8a595c, 1 ether);
addToWhitelist(0x7ce2C04EfC51EaA4Ca7e927a61D51F4dc9A19f41, 1 ether);
addToWhitelist(0x7E8658A0467e34c3ac955117FA3Ba9C18d25d22A, 1 ether);
addToWhitelist(0x7eedaC1991eE2A59B072Be8Dc6Be82CCE9031f91, 1 ether);
addToWhitelist(0x7aa1bb9e0e5439298ec71fb67dc1574f85fecbd1, 1 ether);
addToWhitelist(0x832aC483326472Da0c177EAAf437EA681fAb3ABe, 1 ether);
addToWhitelist(0x861739a2fe0D7d16544c4a295b374705aEEA004F, 1 ether);
addToWhitelist(0x898C86446CcE1B7629aC7f5B5fD8eA0F51a933b3, 1 ether);
addToWhitelist(0x8b2F96cEc0849C6226cf5cFAF32044c12B16eeD9, 1 ether);
addToWhitelist(0x8fF73A67b4406341AfBc4b37c9f595a77Aa062A2, 1 ether);
addToWhitelist(0x964b513c0F30E28B93081195231305a2D92C7762, 1 ether);
addToWhitelist(0x96BC6015ff529eC3a3d0B5e1B7164935Df2bF2fd, 1 ether);
addToWhitelist(0x96BF1A8660C8D74603b3c4f429f6eC53AD32b0B0, 1 ether);
addToWhitelist(0x9840a6b89C53DDB6D6ef57240C6FC972cC97731A, 1 ether);
addToWhitelist(0xA8625D251046abd3F2858D0163A827368a068bac, 1 ether);
addToWhitelist(0xa93e77C28fB6A77518e5C3E61348Aec81E5004fD, 1 ether);
addToWhitelist(0xaEafb182b64FD2CC3866766BA72B030F9AcE69f0, 1 ether);
addToWhitelist(0xB3eA2C6feDb15CDC5228dd0B8606592d712c53e1, 1 ether);
addToWhitelist(0xBde128e0b3EA8E4a6399401A671ce9731282C4C2, 1 ether);
addToWhitelist(0xC3dA85745022fC89CdC774e1FE95ABC4F141292f, 1 ether);
addToWhitelist(0xC62c61Bbcd61A4817b95dA22339A4c856EC4A3F9, 1 ether);
addToWhitelist(0xcE13de0cBd0D7Bde1d2444e2d513868177D2B15F, 1 ether);
addToWhitelist(0xd45546Cbc3C4dE75CC2B1f324d621A7753f25bB3, 1 ether);
addToWhitelist(0xDAF8247Ebcd4BB033D0B82947c3c64a3E5089444, 1 ether);
addToWhitelist(0xEF2F95dbEEd23a04DD674898eaB10cA4C883d780, 1 ether);
addToWhitelist(0xDe3b6c96f7E6c002c1018b77f93b07956C6fB3e8, 1 ether);
addToWhitelist(0xe415638FC30b277EC7F466E746ABf2d406f821FF, 1 ether);
addToWhitelist(0xE4A12D142b218ed96C75AA8D43aa153dc774F403, 1 ether);
addToWhitelist(0xEEBEA0A8303aAc18D2cABaca1033f04c4a43E358, 1 ether);
addToWhitelist(0xf12059ad0EB7D393E41AC3b3250FB5E446AA8dFB, 1 ether);
addToWhitelist(0xF94EfB6049B7bca00cE8e211C9A3f5Ca7ff4800b, 1 ether);
addToWhitelist(0xFBCe0CBB70bD0Bf43B11f721Beaf941980C5fF4a, 1 ether);
addToWhitelist(0x573648f395c26f453bf06Fd046a110A016274710, 1.2 ether);
addToWhitelist(0x95159e796569A9A7866F9A6CF0E36B8D6ddE9c02, 1.2 ether);
addToWhitelist(0xEafF321951F891EBD791eF57Dc583A859626E295, 1.2 ether);
// Set chunk added flag
chunk4IsAdded = true;
}
/// @notice Add chunk 5 / 7 to the whitelist
function addChunk5ToWhiteList() external onlyOwner {
// Chunk should not be added previously
require(!chunk5IsAdded);
// Add whitelisted amounts
addToWhitelist(0x439f5420d4eD1DE8c982100Fcf808C5FcEeC1bFa, 1.25 ether);
addToWhitelist(0xfd5D41Dad5218C312d693a8b6b1128889cFFec43, 1.25 ether);
addToWhitelist(0x1FBB99bf7E6e8920Fac8Ab371cEB5A90e0801656, 1.5 ether);
addToWhitelist(0x6d767fE3e87b6Ffb762cd46138aaaB48a6788d06, 1.5 ether);
addToWhitelist(0x9C299486fc9b5B1bA1dbE2d6D93E3580f9A64995, 1.5 ether);
addToWhitelist(0x009e511c89e033142bdd1f34f7cad0f3e188696d, 2 ether);
addToWhitelist(0x25929fF98a1e8D7d1c14674bD883A24C26FB1df4, 2 ether);
addToWhitelist(0x2a54850a5166d2fCC805B78A1D436b96e4477e09, 2 ether);
addToWhitelist(0x3D212E369e08fB9D5585a35449595df044cdD7a4, 2 ether);
addToWhitelist(0x417EcaE932D3bAE2d93a2af6dA91441d46532A7C, 2 ether);
addToWhitelist(0x53070A3A5faF50280563ea4fB4b5e6AcA53B7221, 2 ether);
addToWhitelist(0x67314b5CdFD52A1D5c4794C02C5b3b2cc4bdc21B, 2 ether);
addToWhitelist(0x67fb2006dd8990de950d1eb41f07ff7f929c3bca, 2 ether);
addToWhitelist(0x76b3a5aad6aD161680F9e7C9dd09bA9626135765, 2 ether);
addToWhitelist(0x77446d3Df1216B1e8Ea1913203B05F5cb182B112, 2 ether);
addToWhitelist(0x788b7433ddf168544b2adae3c6aa416d3f6fa112, 2 ether);
addToWhitelist(0x790310b3f668019056a8b811ced6e2a0af533660, 2 ether);
addToWhitelist(0x7dD1b95E76F7893002E4FB9a533628994b703479, 2 ether);
addToWhitelist(0x821578e6212651CAa996184404787ccC09C71014, 2 ether);
addToWhitelist(0x8b91B39Ef4ae08bEacC128d3C2e19140AbD0245F, 2 ether);
addToWhitelist(0x8f566cdE6724DEA78756B8C252055e6eA7D3d7a4, 2 ether);
addToWhitelist(0x90f7f982c2Ab40534e5E3bE449967B716ef04BB1, 2 ether);
addToWhitelist(0x91FDae97a5a3Ba806fA3Eb8B3cd3F0bEE6431b77, 2 ether);
addToWhitelist(0x99cf8060BaFca88C04Aa2Eace46CA880bE75F166, 2 ether);
addToWhitelist(0xa099638b5CFE746C0B3DD1a3998051c2Ac1F3dC8, 2 ether);
addToWhitelist(0xb9a2ACF30FB774881371F249928Cb48Ccc184bAC, 2 ether);
addToWhitelist(0xC301Fc1acCF9ab89Fa68Fd240dCDaa0Bd9a3658F, 2 ether);
addToWhitelist(0xc4f5bFad8Ec83Bcd4AB3b3a27266f08b4517f59B, 2 ether);
addToWhitelist(0xd1EA23d6713ca22cc1f2e10dc6FD8B1DfB65b563, 2 ether);
addToWhitelist(0xd4F2ad288874653F09e3Cc522C1106692E30394C, 2 ether);
addToWhitelist(0xddF81dabe498118df262b1b907492b391211321e, 2 ether);
addToWhitelist(0xE4fBc54c0a08a5d0CD1EEBC8bf0Ea48fdBFd7E0c, 2 ether);
addToWhitelist(0xf42F3c005B1723782FC25E5771748a6A1fff5e03, 2 ether);
addToWhitelist(0xff7ef21aC94961a3C9F71a3deFFfe2f58e102E1f, 2 ether);
addToWhitelist(0xa27A60769B426b1eEA3be951DF29D352B48ec5Da, 2.5 ether);
addToWhitelist(0xba334469f45f8e0ca1d61fa036fece3b4d5ec0f7, 2.5 ether);
addToWhitelist(0xdE47f3C16cDb757027F61D07a44c881d2D32B161, 2.5 ether);
addToWhitelist(0xfCD47A33207eD5a03390330Fd6EcFF2DFf8F5a2b, 2.5 ether);
addToWhitelist(0x27fcA80168B7eDC487B22F0F334BA922d1e26E2D, 3 ether);
addToWhitelist(0x36bd14eaf211d65164e1e0a2eab5c98b4b734875, 3 ether);
addToWhitelist(0x3D1a96c1fE8D1281537c5A8C93A89215DF254d3f, 3 ether);
addToWhitelist(0x40ED9F03BFfFA1cB30E36910907cd55ac27Be05d, 3 ether);
addToWhitelist(0x5Da227c19913F4deEB64A6E7fE41B30B230161D2, 3 ether);
addToWhitelist(0x7e443aA16aC53419CFd8056Bcc30b674864Ac55F, 3 ether);
addToWhitelist(0x80F30bAc95966922f1E8c66c0fD088959a00f15f, 3 ether);
addToWhitelist(0x8862004b5a7C21B8F771AF3213b79bD9b81f9DA0, 3 ether);
addToWhitelist(0x904063eF93eEEd9584f6B0131F9FD047d7c3C28d, 3 ether);
addToWhitelist(0xa14aC1A9B3D52aBD0652C5Aca346099A6eb16b54, 3 ether);
addToWhitelist(0xA2Ef14F0d1ae84609Cd104feB91EAeD4B39C4852, 3 ether);
addToWhitelist(0xA4D1905ceF480Fb9089578F88D3C128cf386ebd5, 3 ether);
addToWhitelist(0xa5D5404864E9eA3104ec6721CA08E563964Ae536, 3 ether);
addToWhitelist(0xB3ADF1FB9c488DBB42378876ff4Fc2be4c1B4365, 3 ether);
// Set chunk added flag
chunk5IsAdded = true;
}
/// @notice Add chunk 6 / 7 to the whitelist
function addChunk6ToWhiteList() external onlyOwner {
// Chunk should not be added previously
require(!chunk6IsAdded);
// Add whitelisted amounts
addToWhitelist(0xC9403834046d64AAc2F98BA9CD29A84D48DBF58D, 3 ether);
addToWhitelist(0xd0f9899ec83BF1cf915bf101D6E7949361151523, 3 ether);
addToWhitelist(0xeB386a17ED99148dc98F07D0714751786836F68e, 3 ether);
addToWhitelist(0xeFc85EbccE16Db424fCEfBfA4a523fC9957C0E63, 3 ether);
addToWhitelist(0xfa52B6F191F57284762617Cfdbbf187E10C02D93, 3 ether);
addToWhitelist(0xfd0928783dd997D982AeeE5399f9B6816FbF789B, 3 ether);
addToWhitelist(0xFEA0904ACc8Df0F3288b6583f60B86c36Ea52AcD, 3 ether);
addToWhitelist(0xe9Cc01e48F027a0BFa97aFDa0229F09EDD9a590b, 3.7 ether);
addToWhitelist(0x4f7c845e4d09c3453bcfe03dd09cc96b5c6941a3, 4 ether);
addToWhitelist(0x0d41F957181E584dB82d2E316837B2DE1738C477, 5 ether);
addToWhitelist(0x102A65de4c20BCe35Aa9B6ae2eA2ecf60c91831B, 5 ether);
addToWhitelist(0x1Cff36DeBD53EEB3264fD75497356132C4067632, 5 ether);
addToWhitelist(0x21a39c71cb9544336e24d57df3655f30be99cf3b, 5 ether);
addToWhitelist(0x221CDC565782c03fe4ca913f1392741b67d48a81, 5 ether);
addToWhitelist(0x280cbA9bB3bd5E222B75fd9D5ff0D3Ec43F0D087, 5 ether);
addToWhitelist(0x2Fc0F28ee6C0172bD7D4DDbf791Fd520B29b10a1, 5 ether);
addToWhitelist(0x3243d70ed16410F55f22684a8768e7492E91108b, 5 ether);
addToWhitelist(0x44b38befe7a68fdbd50963feaa06566980a92f7e, 5 ether);
addToWhitelist(0x4AA75e261b28884718c49DA3f671b3C32a467faD, 5 ether);
addToWhitelist(0x522e98867715dA9e1fD87A7e759081cCE8ae61d6, 5 ether);
addToWhitelist(0x54e0766871b94d02f148b21a15d7ae4679f19c39, 5 ether);
addToWhitelist(0x61cf029E58713260aCDAd6e46a54BA687A465064, 5 ether);
addToWhitelist(0x6A4234773DC2c3cb4d2951aAa50107E9454451C1, 5 ether);
addToWhitelist(0x6beb418fc6e1958204ac8baddcf109b8e9694966, 5 ether);
addToWhitelist(0x90c0E8849266AE128aA355B46D090802DCfB1a25, 5 ether);
addToWhitelist(0x9b2c4a09ee37105d7ee139b83ca281ab20f6ca78, 5 ether);
addToWhitelist(0x9E4a9f2b4eFd85972cF952d2f5Fb16C291ED43B3, 5 ether);
addToWhitelist(0xafa2a0cd8ed977c2515b266c3bcc6fe1096c573d, 5 ether);
addToWhitelist(0xC1A065a2d29995692735c82d228B63Df1732030E, 5 ether);
addToWhitelist(0xD069A2c75999B87671a29c61B25848ee288a9d75, 5 ether);
addToWhitelist(0xd10f3f908611eca959f43667975f9e917435a449, 5 ether);
addToWhitelist(0xd4e470fad0d7195699cA9B713fD7C5196cb61Fec, 5 ether);
addToWhitelist(0xC32e75369bFcef12195741954687e211B3Bc807A, 6 ether);
addToWhitelist(0xe6fabdca7cb022434a61839268a7d9c10baf5eb2, 6 ether);
addToWhitelist(0xe26b11577372aa5e9c10407fe8f7cce6cb88aba0, 7 ether);
addToWhitelist(0x0edc326b97F071C1a5393Ba5344bb762DEE0C53a, 10 ether);
addToWhitelist(0x2A3F7E5170Ea8Ca967f85f091eF84591f639E031, 10 ether);
addToWhitelist(0x32f3474D1eB6aA38A85a7bb4fB85715A216A2640, 10 ether);
addToWhitelist(0x49CEF0ce48ab89E6C8bB50a184FbEb19b44Ade63, 10 ether);
addToWhitelist(0x67D8dFF88562D156a2306CE5f2eFCA0b452aAdD2, 10 ether);
addToWhitelist(0x969f18769a75847d39e91ad0dbdfd80820293b0d, 10 ether);
addToWhitelist(0x976D1CF16b5b2567503246d7D980F86234cB1fAd, 10 ether);
addToWhitelist(0xA02f61FE8DeB678b53a4eA1BE0353f4F78D16a5a, 10 ether);
addToWhitelist(0xd573C0f13aC91d30bC0A08F1c256063e3a6928eF, 10 ether);
addToWhitelist(0xe5FbbDfd081aaD4913eB25e4b195Ba15C2d64de5, 10 ether);
addToWhitelist(0xf159FdAfA300d4b7E417CFE06d55F09d93b60E53, 10 ether);
addToWhitelist(0xf831dB774BfC4e2c74b9b42474a0e0DD60B342b1, 10 ether);
addToWhitelist(0x8A7aA336E1909641558B906585fc56DeE2B44Dd0, 15 ether);
addToWhitelist(0x48ce7eBe80d771a7023E1dC3eB632a4E6Cb0559b, 20 ether);
addToWhitelist(0x6818025bd0e89506D3D34B0C45cC1E556d2Dbc5B, 20 ether);
addToWhitelist(0x9BE1c7a1F118F61740f01e96d292c0bae90360aB, 20 ether);
addToWhitelist(0xa1B0dDDEFFf18651206ae2d68A14f024760eAa75, 20 ether);
// Set chunk added flag
chunk6IsAdded = true;
}
/// @notice Check if pre-sale contract has enough Parsec credits on its account balance
/// to reward all possible participations within pre-sale period and max cap
function powerUpContract() external onlyOwner {
// Contract should not be powered up previously
require(!contractPoweredUp);
// Contract should have enough Parsec credits
require(parsecToken.balanceOf(this) >= PARSEC_CREDITS_MINIMAL_AMOUNT);
// Raise contract power-up flag
contractPoweredUp = true;
}
/// @notice The owner can withdraw ethers only if the minimum funding level has been reached
// and pre-sale is over
function ownerWithdraw() external onlyOwner {
// The owner cannot withdraw until pre-sale ends
require(now >= PRESALE_END_DATE);
// The owner cannot withdraw if the presale did not reach the minimum funding amount
require(totalFunding >= PRESALE_MINIMUM_FUNDING);
// Withdraw the total funding amount
owner.transfer(totalFunding);
}
/// @notice The owner can withdraw unspent Parsec credits if the minimum funding level has been
/// reached and pre-sale is over
function ownerWithdrawUnspentCredits() external onlyOwner {
// The owner cannot withdraw unspent Parsec credits until pre-sale ends
require(now >= PRESALE_END_DATE);
// The owner cannot withdraw unspent Parsec credits if token withdrawal period started
require(now < TOKEN_WITHDRAWAL_START_DATE);
// The owner cannot withdraw if the pre-sale did not reach the minimum funding amount
require(totalFunding >= PRESALE_MINIMUM_FUNDING);
// The owner cannot withdraw unspent Parsec credits more than once
require(!unspentCreditsWithdrawn);
// Transfer unspent Parsec credits back to pre-sale contract owner
uint256 currentCredits = parsecToken.balanceOf(this);
uint256 unspentAmount = currentCredits.sub(grantedParsecCredits);
unspentCreditsWithdrawn = true;
parsecToken.transfer(owner, unspentAmount);
}
function ownerWithdrawUnclaimedCredits() external onlyOwner {
// The owner cannot withdraw unclaimed Parsec credits until token withdrawal period ends
require(now >= TOKEN_WITHDRAWAL_END_DATE);
// The owner cannot withdraw if the presale did not reach the minimum funding amount
require(totalFunding >= PRESALE_MINIMUM_FUNDING);
// The owner cannot withdraw unclaimed Parsec credits more than once
require(!unclaimedCreditsWithdrawn);
// Transfer unclaimed Parsec credits back to pre-sale contract owner
unclaimedCreditsWithdrawn = true;
parsecToken.transfer(owner, parsecToken.balanceOf(this));
}
/// @notice The participant will need to withdraw their Parsec credits if minimal pre-sale amount
/// was reached and date between TOKEN_WITHDRAWAL_START_DATE and TOKEN_WITHDRAWAL_END_DATE
function participantClaimCredits() external {
// Participant can withdraw Parsec credits only during token withdrawal period
require(now >= TOKEN_WITHDRAWAL_START_DATE);
require(now < TOKEN_WITHDRAWAL_END_DATE);
// Participant cannot withdraw Parsec credits if the minimum funding amount has not been reached
require(totalFunding >= PRESALE_MINIMUM_FUNDING);
// Participant can only withdraw Parsec credits if granted amount exceeds zero
require(creditBalanceOf[msg.sender] > 0);
// Get amount of tokens to approve
var tokensToApprove = creditBalanceOf[msg.sender];
// Update amount of Parsec credits spent
spentParsecCredits = spentParsecCredits.add(tokensToApprove);
// Participant's Parsec credit balance is reduced to zero
creditBalanceOf[msg.sender] = 0;
// Give allowance for participant to withdraw certain amount of Parsec credits
parsecToken.approve(msg.sender, tokensToApprove);
}
/// @notice The participant will need to withdraw their funds from this contract if
/// the presale has not achieved the minimum funding level
function participantWithdrawIfMinimumFundingNotReached(uint256 value) external {
// Participant cannot withdraw before the presale ends
require(now >= PRESALE_END_DATE);
// Participant cannot withdraw if the minimum funding amount has been reached
require(totalFunding < PRESALE_MINIMUM_FUNDING);
// Get sender balance
uint256 senderBalance = balanceOf[msg.sender];
// Participant can only withdraw an amount up to their contributed balance
require(senderBalance >= value);
// Participant's balance is reduced by the claimed amount.
balanceOf[msg.sender] = senderBalance.sub(value);
// Send ethers back to the participant's account
msg.sender.transfer(value);
}
/// @notice The owner can clawback any ethers after a date in the future, so no
/// ethers remain trapped in this contract. This will only be relevant
/// if the minimum funding level is not reached
function ownerClawback() external onlyOwner {
// Minimum funding amount has not been reached
require(totalFunding < PRESALE_MINIMUM_FUNDING);
// The owner cannot withdraw before the clawback date
require(now >= OWNER_CLAWBACK_DATE);
// Send remaining funds back to the owner
owner.transfer(this.balance);
}
/// @notice The owner can clawback any unspent Parsec credits after a date in the future,
/// so no Parsec credits remain trapped in this contract. This will only be relevant
/// if the minimum funding level is not reached
function ownerClawbackCredits() external onlyOwner {
// Minimum funding amount has not been reached
require(totalFunding < PRESALE_MINIMUM_FUNDING);
// The owner cannot withdraw before the clawback date
require(now >= OWNER_CLAWBACK_DATE);
// The owner cannot clawback unclaimed Parsec credits more than once
require(!creditsClawbacked);
// Transfer clawbacked Parsec credits back to pre-sale contract owner
creditsClawbacked = true;
parsecToken.transfer(owner, parsecToken.balanceOf(this));
}
/// @dev Keep track of participants contributions and the total funding amount
function addBalance(address participant, uint256 value) private {
// Participant's balance is increased by the sent amount
balanceOf[participant] = balanceOf[participant].add(value);
// Keep track of the total funding amount
totalFunding = totalFunding.add(value);
// Log an event of the participant's contribution
LogParticipation(participant, value, now);
}
/// @dev Add whitelisted amount
function ownerAddToWhitelist(address participant, uint256 value) external onlyOwner {
addToWhitelist(participant, value);
}
/// @dev Keep track of whitelisted participants contributions
function addToWhitelist(address participant, uint256 value) private {
// Participant's balance is increased by the sent amount
whitelist[participant] = whitelist[participant].add(value);
// Keep track of the total whitelisted funding amount
totalWhitelistedFunding = totalWhitelistedFunding.add(value);
}
function grantCreditsForParticipation(address participant, uint256 etherAmount) private {
// Add bonus 5% if contributed amount is greater or equal to bonus threshold
uint256 dividend = etherAmount >= BONUS_THRESHOLD ? 105 : 100;
dividend = dividend.mul(etherAmount);
dividend = dividend.mul(PARSEC_CREDITS_PER_ETHER);
uint256 divisor = 100;
divisor = divisor.mul(1 ether);
// Calculate amount of Parsec credits to grant to contributor
uint256 creditsToGrant = dividend.div(divisor);
// Check if contract has enough Parsec credits
uint256 currentBalanceInCredits = parsecToken.balanceOf(this);
uint256 availableCredits = currentBalanceInCredits.sub(grantedParsecCredits);
require(availableCredits >= creditsToGrant);
// Add Parsec credits amount to participant's credit balance
creditBalanceOf[participant] = creditBalanceOf[participant].add(creditsToGrant);
// Add Parsec credits amount to total granted credits
grantedParsecCredits = grantedParsecCredits.add(creditsToGrant);
}
}
|
@notice Add chunk 2 / 7 to the whitelist Chunk should not be added previously Add whitelisted amounts Set chunk added flag
|
function addChunk2ToWhiteList() external onlyOwner {
require(!chunk2IsAdded);
addToWhitelist(0x6A35d29D8F63E4D8A8E5418Be9342A48c4C8eF07, 0.5 ether);
addToWhitelist(0x6b2a80FB3C8Eca5144E6F129a447b9D06224a402, 0.5 ether);
addToWhitelist(0x6b8ebca41389689e8875af541a2fa4328ac49917, 0.5 ether);
addToWhitelist(0x6c3Db34C768Ab1E67E2a7E973B7a83651657660b, 0.5 ether);
addToWhitelist(0x7018564dCe2c68417DFa7678541DfA0040Ca0c54, 0.5 ether);
addToWhitelist(0x708faa43f5824d271466c119148728467f66e233, 0.5 ether);
addToWhitelist(0x71526410C961727a89155D6a32Bb75f9a9d755F5, 0.5 ether);
addToWhitelist(0x746B426D0B8e272Ef7402db7CE0FD01C2B1c4aDE, 0.5 ether);
addToWhitelist(0x762C73603f5456c4ad729b3B46464269bcD7C212, 0.5 ether);
addToWhitelist(0x7a0D19955bBf6cff0D86F6e72355A8AFf3c0d74F, 0.5 ether);
addToWhitelist(0x7Cf017bDe8af2DfC67cb3f1b16943A0620eA1B54, 0.5 ether);
addToWhitelist(0x807bAf9e22F4e1E7A5Fcf4B5721ba54666d71421, 0.5 ether);
addToWhitelist(0x810f1C65f9C7c566E14a1E8ECA7b36b78C6da3A8, 0.5 ether);
addToWhitelist(0x871a314d75BdF106420B9e08314e776d2746E0Eb, 0.5 ether);
addToWhitelist(0x88Cf04474CFD3b9Bc4110FfC2980Bc56feBF0465, 0.5 ether);
addToWhitelist(0x8914316B6505b39e706a208A8E91ab8F79eFA7Cf, 0.5 ether);
addToWhitelist(0x8b104344F397aFC33Ee55C743a0FbD7d956201cD, 0.5 ether);
addToWhitelist(0x8Bd5306d0c08Eaa2D9AabaED62297A8AB42db1de, 0.5 ether);
addToWhitelist(0x8Be1843532E5eE0142420fe627a097a0E0681e97, 0.5 ether);
addToWhitelist(0x8c269040283c4112198bc59120ad2bcd70e6b387, 0.5 ether);
addToWhitelist(0x8E14437E18B1091B369c6ff6ecCa73D648aCA3bd, 0.5 ether);
addToWhitelist(0x8Fc9040b8B9305458716e90F83D9b656a07ae7e6, 0.5 ether);
addToWhitelist(0x906d9e4D0E028FE85625d06268A437Bb58753301, 0.5 ether);
addToWhitelist(0x91Fe65df20b13CA260990e096d4EBDbD64f7b399, 0.5 ether);
addToWhitelist(0x92cBbf4A87953975c39EaA2bF70deDEbC356358b, 0.5 ether);
addToWhitelist(0x95D4914d4f08732A169367674A8BE026c02c5B44, 0.5 ether);
addToWhitelist(0x985116bBCcEE828d439c4F6F9233016bf1e95669, 0.5 ether);
addToWhitelist(0x9976cF5617F5E4022CdC887A7A0a68E8eE5dBA22, 0.5 ether);
addToWhitelist(0x9A7379c8aF6765aa267d338A20D197DD1544bF9b, 0.5 ether);
addToWhitelist(0x9DEFB6A85680E11b6aD8AD4095e51464bB4C0C66, 0.5 ether);
addToWhitelist(0xA02896e448A35DeD03C48c2986A545779ed87edd, 0.5 ether);
addToWhitelist(0xa460A24F606d4ABba5041B162E06D42aD6f09157, 0.5 ether);
addToWhitelist(0xaB91cF12f8e133C7B1C849d87997dca895cE0BCB, 0.5 ether);
addToWhitelist(0xac935E0dD7F90851E0c6EE641cd30B800e35f7A8, 0.5 ether);
addToWhitelist(0xae41F73635b6F5F9556Cd3B0d3970aDA5Fb0C1b5, 0.5 ether);
addToWhitelist(0xB16fE19652ceDf4Ba2568b4886CeE29D4e0617B0, 0.5 ether);
addToWhitelist(0xB2F19E5457404dCaCd2d6344592e5a657DFcA27b, 0.5 ether);
addToWhitelist(0xB33cc3147d70Ce2aF31B2B90411BD6333EeA0EA7, 0.5 ether);
addToWhitelist(0xb49a6DD81a847f3A704D0C11C6e1a7C65C47d215, 0.5 ether);
addToWhitelist(0xb75312cdfBee6B6104a7161E27dbd48bb253E186, 0.5 ether);
addToWhitelist(0xB87e73ad25086C43a16fE5f9589Ff265F8A3A9Eb, 0.5 ether);
addToWhitelist(0xc12549d486e20835960Fb3A44ba67fD353B1C48a, 0.5 ether);
addToWhitelist(0xc4Eab1eAaCbf628F0f9Aee4B7375bDE18dd173C4, 0.5 ether);
addToWhitelist(0xc8B15B3189b8C6e90ff330CBA190153fF0A9997e, 0.5 ether);
addToWhitelist(0xCb033bE278d7bD297a2b1Cc6201113480daC579F, 0.5 ether);
addToWhitelist(0xCb570fE877CA6B7dE030afaf9483f58F774df135, 0.5 ether);
addToWhitelist(0xcD4929fdDC83Aca93cD4a75bD12780DaDF51870b, 0.5 ether);
addToWhitelist(0xcdc22860Ff346ead18ECA5E30f0d302a95F33A19, 0.5 ether);
addToWhitelist(0xD26BA3C03fBC1EA352b5F77B2c1F2881d03D1e2F, 0.5 ether);
addToWhitelist(0xd454ED303748Bb5a433388F9508433ba5d507030, 0.5 ether);
addToWhitelist(0xd4d1197fed5F9f3679497Df3604147087B85Ce39, 0.5 ether);
addToWhitelist(0xd83F072142C802A6fA3921d6512B25a7c1A216b1, 0.5 ether);
chunk2IsAdded = true;
}
| 13,063,827 |
[
1,
986,
2441,
576,
342,
2371,
358,
326,
10734,
13021,
1410,
486,
506,
3096,
7243,
1436,
26944,
30980,
1000,
2441,
3096,
2982,
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
] |
[
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,
0
] |
[
1,
565,
445,
527,
5579,
22,
774,
13407,
682,
1435,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
5,
6551,
22,
2520,
8602,
1769,
203,
203,
3639,
9604,
18927,
12,
20,
92,
26,
37,
4763,
72,
5540,
40,
28,
42,
4449,
41,
24,
40,
28,
37,
28,
41,
6564,
2643,
1919,
29,
5026,
22,
37,
8875,
71,
24,
39,
28,
73,
42,
8642,
16,
374,
18,
25,
225,
2437,
1769,
203,
3639,
9604,
18927,
12,
20,
92,
26,
70,
22,
69,
3672,
22201,
23,
39,
28,
41,
5353,
25,
25339,
41,
26,
42,
24886,
69,
6334,
27,
70,
29,
40,
7677,
23622,
69,
24,
3103,
16,
374,
18,
25,
225,
2437,
1769,
203,
3639,
9604,
18927,
12,
20,
92,
26,
70,
28,
24008,
5353,
24,
3437,
6675,
26,
6675,
73,
5482,
5877,
1727,
6564,
21,
69,
22,
507,
24,
1578,
28,
1077,
24,
2733,
4033,
16,
374,
18,
25,
225,
2437,
1769,
203,
3639,
9604,
18927,
12,
20,
92,
26,
71,
23,
4331,
5026,
39,
6669,
28,
5895,
21,
41,
9599,
41,
22,
69,
27,
41,
29,
9036,
38,
27,
69,
28,
5718,
25,
28275,
6669,
4848,
70,
16,
374,
18,
25,
225,
2437,
1769,
203,
3639,
9604,
18927,
12,
20,
92,
27,
1611,
7140,
1105,
72,
39,
73,
22,
71,
26,
5193,
4033,
4577,
69,
6669,
8285,
6564,
21,
40,
29534,
713,
7132,
23508,
20,
71,
6564,
16,
374,
18,
25,
225,
2437,
1769,
203,
3639,
9604,
18927,
12,
20,
92,
27,
6840,
507,
69,
8942,
74,
8204,
3247,
72,
5324,
3461,
6028,
71,
2
] |
pragma solidity ^0.4.23;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
* ERC20 interface
* see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) constant returns (uint);
function allowance(address owner, address spender) constant returns (uint);
function transfer(address to, uint value) returns (bool ok);
function transferFrom(address from, address to, uint value) returns (bool ok);
function approve(address spender, uint value) returns (bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract ERC223 is ERC20 {
function transfer(address to, uint value, bytes data) returns (bool ok);
function transferFrom(address from, address to, uint value, bytes data) returns (bool ok);
}
/*
Base class contracts willing to accept ERC223 token transfers must conform to.
Sender: msg.sender to the token contract, the address originating the token transfer.
- For user originated transfers sender will be equal to tx.origin
- For contract originated transfers, tx.origin will be the user that made the tx that produced the transfer.
Origin: the origin address from whose balance the tokens are sent
- For transfer(), origin = msg.sender
- For transferFrom() origin = _from to token contract
Value is the amount of tokens sent
Data is arbitrary data sent with the token transfer. Simulates ether tx.data
From, origin and value shouldn't be trusted unless the token contract is trusted.
If sender == tx.origin, it is safe to trust it regardless of the token.
*/
contract ERC223Receiver {
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) returns (bool ok);
}
/**
* Math operations with safety checks
*/
contract 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 max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
/*function assert(bool assertion) internal {
if (!assertion) {
throw;
}
}*/
}
/**
* Standard ERC20 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, SafeMath {
mapping(address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
function transfer(address _to, uint _value) returns (bool success) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because safeSub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
balances[_to] = safeAdd(balances[_to], _value);
balances[_from] = safeSub(balances[_from], _value);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
contract KinguinKrowns is ERC223, StandardToken {
address public owner; // token owner adddres
string public constant name = "PINGUINS";
string public constant symbol = "PGS";
uint8 public constant decimals = 18;
// uint256 public totalSupply; // defined in ERC20 contract
function KinguinKrowns() {
owner = msg.sender;
totalSupply = 100000000 * (10**18); // 100 mln
balances[msg.sender] = totalSupply;
}
/*
//only do if call is from owner modifier
modifier onlyOwner() {
if (msg.sender != owner) throw;
_;
}*/
//function that is called when a user or another contract wants to transfer funds
function transfer(address _to, uint _value, bytes _data) returns (bool success) {
//filtering if the target is a contract with bytecode inside it
if (!super.transfer(_to, _value)) throw; // do a normal token transfer
if (isContract(_to)) return contractFallback(msg.sender, _to, _value, _data);
return true;
}
function transferFrom(address _from, address _to, uint _value, bytes _data) returns (bool success) {
if (!super.transferFrom(_from, _to, _value)) throw; // do a normal token transfer
if (isContract(_to)) return contractFallback(_from, _to, _value, _data);
return true;
}
function transfer(address _to, uint _value) returns (bool success) {
return transfer(_to, _value, new bytes(0));
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
return transferFrom(_from, _to, _value, new bytes(0));
}
//function that is called when transaction target is a contract
function contractFallback(address _origin, address _to, uint _value, bytes _data) private returns (bool success) {
ERC223Receiver receiver = ERC223Receiver(_to);
return receiver.tokenFallback(msg.sender, _origin, _value, _data);
}
//assemble the given address bytecode. If bytecode exists then the _addr is a contract.
function isContract(address _addr) private returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
// returns krown balance of given address
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
}
contract KinguinIco is SafeMath, ERC223Receiver {
address constant public superOwner = 0xcEbb7454429830C92606836350569A17207dA857;
address public owner; // contract owner address
address public api; // address of api manager
KinguinKrowns public krs; // handler to KRS token contract
// rounds data storage:
struct IcoRoundData {
uint rMinEthPayment; // set minimum ETH payment
uint rKrsUsdFixed; // set KRS/USD fixed ratio for calculation of krown amount to be sent,
uint rKycTreshold; // KYC treshold in EUR (needed for check whether incoming payment requires KYC/AML verified address)
uint rMinKrsCap; // minimum amount of KRS to be sent during a round
uint rMaxKrsCap; // maximum amount of KRS to be sent during a round
uint rStartBlock; // number of blockchain start block for a round
uint rEndBlock; // number of blockchain end block for a round
uint rEthPaymentsAmount; // sum of ETH tokens received from participants during a round
uint rEthPaymentsCount; // counter of ETH payments during a round
uint rSentKrownsAmount; // sum of ETH tokens received from participants during a round
uint rSentKrownsCount; // counter of KRS transactions during a round
bool roundCompleted; // flag whether a round has finished
}
mapping(uint => IcoRoundData) public icoRounds; // table of rounds data: ico number, ico record
mapping(address => bool) public allowedAdresses; // list of KYC/AML approved wallets: participant address, allowed/not allowed
struct RoundPayments { // structure for storing sum of payments
uint round;
uint amount;
}
// amount of payments from the same address during each round
// (to catch multiple payments to check KYC/AML approvance): participant address, payments record
mapping(address => RoundPayments) public paymentsFromAddress;
uint public ethEur; // current EUR/ETH exchange rate (for AML check)
uint public ethUsd; // current ETH/USD exchange rate (sending KRS for ETH calc)
uint public krsUsd; // current KRS/USD exchange rate (sending KRS for ETH calc)
uint public rNo; // counter for rounds
bool public icoInProgress; // ico status flag
bool public apiAccessDisabled; // api access security flag
event LogReceivedEth(address from, uint value, uint block); // publish an event about incoming ETH
event LogSentKrs(address to, uint value, uint block); // publish an event about sent KRS
// execution allowed only for contract superowner
modifier onlySuperOwner() {
require(msg.sender == superOwner);
_;
}
// execution allowed only for contract owner
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// execution allowed only for contract owner or api address
modifier onlyOwnerOrApi() {
require(msg.sender == owner || msg.sender == api);
if (msg.sender == api && api != owner) {
require(!apiAccessDisabled);
}
_;
}
function KinguinIco() {
owner = msg.sender; // this contract owner
api = msg.sender; // initially api address is the contract owner's address
krs = KinguinKrowns(0xdfb410994b66778bd6cc2c82e8ffe4f7b2870006); // KRS token
}
// receiving ETH and sending KRS
function () payable {
if(msg.sender != owner) { // if ETH comes from other than the contract owner address
if(block.number >= icoRounds[rNo].rStartBlock && block.number <= icoRounds[rNo].rEndBlock && !icoInProgress) {
icoInProgress = true;
}
require(block.number >= icoRounds[rNo].rStartBlock && block.number <= icoRounds[rNo].rEndBlock && !icoRounds[rNo].roundCompleted); // allow payments only during the ico round
require(msg.value >= icoRounds[rNo].rMinEthPayment); // minimum eth payment
require(ethEur > 0); // ETH/EUR rate for AML must be set earlier
require(ethUsd > 0); // ETH/USD rate for conversion to KRS
uint krowns4eth;
if(icoRounds[rNo].rKrsUsdFixed > 0) { // KRS has fixed ratio to USD
krowns4eth = safeDiv(safeMul(safeMul(msg.value, ethUsd), uint(100)), icoRounds[rNo].rKrsUsdFixed);
} else { // KRS/USD is traded on exchanges
require(krsUsd > 0); // KRS/USD rate for conversion to KRS
krowns4eth = safeDiv(safeMul(safeMul(msg.value, ethUsd), uint(100)), krsUsd);
}
require(safeAdd(icoRounds[rNo].rSentKrownsAmount, krowns4eth) <= icoRounds[rNo].rMaxKrsCap); // krs cap per round
if(paymentsFromAddress[msg.sender].round != rNo) { // on mappings all keys are possible, so there is no checking for its existence
paymentsFromAddress[msg.sender].round = rNo; // on new round set to current round
paymentsFromAddress[msg.sender].amount = 0; // zeroing amount on new round
}
if(safeMul(ethEur, safeDiv(msg.value, 10**18)) >= icoRounds[rNo].rKycTreshold || // if payment from this sender requires to be from KYC/AML approved address
// if sum of payments from this sender address requires to be from KYC/AML approved address
safeMul(ethEur, safeDiv(safeAdd(paymentsFromAddress[msg.sender].amount, msg.value), 10**18)) >= icoRounds[rNo].rKycTreshold) {
require(allowedAdresses[msg.sender]); // only KYC/AML allowed address
}
icoRounds[rNo].rEthPaymentsAmount = safeAdd(icoRounds[rNo].rEthPaymentsAmount, msg.value);
icoRounds[rNo].rEthPaymentsCount += 1;
paymentsFromAddress[msg.sender].amount = safeAdd(paymentsFromAddress[msg.sender].amount, msg.value);
LogReceivedEth(msg.sender, msg.value, block.number);
icoRounds[rNo].rSentKrownsAmount = safeAdd(icoRounds[rNo].rSentKrownsAmount, krowns4eth);
icoRounds[rNo].rSentKrownsCount += 1;
krs.transfer(msg.sender, krowns4eth);
LogSentKrs(msg.sender, krowns4eth, block.number);
} else { // owner can always pay-in (and trigger round start/stop)
if(block.number >= icoRounds[rNo].rStartBlock && block.number <= icoRounds[rNo].rEndBlock && !icoInProgress) {
icoInProgress = true;
}
if(block.number > icoRounds[rNo].rEndBlock && icoInProgress) {
endIcoRound();
}
}
}
// receiving tokens other than ETH
// ERC223 receiver implementation - https://github.com/aragon/ERC23/blob/master/contracts/implementation/Standard223Receiver.sol
Tkn tkn;
struct Tkn {
address addr;
address sender;
address origin;
uint256 value;
bytes data;
bytes4 sig;
}
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) returns (bool ok) {
if (!supportsToken(msg.sender)) return false;
return true;
}
function getSig(bytes _data) private returns (bytes4 sig) {
uint l = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < l; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (l - 1 - i))));
}
}
bool __isTokenFallback;
modifier tokenPayable {
if (!__isTokenFallback) throw;
_;
}
function supportsToken(address token) returns (bool) {
if (token == address(krs)) {
return true;
} else {
revert();
}
}
// end of ERC223 receiver implementation ------------------------------------
// set up a new ico round
function newIcoRound(uint _rMinEthPayment, uint _rKrsUsdFixed, uint _rKycTreshold,
uint _rMinKrsCap, uint _rMaxKrsCap, uint _rStartBlock, uint _rEndBlock) public onlyOwner {
require(!icoInProgress); // new round can be set up only after finished/cancelled the active one
require(rNo < 25); // limit of 25 rounds (with pre-ico)
rNo += 1; // increment round number, pre-ico has number 1
icoRounds[rNo] = IcoRoundData(_rMinEthPayment, _rKrsUsdFixed, _rKycTreshold, _rMinKrsCap, _rMaxKrsCap,
_rStartBlock, _rEndBlock, 0, 0, 0, 0, false); // rEthPaymentsAmount, rEthPaymentsCount, rSentKrownsAmount, rSentKrownsCount);
}
// remove current round, params only - it does not refund any ETH!
function removeCurrentIcoRound() public onlyOwner {
require(icoRounds[rNo].rEthPaymentsAmount == 0); // only if there was no payment already
require(!icoRounds[rNo].roundCompleted); // only current round can be removed
icoInProgress = false;
icoRounds[rNo].rMinEthPayment = 0;
icoRounds[rNo].rKrsUsdFixed = 0;
icoRounds[rNo].rKycTreshold = 0;
icoRounds[rNo].rMinKrsCap = 0;
icoRounds[rNo].rMaxKrsCap = 0;
icoRounds[rNo].rStartBlock = 0;
icoRounds[rNo].rEndBlock = 0;
icoRounds[rNo].rEthPaymentsAmount = 0;
icoRounds[rNo].rEthPaymentsCount = 0;
icoRounds[rNo].rSentKrownsAmount = 0;
icoRounds[rNo].rSentKrownsCount = 0;
if(rNo > 0) rNo -= 1;
}
function changeIcoRoundEnding(uint _rEndBlock) public onlyOwner {
require(icoRounds[rNo].rStartBlock > 0); // round must be set up earlier
icoRounds[rNo].rEndBlock = _rEndBlock;
}
// closes round automatically
function endIcoRound() private {
icoInProgress = false;
icoRounds[rNo].rEndBlock = block.number;
icoRounds[rNo].roundCompleted = true;
}
// close round manually - if needed
function endIcoRoundManually() public onlyOwner {
endIcoRound();
}
// add a verified KYC/AML address
function addAllowedAddress(address _address) public onlyOwnerOrApi {
allowedAdresses[_address] = true;
}
function removeAllowedAddress(address _address) public onlyOwnerOrApi {
delete allowedAdresses[_address];
}
// set exchange rate for ETH/EUR - needed for check whether incoming payment
// is more than xxxx EUR (thus requires KYC/AML verified address)
function setEthEurRate(uint _ethEur) public onlyOwnerOrApi {
ethEur = _ethEur;
}
// set exchange rate for ETH/USD
function setEthUsdRate(uint _ethUsd) public onlyOwnerOrApi {
ethUsd = _ethUsd;
}
// set exchange rate for KRS/USD
function setKrsUsdRate(uint _krsUsd) public onlyOwnerOrApi {
krsUsd = _krsUsd;
}
// set all three exchange rates: ETH/EUR, ETH/USD, KRS/USD
function setAllRates(uint _ethEur, uint _ethUsd, uint _krsUsd) public onlyOwnerOrApi {
ethEur = _ethEur;
ethUsd = _ethUsd;
krsUsd = _krsUsd;
}
// send KRS from the contract to a given address (for BTC and FIAT payments)
function sendKrs(address _receiver, uint _amount) public onlyOwnerOrApi {
krs.transfer(_receiver, _amount);
}
// transfer KRS from other holder, up to amount allowed through krs.approve() function
function getKrsFromApproved(address _from, uint _amount) public onlyOwnerOrApi {
krs.transferFrom(_from, address(this), _amount);
}
// send ETH from the contract to a given address
function sendEth(address _receiver, uint _amount) public onlyOwner {
_receiver.transfer(_amount);
}
// disable/enable access from API - for security reasons
function disableApiAccess(bool _disabled) public onlyOwner {
apiAccessDisabled = _disabled;
}
// change API wallet address - for security reasons
function changeApi(address _address) public onlyOwner {
api = _address;
}
// change owner address
function changeOwner(address _address) public onlySuperOwner {
owner = _address;
}
}
library MicroWalletLib {
//change to production token address
KinguinKrowns constant token = KinguinKrowns(0xdfb410994b66778bd6cc2c82e8ffe4f7b2870006);
struct MicroWalletStorage {
uint krsAmount ;
address owner;
}
function toBytes(address a) private pure returns (bytes b){
assembly {
let m := mload(0x40)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
mstore(0x40, add(m, 52))
b := m
}
}
function processPayment(MicroWalletStorage storage self, address _sender) public {
require(msg.sender == address(token));
if (self.owner == _sender) { //closing MicroWallet
self.krsAmount = 0;
return;
}
require(self.krsAmount > 0);
uint256 currentBalance = token.balanceOf(address(this));
require(currentBalance >= self.krsAmount);
if(currentBalance > self.krsAmount) {
//return rest of the token
require(token.transfer(_sender, currentBalance - self.krsAmount));
}
require(token.transfer(self.owner, self.krsAmount, toBytes(_sender)));
self.krsAmount = 0;
}
}
contract KinguinVault is Ownable, ERC223Receiver {
mapping(uint=>address) public microWalletPayments;
mapping(uint=>address) public microWalletsAddrs;
mapping(address=>uint) public microWalletsIDs;
mapping(uint=>uint) public microWalletPaymentBlockNr;
KinguinKrowns public token;
uint public uncleSafeNr = 5;
address public withdrawAddress;
modifier onlyWithdraw() {
require(withdrawAddress == msg.sender);
_;
}
constructor(KinguinKrowns _token) public {
token = _token;
withdrawAddress = owner;
}
function createMicroWallet(uint productOrderID, uint krsAmount) onlyOwner public {
require(productOrderID != 0 && microWalletsAddrs[productOrderID] == address(0x0));
microWalletsAddrs[productOrderID] = new MicroWallet(krsAmount);
microWalletsIDs[microWalletsAddrs[productOrderID]] = productOrderID;
}
function getMicroWalletAddress(uint productOrderID) public view returns(address) {
return microWalletsAddrs[productOrderID];
}
function closeMicroWallet(uint productOrderID) onlyOwner public {
token.transfer(microWalletsAddrs[productOrderID], 0);
}
function checkIfOnUncle(uint currentBlockNr, uint transBlockNr) private view returns (bool) {
if((currentBlockNr - transBlockNr) < uncleSafeNr) {
return true;
}
return false;
}
function setUncleSafeNr(uint newUncleSafeNr) onlyOwner public {
uncleSafeNr = newUncleSafeNr;
}
function getProductOrderPayer(uint productOrderID) public view returns (address) {
if (checkIfOnUncle(block.number, microWalletPaymentBlockNr[productOrderID])) {
return 0;
}
return microWalletPayments[productOrderID];
}
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) public returns (bool) {
require(msg.sender == address(token));
if(microWalletsIDs[_sender] > 0) {
microWalletPayments[microWalletsIDs[_sender]] = bytesToAddr(_data);
microWalletPaymentBlockNr[microWalletsIDs[_sender]] = block.number;
}
return true;
}
function setWithdrawAccount(address _addr) onlyWithdraw public {
withdrawAddress = _addr;
}
function withdrawKrowns(address wallet, uint amount) onlyWithdraw public {
require(wallet != address(0x0));
token.transfer(wallet, amount);
}
function bytesToAddr (bytes b) private pure returns (address) {
uint result = 0;
for (uint i = b.length-1; i+1 > 0; i--) {
uint c = uint(b[i]);
uint to_inc = c * ( 16 ** ((b.length - i-1) * 2));
result += to_inc;
}
return address(result);
}
}
contract MicroWallet is ERC223Receiver {
MicroWalletLib.MicroWalletStorage private mwStorage;
constructor(uint _krsAmount) public {
mwStorage.krsAmount = _krsAmount;
mwStorage.owner = msg.sender;
}
function tokenFallback(address _sender, address _origin, uint _value, bytes _data) public returns (bool) {
MicroWalletLib.processPayment(mwStorage, _sender);
return true;
}
}
|
set exchange rate for KRS/USD
|
function setKrsUsdRate(uint _krsUsd) public onlyOwnerOrApi {
krsUsd = _krsUsd;
}
| 6,979,758 |
[
1,
542,
7829,
4993,
364,
1475,
13225,
19,
3378,
40,
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,
445,
444,
47,
5453,
3477,
72,
4727,
12,
11890,
389,
79,
5453,
3477,
72,
13,
1071,
1338,
5541,
1162,
3064,
288,
203,
565,
417,
5453,
3477,
72,
273,
389,
79,
5453,
3477,
72,
31,
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
] |
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, 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.
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/interfaces/IStrategy.sol
pragma solidity 0.5.11;
/**
* @title Platform interface to integrate with lending platform like Compound, AAVE etc.
*/
interface IStrategy {
/**
* @dev Deposit the given asset to platform
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount) external;
/**
* @dev Deposit the entire balance of all supported assets in the Strategy
* to the platform
*/
function depositAll() external;
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external;
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function withdrawAll() external;
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
/**
* @dev The address of the reward token for the Strategy.
*/
function rewardTokenAddress() external pure returns (address);
/**
* @dev The threshold (denominated in the reward token) over which the
* vault will auto harvest on allocate calls.
*/
function rewardLiquidationThreshold() external pure returns (uint256);
}
// File: contracts/governance/Governable.sol
pragma solidity 0.5.11;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
// keccak256("OUSD.governor");
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
// keccak256("OUSD.pending.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
// keccak256("OUSD.reentry.status");
bytes32
private constant reentryStatusPosition = 0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535;
// See OpenZeppelin ReentrancyGuard implementation
uint256 constant _NOT_ENTERED = 1;
uint256 constant _ENTERED = 2;
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
/**
* @dev Returns the address of the current Governor.
*/
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
/**
* @dev Returns the address of the pending Governor.
*/
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @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() {
bytes32 position = reentryStatusPosition;
uint256 _reentry_status;
assembly {
_reentry_status := sload(position)
}
// On the first call to nonReentrant, _notEntered will be true
require(_reentry_status != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
assembly {
sstore(position, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(position, _NOT_ENTERED)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: contracts/utils/InitializableERC20Detailed.sol
pragma solidity 0.5.11;
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
contract InitializableERC20Detailed is IERC20 {
// Storage gap to skip storage from prior to OUSD reset
uint256[100] private _____gap;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/utils/StableMath.sol
pragma solidity 0.5.11;
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17
*/
function scaleBy(uint256 x, int8 adjustment)
internal
pure
returns (uint256)
{
if (adjustment > 0) {
x = x.mul(10**uint256(adjustment));
} else if (adjustment < 0) {
x = x.div(10**uint256(adjustment * -1));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// File: contracts/token/OUSD.sol
pragma solidity 0.5.11;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
/**
* NOTE that this is an ERC20 token but the invariant that the sum of
* balanceOf(x) for all x is not >= totalSupply(). This is a consequence of the
* rebasing design. Any integrations with OUSD should be aware.
*/
contract OUSD is Initializable, InitializableERC20Detailed, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
enum RebaseOptions { NotSet, OptOut, OptIn }
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 public _totalSupply;
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
mapping(address => uint256) private _creditBalances;
uint256 public rebasingCredits;
uint256 public rebasingCreditsPerToken;
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => RebaseOptions) public rebaseState;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the _amount of base units owned by the
* specified address.
*/
function balanceOf(address _account) public view returns (uint256) {
if (_creditBalances[_account] == 0) return 0;
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
return (_creditBalances[_account], _creditsPerToken(_account));
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the _amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(
_value <= balanceOf(msg.sender),
"Transfer greater than balance"
);
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The _amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(_value <= balanceOf(_from), "Transfer greater than balance");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
bool isNonRebasingTo = _isNonRebasingAccount(_to);
bool isNonRebasingFrom = _isNonRebasingAccount(_from);
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
rebasingCredits = rebasingCredits.add(creditsCredited);
}
}
/**
* @dev Function to check the _amount of tokens that an owner has allowed to a _spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @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 _spender, uint256 _value) public returns (bool) {
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the _amount of tokens that an owner has allowed to a _spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param _spender The address which will spend the funds.
* @param _addedValue The _amount of tokens to increase the allowance by.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
public
returns (bool)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the _amount of tokens that an owner has allowed to a _spender.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The _amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _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 nonReentrant {
require(_account != address(0), "Mint to the zero address");
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
rebasingCredits = rebasingCredits.add(creditAmount);
}
_totalSupply = _totalSupply.add(_amount);
require(_totalSupply < MAX_SUPPLY, "Max supply");
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
_burn(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 nonReentrant {
require(_account != address(0), "Burn from the zero address");
if (_amount == 0) {
return;
}
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
// Remove from the credit tallies and non-rebasing supply
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
rebasingCredits = rebasingCredits.sub(creditAmount);
}
_totalSupply = _totalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return rebasingCreditsPerToken;
}
}
/**
* @dev Is an account using rebasing accounting or non-rebasing accounting?
* Also, ensure contracts are non-rebasing if they have not opted in.
* @param _account Address of the account.
*/
function _isNonRebasingAccount(address _account) internal returns (bool) {
bool isContract = Address.isContract(_account);
if (isContract && rebaseState[_account] == RebaseOptions.NotSet) {
_ensureRebasingMigration(_account);
}
return nonRebasingCreditsPerToken[_account] > 0;
}
/**
* @dev Ensures internal account for rebasing and non-rebasing credits and
* supply is updated following deployment of frozen yield change.
*/
function _ensureRebasingMigration(address _account) internal {
if (nonRebasingCreditsPerToken[_account] == 0) {
if (_creditBalances[_account] == 0) {
// Since there is no existing balance, we can directly set to
// high resolution, and do not have to do any other bookkeeping
nonRebasingCreditsPerToken[_account] = 1e27;
} else {
// Migrate an existing account:
// Set fixed credits per token for this account
nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken;
// Update non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account));
// Update credit tallies
rebasingCredits = rebasingCredits.sub(
_creditBalances[_account]
);
}
}
}
/**
* @dev Add a contract address to the non rebasing exception list. I.e. the
* address's balance will be part of rebases so the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public nonReentrant {
require(_isNonRebasingAccount(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
// Decreasing non rebasing supply
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
_creditBalances[msg.sender] = newCreditBalance;
// Increase rebasing credits, totalSupply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.add(_creditBalances[msg.sender]);
rebaseState[msg.sender] = RebaseOptions.OptIn;
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Remove a contract address to the non rebasing exception list.
*/
function rebaseOptOut() public nonReentrant {
require(!_isNonRebasingAccount(msg.sender), "Account has not opted in");
// Increase non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
// Set fixed credits per token
nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
// Decrease rebasing credits, total supply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.sub(_creditBalances[msg.sender]);
// Mark explicitly opted out of rebasing
rebaseState[msg.sender] = RebaseOptions.OptOut;
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
* @return uint256 representing the new total supply.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
nonReentrant
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return;
}
_totalSupply = _newTotalSupply > MAX_SUPPLY
? MAX_SUPPLY
: _newTotalSupply;
rebasingCreditsPerToken = rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
require(rebasingCreditsPerToken > 0, "Invalid change in supply");
_totalSupply = rebasingCredits
.divPrecisely(rebasingCreditsPerToken)
.add(nonRebasingSupply);
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
}
}
// File: contracts/interfaces/IBasicToken.sol
pragma solidity 0.5.11;
interface IBasicToken {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/utils/Helpers.sol
pragma solidity 0.5.11;
library Helpers {
/**
* @notice Fetch the `symbol()` from an ERC20 token
* @dev Grabs the `symbol()` from a contract
* @param _token Address of the ERC20 token
* @return string Symbol of the ERC20 token
*/
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token) internal view returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(
decimals >= 4 && decimals <= 18,
"Token must have sufficient decimal places"
);
return decimals;
}
}
// File: contracts/vault/VaultStorage.sol
pragma solidity 0.5.11;
/**
* @title OUSD VaultStorage Contract
* @notice The VaultStorage contract defines the storage for the Vault contracts
* @author Origin Protocol Inc
*/
contract VaultStorage is Initializable, Governable {
using SafeMath for uint256;
using StableMath for uint256;
using SafeMath for int256;
using SafeERC20 for IERC20;
event AssetSupported(address _asset);
event AssetDefaultStrategyUpdated(address _asset, address _strategy);
event StrategyApproved(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event CapitalPaused();
event CapitalUnpaused();
event RebasePaused();
event RebaseUnpaused();
event VaultBufferUpdated(uint256 _vaultBuffer);
event RedeemFeeUpdated(uint256 _redeemFeeBps);
event PriceProviderUpdated(address _priceProvider);
event AllocateThresholdUpdated(uint256 _threshold);
event RebaseThresholdUpdated(uint256 _threshold);
event UniswapUpdated(address _address);
event StrategistUpdated(address _address);
event MaxSupplyDiffChanged(uint256 maxSupplyDiff);
event YieldDistribution(address _to, uint256 _yield, uint256 _fee);
event TrusteeFeeBpsChanged(uint256 _basis);
event TrusteeAddressChanged(address _address);
// Assets supported by the Vault, i.e. Stablecoins
struct Asset {
bool isSupported;
}
mapping(address => Asset) assets;
address[] allAssets;
// Strategies approved for use by the Vault
struct Strategy {
bool isSupported;
uint256 _deprecated; // Deprecated storage slot
}
mapping(address => Strategy) strategies;
address[] allStrategies;
// Address of the Oracle price provider contract
address public priceProvider;
// Pausing bools
bool public rebasePaused = false;
bool public capitalPaused = true;
// Redemption fee in basis points
uint256 public redeemFeeBps;
// Buffer of assets to keep in Vault to handle (most) withdrawals
uint256 public vaultBuffer;
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
// Mints over this amount automatically rebase. 18 decimals.
uint256 public rebaseThreshold;
OUSD oUSD;
//keccak256("OUSD.vault.governor.admin.impl");
bytes32 constant adminImplPosition = 0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9;
// Address of the contract responsible for post rebase syncs with AMMs
address private _deprecated_rebaseHooksAddr = address(0);
// Address of Uniswap
address public uniswapAddr = address(0);
// Address of the Strategist
address public strategistAddr = address(0);
// Mapping of asset address to the Strategy that they should automatically
// be allocated to
mapping(address => address) public assetDefaultStrategies;
uint256 public maxSupplyDiff;
// Trustee contract that can collect a percentage of yield
address public trusteeAddress;
// Amount of yield collected in basis points
uint256 public trusteeFeeBps;
/**
* @dev set the implementation for the admin, this needs to be in a base class else we cannot set it
* @param newImpl address of the implementation
*/
function setAdminImpl(address newImpl) external onlyGovernor {
require(
Address.isContract(newImpl),
"new implementation is not a contract"
);
bytes32 position = adminImplPosition;
assembly {
sstore(position, newImpl)
}
}
}
// File: contracts/interfaces/IOracle.sol
pragma solidity 0.5.11;
interface IOracle {
/**
* @dev returns the asset price in USD, 8 decimal digits.
*/
function price(address asset) external view returns (uint256);
}
// File: contracts/interfaces/IVault.sol
pragma solidity 0.5.11;
interface IVault {
event AssetSupported(address _asset);
event StrategyApproved(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event DepositsPaused();
event DepositsUnpaused();
// Governable.sol
function transferGovernance(address _newGovernor) external;
function claimGovernance() external;
function governor() external view returns (address);
// VaultAdmin.sol
function setPriceProvider(address _priceProvider) external;
function priceProvider() external view returns (address);
function setRedeemFeeBps(uint256 _redeemFeeBps) external;
function redeemFeeBps() external view returns (uint256);
function setVaultBuffer(uint256 _vaultBuffer) external;
function vaultBuffer() external view returns (uint256);
function setAutoAllocateThreshold(uint256 _threshold) external;
function autoAllocateThreshold() external view returns (uint256);
function setRebaseThreshold(uint256 _threshold) external;
function rebaseThreshold() external view returns (uint256);
function setStrategistAddr(address _address) external;
function strategistAddr() external view returns (address);
function setUniswapAddr(address _address) external;
function uniswapAddr() external view returns (address);
function setMaxSupplyDiff(uint256 _maxSupplyDiff) external;
function maxSupplyDiff() external view returns (uint256);
function setTrusteeAddress(address _address) external;
function trusteeAddress() external view returns (address);
function setTrusteeFeeBps(uint256 _basis) external;
function trusteeFeeBps() external view returns (uint256);
function supportAsset(address _asset) external;
function approveStrategy(address _addr) external;
function removeStrategy(address _addr) external;
function setAssetDefaultStrategy(address _asset, address _strategy)
external;
function assetDefaultStrategies(address _asset)
external
view
returns (address);
function pauseRebase() external;
function unpauseRebase() external;
function rebasePaused() external view returns (bool);
function pauseCapital() external;
function unpauseCapital() external;
function capitalPaused() external view returns (bool);
function transferToken(address _asset, uint256 _amount) external;
function harvest() external;
function harvest(address _strategyAddr) external;
function priceUSDMint(address asset) external view returns (uint256);
function priceUSDRedeem(address asset) external view returns (uint256);
function withdrawAllFromStrategy(address _strategyAddr) external;
function withdrawAllFromStrategies() external;
// VaultCore.sol
function mint(
address _asset,
uint256 _amount,
uint256 _minimumOusdAmount
) external;
function mintMultiple(
address[] calldata _assets,
uint256[] calldata _amount,
uint256 _minimumOusdAmount
) external;
function redeem(uint256 _amount, uint256 _minimumUnitAmount) external;
function redeemAll(uint256 _minimumUnitAmount) external;
function allocate() external;
function reallocate(
address _strategyFromAddress,
address _strategyToAddress,
address[] calldata _assets,
uint256[] calldata _amounts
) external;
function rebase() external;
function totalValue() external view returns (uint256 value);
function checkBalance() external view returns (uint256);
function checkBalance(address _asset) external view returns (uint256);
function calculateRedeemOutputs(uint256 _amount)
external
view
returns (uint256[] memory);
function getAssetCount() external view returns (uint256);
function getAllAssets() external view returns (address[] memory);
function getStrategyCount() external view returns (uint256);
function isSupportedAsset(address _asset) external view returns (bool);
}
// File: contracts/interfaces/IBuyback.sol
pragma solidity 0.5.11;
interface IBuyback {
function swap() external;
}
// File: contracts/vault/VaultCore.sol
pragma solidity 0.5.11;
/**
* @title OUSD Vault Contract
* @notice The Vault contract stores assets. On a deposit, OUSD will be minted
and sent to the depositor. On a withdrawal, OUSD will be burned and
assets will be sent to the withdrawer. The Vault accepts deposits of
interest form yield bearing strategies which will modify the supply
of OUSD.
* @author Origin Protocol Inc
*/
contract VaultCore is VaultStorage {
uint256 constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/**
* @dev Verifies that the rebasing is not paused.
*/
modifier whenNotRebasePaused() {
require(!rebasePaused, "Rebasing paused");
_;
}
/**
* @dev Verifies that the deposits are not paused.
*/
modifier whenNotCapitalPaused() {
require(!capitalPaused, "Capital paused");
_;
}
/**
* @dev Deposit a supported asset and mint OUSD.
* @param _asset Address of the asset being deposited
* @param _amount Amount of the asset being deposited
* @param _minimumOusdAmount Minimum OUSD to mint
*/
function mint(
address _asset,
uint256 _amount,
uint256 _minimumOusdAmount
) external whenNotCapitalPaused nonReentrant {
require(assets[_asset].isSupported, "Asset is not supported");
require(_amount > 0, "Amount must be greater than 0");
uint256 price = IOracle(priceProvider).price(_asset);
if (price > 1e8) {
price = 1e8;
}
uint256 assetDecimals = Helpers.getDecimals(_asset);
uint256 unitAdjustedDeposit = _amount.scaleBy(int8(18 - assetDecimals));
uint256 priceAdjustedDeposit = _amount.mulTruncateScale(
price.scaleBy(int8(10)), // 18-8 because oracles have 8 decimals precision
10**assetDecimals
);
if (_minimumOusdAmount > 0) {
require(
priceAdjustedDeposit >= _minimumOusdAmount,
"Mint amount lower than minimum"
);
}
emit Mint(msg.sender, priceAdjustedDeposit);
// Rebase must happen before any transfers occur.
if (unitAdjustedDeposit >= rebaseThreshold && !rebasePaused) {
_rebase();
}
// Mint matching OUSD
oUSD.mint(msg.sender, priceAdjustedDeposit);
// Transfer the deposited coins to the vault
IERC20 asset = IERC20(_asset);
asset.safeTransferFrom(msg.sender, address(this), _amount);
if (unitAdjustedDeposit >= autoAllocateThreshold) {
_allocate();
}
}
/**
* @dev Mint for multiple assets in the same call.
* @param _assets Addresses of assets being deposited
* @param _amounts Amount of each asset at the same index in the _assets
* to deposit.
* @param _minimumOusdAmount Minimum OUSD to mint
*/
function mintMultiple(
address[] calldata _assets,
uint256[] calldata _amounts,
uint256 _minimumOusdAmount
) external whenNotCapitalPaused nonReentrant {
require(_assets.length == _amounts.length, "Parameter length mismatch");
uint256 unitAdjustedTotal = 0;
uint256 priceAdjustedTotal = 0;
uint256[] memory assetPrices = _getAssetPrices(false);
for (uint256 j = 0; j < _assets.length; j++) {
// In memoriam
require(assets[_assets[j]].isSupported, "Asset is not supported");
require(_amounts[j] > 0, "Amount must be greater than 0");
for (uint256 i = 0; i < allAssets.length; i++) {
if (_assets[j] == allAssets[i]) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
uint256 price = assetPrices[i];
if (price > 1e18) {
price = 1e18;
}
unitAdjustedTotal = unitAdjustedTotal.add(
_amounts[j].scaleBy(int8(18 - assetDecimals))
);
priceAdjustedTotal = priceAdjustedTotal.add(
_amounts[j].mulTruncateScale(price, 10**assetDecimals)
);
}
}
}
if (_minimumOusdAmount > 0) {
require(
priceAdjustedTotal >= _minimumOusdAmount,
"Mint amount lower than minimum"
);
}
emit Mint(msg.sender, priceAdjustedTotal);
// Rebase must happen before any transfers occur.
if (unitAdjustedTotal >= rebaseThreshold && !rebasePaused) {
_rebase();
}
oUSD.mint(msg.sender, priceAdjustedTotal);
for (uint256 i = 0; i < _assets.length; i++) {
IERC20 asset = IERC20(_assets[i]);
asset.safeTransferFrom(msg.sender, address(this), _amounts[i]);
}
if (unitAdjustedTotal >= autoAllocateThreshold) {
_allocate();
}
}
/**
* @dev Withdraw a supported asset and burn OUSD.
* @param _amount Amount of OUSD to burn
* @param _minimumUnitAmount Minimum stablecoin units to receive in return
*/
function redeem(uint256 _amount, uint256 _minimumUnitAmount)
public
whenNotCapitalPaused
nonReentrant
{
_redeem(_amount, _minimumUnitAmount);
}
/**
* @dev Withdraw a supported asset and burn OUSD.
* @param _amount Amount of OUSD to burn
* @param _minimumUnitAmount Minimum stablecoin units to receive in return
*/
function _redeem(uint256 _amount, uint256 _minimumUnitAmount) internal {
require(_amount > 0, "Amount must be greater than 0");
// Calculate redemption outputs
(
uint256[] memory outputs,
uint256 _backingValue
) = _calculateRedeemOutputs(_amount);
// Check that OUSD is backed by enough assets
uint256 _totalSupply = oUSD.totalSupply();
if (maxSupplyDiff > 0) {
// Allow a max difference of maxSupplyDiff% between
// backing assets value and OUSD total supply
uint256 diff = _totalSupply.divPrecisely(_backingValue);
require(
(diff > 1e18 ? diff.sub(1e18) : uint256(1e18).sub(diff)) <=
maxSupplyDiff,
"Backing supply liquidity error"
);
}
emit Redeem(msg.sender, _amount);
// Send outputs
for (uint256 i = 0; i < allAssets.length; i++) {
if (outputs[i] == 0) continue;
IERC20 asset = IERC20(allAssets[i]);
if (asset.balanceOf(address(this)) >= outputs[i]) {
// Use Vault funds first if sufficient
asset.safeTransfer(msg.sender, outputs[i]);
} else {
address strategyAddr = assetDefaultStrategies[allAssets[i]];
if (strategyAddr != address(0)) {
// Nothing in Vault, but something in Strategy, send from there
IStrategy strategy = IStrategy(strategyAddr);
strategy.withdraw(msg.sender, allAssets[i], outputs[i]);
} else {
// Cant find funds anywhere
revert("Liquidity error");
}
}
}
if (_minimumUnitAmount > 0) {
uint256 unitTotal = 0;
for (uint256 i = 0; i < outputs.length; i++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
unitTotal = unitTotal.add(
outputs[i].scaleBy(int8(18 - assetDecimals))
);
}
require(
unitTotal >= _minimumUnitAmount,
"Redeem amount lower than minimum"
);
}
oUSD.burn(msg.sender, _amount);
// Until we can prove that we won't affect the prices of our assets
// by withdrawing them, this should be here.
// It's possible that a strategy was off on its asset total, perhaps
// a reward token sold for more or for less than anticipated.
if (_amount > rebaseThreshold && !rebasePaused) {
_rebase();
}
}
/**
* @notice Withdraw a supported asset and burn all OUSD.
* @param _minimumUnitAmount Minimum stablecoin units to receive in return
*/
function redeemAll(uint256 _minimumUnitAmount)
external
whenNotCapitalPaused
nonReentrant
{
_redeem(oUSD.balanceOf(msg.sender), _minimumUnitAmount);
}
/**
* @notice Allocate unallocated funds on Vault to strategies.
* @dev Allocate unallocated funds on Vault to strategies.
**/
function allocate() public whenNotCapitalPaused nonReentrant {
_allocate();
}
/**
* @notice Allocate unallocated funds on Vault to strategies.
* @dev Allocate unallocated funds on Vault to strategies.
**/
function _allocate() internal {
uint256 vaultValue = _totalValueInVault();
// Nothing in vault to allocate
if (vaultValue == 0) return;
uint256 strategiesValue = _totalValueInStrategies();
// We have a method that does the same as this, gas optimisation
uint256 calculatedTotalValue = vaultValue.add(strategiesValue);
// We want to maintain a buffer on the Vault so calculate a percentage
// modifier to multiply each amount being allocated by to enforce the
// vault buffer
uint256 vaultBufferModifier;
if (strategiesValue == 0) {
// Nothing in Strategies, allocate 100% minus the vault buffer to
// strategies
vaultBufferModifier = uint256(1e18).sub(vaultBuffer);
} else {
vaultBufferModifier = vaultBuffer.mul(calculatedTotalValue).div(
vaultValue
);
if (1e18 > vaultBufferModifier) {
// E.g. 1e18 - (1e17 * 10e18)/5e18 = 8e17
// (5e18 * 8e17) / 1e18 = 4e18 allocated from Vault
vaultBufferModifier = uint256(1e18).sub(vaultBufferModifier);
} else {
// We need to let the buffer fill
return;
}
}
if (vaultBufferModifier == 0) return;
// Iterate over all assets in the Vault and allocate the the appropriate
// strategy
for (uint256 i = 0; i < allAssets.length; i++) {
IERC20 asset = IERC20(allAssets[i]);
uint256 assetBalance = asset.balanceOf(address(this));
// No balance, nothing to do here
if (assetBalance == 0) continue;
// Multiply the balance by the vault buffer modifier and truncate
// to the scale of the asset decimals
uint256 allocateAmount = assetBalance.mulTruncate(
vaultBufferModifier
);
address depositStrategyAddr = assetDefaultStrategies[address(
asset
)];
if (depositStrategyAddr != address(0) && allocateAmount > 0) {
IStrategy strategy = IStrategy(depositStrategyAddr);
// Transfer asset to Strategy and call deposit method to
// mint or take required action
asset.safeTransfer(address(strategy), allocateAmount);
strategy.deposit(address(asset), allocateAmount);
}
}
// Harvest for all reward tokens above reward liquidation threshold
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
address rewardTokenAddress = strategy.rewardTokenAddress();
if (rewardTokenAddress != address(0)) {
uint256 liquidationThreshold = strategy
.rewardLiquidationThreshold();
if (liquidationThreshold == 0) {
// No threshold set, always harvest from strategy
IVault(address(this)).harvest(allStrategies[i]);
} else {
// Check balance against liquidation threshold
// Note some strategies don't hold the reward token balance
// on their contract so the liquidation threshold should be
// set to 0
IERC20 rewardToken = IERC20(rewardTokenAddress);
uint256 rewardTokenAmount = rewardToken.balanceOf(
allStrategies[i]
);
if (rewardTokenAmount >= liquidationThreshold) {
IVault(address(this)).harvest(allStrategies[i]);
}
}
}
}
// Trigger OGN Buyback
IBuyback(trusteeAddress).swap();
}
/**
* @dev Calculate the total value of assets held by the Vault and all
* strategies and update the supply of OUSD.
*/
function rebase() public whenNotRebasePaused nonReentrant {
_rebase();
}
/**
* @dev Calculate the total value of assets held by the Vault and all
* strategies and update the supply of OUSD, optionaly sending a
* portion of the yield to the trustee.
*/
function _rebase() internal whenNotRebasePaused {
uint256 ousdSupply = oUSD.totalSupply();
if (ousdSupply == 0) {
return;
}
uint256 vaultValue = _totalValue();
// Yield fee collection
address _trusteeAddress = trusteeAddress; // gas savings
if (_trusteeAddress != address(0) && (vaultValue > ousdSupply)) {
uint256 yield = vaultValue.sub(ousdSupply);
uint256 fee = yield.mul(trusteeFeeBps).div(10000);
require(yield > fee, "Fee must not be greater than yield");
if (fee > 0) {
oUSD.mint(_trusteeAddress, fee);
}
emit YieldDistribution(_trusteeAddress, yield, fee);
}
// Only rachet OUSD supply upwards
ousdSupply = oUSD.totalSupply(); // Final check should use latest value
if (vaultValue > ousdSupply) {
oUSD.changeSupply(vaultValue);
}
}
/**
* @dev Determine the total value of assets held by the vault and its
* strategies.
* @return uint256 value Total value in USD (1e18)
*/
function totalValue() external view returns (uint256 value) {
value = _totalValue();
}
/**
* @dev Internal Calculate the total value of the assets held by the
* vault and its strategies.
* @return uint256 value Total value in USD (1e18)
*/
function _totalValue() internal view returns (uint256 value) {
return _totalValueInVault().add(_totalValueInStrategies());
}
/**
* @dev Internal to calculate total value of all assets held in Vault.
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInVault() internal view returns (uint256 value) {
for (uint256 y = 0; y < allAssets.length; y++) {
IERC20 asset = IERC20(allAssets[y]);
uint256 assetDecimals = Helpers.getDecimals(allAssets[y]);
uint256 balance = asset.balanceOf(address(this));
if (balance > 0) {
value = value.add(balance.scaleBy(int8(18 - assetDecimals)));
}
}
}
/**
* @dev Internal to calculate total value of all assets held in Strategies.
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInStrategies() internal view returns (uint256 value) {
for (uint256 i = 0; i < allStrategies.length; i++) {
value = value.add(_totalValueInStrategy(allStrategies[i]));
}
}
/**
* @dev Internal to calculate total value of all assets held by strategy.
* @param _strategyAddr Address of the strategy
* @return uint256 Total value in ETH (1e18)
*/
function _totalValueInStrategy(address _strategyAddr)
internal
view
returns (uint256 value)
{
IStrategy strategy = IStrategy(_strategyAddr);
for (uint256 y = 0; y < allAssets.length; y++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[y]);
if (strategy.supportsAsset(allAssets[y])) {
uint256 balance = strategy.checkBalance(allAssets[y]);
if (balance > 0) {
value = value.add(
balance.scaleBy(int8(18 - assetDecimals))
);
}
}
}
}
/**
* @notice Get the balance of an asset held in Vault and all strategies.
* @param _asset Address of asset
* @return uint256 Balance of asset in decimals of asset
*/
function checkBalance(address _asset) external view returns (uint256) {
return _checkBalance(_asset);
}
/**
* @notice Get the balance of an asset held in Vault and all strategies.
* @param _asset Address of asset
* @return uint256 Balance of asset in decimals of asset
*/
function _checkBalance(address _asset)
internal
view
returns (uint256 balance)
{
IERC20 asset = IERC20(_asset);
balance = asset.balanceOf(address(this));
for (uint256 i = 0; i < allStrategies.length; i++) {
IStrategy strategy = IStrategy(allStrategies[i]);
if (strategy.supportsAsset(_asset)) {
balance = balance.add(strategy.checkBalance(_asset));
}
}
}
/**
* @notice Get the balance of all assets held in Vault and all strategies.
* @return uint256 Balance of all assets (1e18)
*/
function _checkBalance() internal view returns (uint256 balance) {
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 assetDecimals = Helpers.getDecimals(allAssets[i]);
balance = balance.add(
_checkBalance(allAssets[i]).scaleBy(int8(18 - assetDecimals))
);
}
}
/**
* @notice Calculate the outputs for a redeem function, i.e. the mix of
* coins that will be returned
*/
function calculateRedeemOutputs(uint256 _amount)
external
view
returns (uint256[] memory)
{
(
uint256[] memory outputs,
uint256 totalValue
) = _calculateRedeemOutputs(_amount);
return outputs;
}
/**
* @notice Calculate the outputs for a redeem function, i.e. the mix of
* coins that will be returned.
* @return Array of amounts respective to the supported assets
*/
function _calculateRedeemOutputs(uint256 _amount)
internal
view
returns (uint256[] memory outputs, uint256 totalBalance)
{
// We always give out coins in proportion to how many we have,
// Now if all coins were the same value, this math would easy,
// just take the percentage of each coin, and multiply by the
// value to be given out. But if coins are worth more than $1,
// then we would end up handing out too many coins. We need to
// adjust by the total value of coins.
//
// To do this, we total up the value of our coins, by their
// percentages. Then divide what we would otherwise give out by
// this number.
//
// Let say we have 100 DAI at $1.06 and 200 USDT at $1.00.
// So for every 1 DAI we give out, we'll be handing out 2 USDT
// Our total output ratio is: 33% * 1.06 + 66% * 1.00 = 1.02
//
// So when calculating the output, we take the percentage of
// each coin, times the desired output value, divided by the
// totalOutputRatio.
//
// For example, withdrawing: 30 OUSD:
// DAI 33% * 30 / 1.02 = 9.80 DAI
// USDT = 66 % * 30 / 1.02 = 19.60 USDT
//
// Checking these numbers:
// 9.80 DAI * 1.06 = $10.40
// 19.60 USDT * 1.00 = $19.60
//
// And so the user gets $10.40 + $19.60 = $30 worth of value.
uint256 assetCount = getAssetCount();
uint256[] memory assetPrices = _getAssetPrices(true);
uint256[] memory assetBalances = new uint256[](assetCount);
uint256[] memory assetDecimals = new uint256[](assetCount);
uint256 totalOutputRatio = 0;
outputs = new uint256[](assetCount);
// Calculate redeem fee
if (redeemFeeBps > 0) {
uint256 redeemFee = _amount.mul(redeemFeeBps).div(10000);
_amount = _amount.sub(redeemFee);
}
// Calculate assets balances and decimals once,
// for a large gas savings.
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 balance = _checkBalance(allAssets[i]);
uint256 decimals = Helpers.getDecimals(allAssets[i]);
assetBalances[i] = balance;
assetDecimals[i] = decimals;
totalBalance = totalBalance.add(
balance.scaleBy(int8(18 - decimals))
);
}
// Calculate totalOutputRatio
for (uint256 i = 0; i < allAssets.length; i++) {
uint256 price = assetPrices[i];
// Never give out more than one
// stablecoin per dollar of OUSD
if (price < 1e18) {
price = 1e18;
}
uint256 ratio = assetBalances[i]
.scaleBy(int8(18 - assetDecimals[i]))
.mul(price)
.div(totalBalance);
totalOutputRatio = totalOutputRatio.add(ratio);
}
// Calculate final outputs
uint256 factor = _amount.divPrecisely(totalOutputRatio);
for (uint256 i = 0; i < allAssets.length; i++) {
outputs[i] = assetBalances[i].mul(factor).div(totalBalance);
}
}
/**
* @notice Get an array of the supported asset prices in USD.
* @return uint256[] Array of asset prices in USD (1e18)
*/
function _getAssetPrices(bool useMax)
internal
view
returns (uint256[] memory assetPrices)
{
assetPrices = new uint256[](getAssetCount());
IOracle oracle = IOracle(priceProvider);
// Price from Oracle is returned with 8 decimals
// _amount is in assetDecimals
for (uint256 i = 0; i < allAssets.length; i++) {
assetPrices[i] = oracle.price(allAssets[i]).scaleBy(int8(18 - 8));
}
}
/***************************************
Utils
****************************************/
/**
* @dev Return the number of assets suppported by the Vault.
*/
function getAssetCount() public view returns (uint256) {
return allAssets.length;
}
/**
* @dev Return all asset addresses in order
*/
function getAllAssets() external view returns (address[] memory) {
return allAssets;
}
/**
* @dev Return the number of strategies active on the Vault.
*/
function getStrategyCount() external view returns (uint256) {
return allStrategies.length;
}
function isSupportedAsset(address _asset) external view returns (bool) {
return assets[_asset].isSupported;
}
/**
* @dev Falldown to the admin implementation
* @notice This is a catch all for all functions not declared in core
*/
function() external payable {
bytes32 slot = adminImplPosition;
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize)
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas, sload(slot), 0, calldatasize, 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize)
}
default {
return(0, returndatasize)
}
}
}
}
|
* @notice Calculate the outputs for a redeem function, i.e. the mix of coins that will be returned/
|
function calculateRedeemOutputs(uint256 _amount)
external
view
returns (uint256[] memory)
{
(
uint256[] memory outputs,
uint256 totalValue
) = _calculateRedeemOutputs(_amount);
return outputs;
}
| 12,110,814 |
[
1,
8695,
326,
6729,
364,
279,
283,
24903,
445,
16,
277,
18,
73,
18,
326,
6843,
434,
276,
9896,
716,
903,
506,
2106,
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,
4604,
426,
24903,
13856,
12,
11890,
5034,
389,
8949,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
8526,
3778,
13,
203,
565,
288,
203,
3639,
261,
203,
5411,
2254,
5034,
8526,
3778,
6729,
16,
203,
5411,
2254,
5034,
2078,
620,
203,
3639,
262,
273,
389,
11162,
426,
24903,
13856,
24899,
8949,
1769,
203,
3639,
327,
6729,
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
] |
pragma solidity >=0.4.21 <0.6.0;
/// @author Andrea Lisi, Samuel Fabrizi
/// @title RatingFunction
/// @notice This contract interface defines the method to compute the final score of a list of scores
interface RatingFunction {
modifier haveEqualLength(uint[] memory _s, uint[] memory _b) {
require(_s.length == _b.length);
_;
}
/// @notice Compute the final score given a bundle of rating information
/// @param _scores The array of scores
/// @param _blocks The array of blocks containing the scores
/// @param _valuesSkill The array of values about skill of item rated
function compute(uint[] calldata _scores,
uint[] calldata _blocks,
uint[] calldata _valuesSkill
) external pure returns(uint);
}
/// @title SimpleAverageFunction
/// @notice Compute the final score with simple average on the score values
contract SimpleAvarageFunction is RatingFunction {
/// @notice Compute the final score given a bundle of rating information
/// @param _scores The array of scores
/// @param _blocks The array of blocks containing the scores
/// @param _valuesSkill The array of values about skill of item rated
function compute(uint[] calldata _scores,
uint[] calldata _blocks,
uint[] calldata _valuesSkill) haveEqualLength(_scores, _blocks) external pure returns(uint) {
uint len = _scores.length;
if (len <= 0)
return 0;
// Simple average
uint total = 0;
for (uint i=0; i<len; i++)
total += _scores[i];
return total / len;
}
}
/// @title WeightedAverageFunction
/// @notice Compute the final score with a weighted average using the blocks
contract WeightedAverageFunction is RatingFunction {
/// @notice Compute the final score given a bundle of rating information
/// @param _scores The array of scores
/// @param _blocks The array of blocks containing the scores
/// @param _valuesSkill The array of values about skill of item rated
function compute(uint[] calldata _scores,
uint[] calldata _blocks,
uint[] calldata _valuesSkill
) haveEqualLength(_scores, _blocks) external pure returns(uint) {
uint len = _scores.length;
if (len <= 0)
return 0;
// Weighted average w.r.t. blocks
uint last = _blocks[len-1];
uint weightedScore = 0;
uint weightSum = 0;
for (uint i=0; i<len; i++) {
uint s = _scores[i];
uint b = _blocks[i];
uint weight = (b*100)/last;
weightedScore += s * weight;
weightSum += weight;
}
if (weightSum == 0 || weightedScore == 0)
return 0;
return weightedScore / weightSum;
}
}
/// @title WeightedAverageFunction
/// @notice Compute the final score with a weighted average using the skill values
contract WeightedAverageSkillFunction is RatingFunction {
/// @notice Compute the final score given a bundle of rating information
/// @param _scores The array of scores
/// @param _blocks The array of blocks containing the scores
/// @param _valuesSkill The array of values about skill of item rated
function compute(uint[] calldata _scores,
uint[] calldata _blocks,
uint[] calldata _valuesSkill
) haveEqualLength(_scores, _valuesSkill) external pure returns(uint) {
uint len = _scores.length;
if (len <= 0)
return 0;
// Weighted average based on skill values
uint totalWeight = 0;
uint totalValues = 0;
for (uint i=0; i<len; i++){
totalValues += _valuesSkill[i];
totalWeight += _scores[i]*_valuesSkill[i];
}
if (totalValues == 0 || totalWeight == 0)
return 0;
return totalWeight / totalValues;
}
}
/// @title BlocksAndSkillsWeightFunction
/// @notice Compute the final score with a weighted average using the blocks and skill values
/// @dev Array as parameter is needed to avoid StackTooDeep exception due to many local variables
contract BlocksAndSkillsWeightFunction is RatingFunction {
/// @notice Compute the final score given a bundle of rating information
/// @param _scores The array of scores
/// @param _blocks The array of blocks containing the scores
/// @param _valuesSkill The array of values about skill of item rated
function compute(uint[] calldata _scores,
uint[] calldata _blocks,
uint[] calldata _valuesSkill
) haveEqualLength(_scores, _blocks)
haveEqualLength(_scores, _valuesSkill) external pure returns(uint result) {
uint[5] memory data;
data[0] = 0; // i : iterator
data[1] = _scores.length; // len : number of scores
data[2] = _blocks[ data[1] -1]; // last : last block value
for (data[0] = 0; data[0] < data[1]; data[0]++){
uint s = _scores[ data[0] ];
uint b = _blocks[ data[0] ];
uint v = _valuesSkill[ data[0] ];
uint weight = (b*v*100) / data[2];
data[3] += weight; // sum of weights
data[4] += weight * s; // Weighted sum of scores
}
if (data[3] == 0 || data[4] == 0)
return 0;
result = data[4] / data[3]; // Weighted sum / sum of weights
}
}
|
len : number of scores
|
data[1] = _scores.length;
| 5,469,797 |
[
1,
1897,
565,
294,
1300,
434,
8474,
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,
3639,
501,
63,
21,
65,
273,
389,
12630,
18,
2469,
31,
1850,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import '../interfaces/IForceMoveApp.sol';
import {ExitFormat as Outcome} from '@statechannels/exit-format/contracts/ExitFormat.sol';
/**
* @dev The HashLockedSwap contract complies with the ForceMoveApp interface and implements a HashLockedSwaped payment
*/
contract HashLockedSwap is IForceMoveApp {
struct AppData {
bytes32 h;
bytes preImage;
}
function validTransition(
VariablePart memory a,
VariablePart memory b,
uint48 turnNumB,
uint256
) public override pure returns (bool) {
// is this the first and only swap?
require(turnNumB == 4, 'turnNumB != 4');
// Decode variables.
// Assumptions:
// - single asset in this channel
// - two parties in this channel
// - not a "guarantee" channel (c.f. Nitro paper)
Outcome.Allocation[] memory allocationsA = decode2PartyAllocation(a.outcome);
Outcome.Allocation[] memory allocationsB = decode2PartyAllocation(b.outcome);
bytes memory preImage = abi.decode(b.appData, (AppData)).preImage;
bytes32 h = abi.decode(a.appData, (AppData)).h;
// is the preimage correct?
require(sha256(preImage) == h, 'Incorrect preimage');
// NOTE ON GAS COSTS
// The gas cost of hashing depends on the choice of hash function
// and the length of the the preImage.
// sha256 is twice as expensive as keccak256
// https://ethereum.stackexchange.com/a/3200
// But is compatible with bitcoin.
// slots for each participant unchanged
require(
allocationsA[0].destination == allocationsB[0].destination &&
allocationsA[1].destination == allocationsB[1].destination,
'destinations may not change'
);
// was the payment made?
require(
allocationsA[0].amount == allocationsB[1].amount &&
allocationsA[1].amount == allocationsB[0].amount,
'amounts must be permuted'
);
return true;
}
function decode2PartyAllocation(bytes memory outcomeBytes)
private
pure
returns (Outcome.Allocation[] memory allocations)
{
Outcome.SingleAssetExit[] memory outcome = abi.decode(
outcomeBytes,
(Outcome.SingleAssetExit[])
);
Outcome.SingleAssetExit memory assetOutcome = outcome[0];
allocations = assetOutcome.allocations; // TODO should we check each allocation is a "simple" one?
// Throws unless there are exactly 3 allocations
require(allocations.length == 2, 'allocation.length != 3');
}
}
|
* @dev The HashLockedSwap contract complies with the ForceMoveApp interface and implements a HashLockedSwaped payment/
|
contract HashLockedSwap is IForceMoveApp {
pragma solidity 0.7.4;
import {ExitFormat as Outcome} from '@statechannels/exit-format/contracts/ExitFormat.sol';
struct AppData {
bytes32 h;
bytes preImage;
}
function validTransition(
VariablePart memory a,
VariablePart memory b,
uint48 turnNumB,
uint256
) public override pure returns (bool) {
require(turnNumB == 4, 'turnNumB != 4');
Outcome.Allocation[] memory allocationsA = decode2PartyAllocation(a.outcome);
Outcome.Allocation[] memory allocationsB = decode2PartyAllocation(b.outcome);
bytes memory preImage = abi.decode(b.appData, (AppData)).preImage;
bytes32 h = abi.decode(a.appData, (AppData)).h;
require(sha256(preImage) == h, 'Incorrect preimage');
require(
allocationsA[0].destination == allocationsB[0].destination &&
allocationsA[1].destination == allocationsB[1].destination,
'destinations may not change'
);
require(
allocationsA[0].amount == allocationsB[1].amount &&
allocationsA[1].amount == allocationsB[0].amount,
'amounts must be permuted'
);
return true;
}
function decode2PartyAllocation(bytes memory outcomeBytes)
private
pure
returns (Outcome.Allocation[] memory allocations)
{
Outcome.SingleAssetExit[] memory outcome = abi.decode(
outcomeBytes,
(Outcome.SingleAssetExit[])
);
Outcome.SingleAssetExit memory assetOutcome = outcome[0];
require(allocations.length == 2, 'allocation.length != 3');
}
}
| 7,211,962 |
[
1,
1986,
2474,
8966,
12521,
6835,
532,
5259,
598,
326,
11889,
7607,
3371,
1560,
471,
4792,
279,
2474,
8966,
6050,
5994,
5184,
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,
16351,
2474,
8966,
12521,
353,
467,
10997,
7607,
3371,
288,
203,
683,
9454,
18035,
560,
374,
18,
27,
18,
24,
31,
203,
5666,
288,
6767,
1630,
487,
2976,
5624,
97,
628,
4622,
2019,
9114,
19,
8593,
17,
2139,
19,
16351,
87,
19,
6767,
1630,
18,
18281,
13506,
203,
565,
1958,
4677,
751,
288,
203,
3639,
1731,
1578,
366,
31,
203,
3639,
1731,
675,
2040,
31,
203,
565,
289,
203,
203,
565,
445,
923,
8850,
12,
203,
3639,
7110,
1988,
3778,
279,
16,
203,
3639,
7110,
1988,
3778,
324,
16,
203,
3639,
2254,
8875,
7005,
2578,
38,
16,
203,
3639,
2254,
5034,
203,
565,
262,
1071,
3849,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
20922,
2578,
38,
422,
1059,
16,
296,
20922,
2578,
38,
480,
1059,
8284,
203,
203,
3639,
2976,
5624,
18,
17353,
8526,
3778,
23804,
37,
273,
2495,
22,
17619,
17353,
12,
69,
18,
21672,
1769,
203,
3639,
2976,
5624,
18,
17353,
8526,
3778,
23804,
38,
273,
2495,
22,
17619,
17353,
12,
70,
18,
21672,
1769,
203,
3639,
1731,
3778,
675,
2040,
273,
24126,
18,
3922,
12,
70,
18,
2910,
751,
16,
261,
3371,
751,
13,
2934,
1484,
2040,
31,
203,
3639,
1731,
1578,
366,
273,
24126,
18,
3922,
12,
69,
18,
2910,
751,
16,
261,
3371,
751,
13,
2934,
76,
31,
203,
203,
3639,
2583,
12,
7819,
5034,
12,
1484,
2040,
13,
422,
366,
16,
296,
16268,
675,
2730,
8284,
203,
203,
3639,
2583,
12,
203,
5411,
23804,
37,
63,
20,
8009,
10590,
422,
23804,
38,
63,
20,
8009,
2
] |
// SPDX-License-Identifier: MIT
// @unsupported: ovm
pragma solidity 0.8.9;
pragma experimental ABIEncoderV2;
import "../polygon/tunnel/FxBaseRootTunnel.sol";
import "./MessengerWrapper.sol";
/**
* @dev A MessengerWrapper for Polygon - https://docs.matic.network/docs
* @notice Deployed on layer-1
*/
contract PolygonMessengerWrapper is FxBaseRootTunnel, MessengerWrapper {
constructor(
address _l1BridgeAddress,
address _checkpointManager,
address _fxRoot,
address _fxChildTunnel
)
public
MessengerWrapper(_l1BridgeAddress)
FxBaseRootTunnel(_checkpointManager, _fxRoot)
{
setFxChildTunnel(_fxChildTunnel);
}
/**
* @dev Sends a message to the l2MessengerProxy from layer-1
* @param _calldata The data that l2MessengerProxy will be called with
* @notice The msg.sender is sent to the L2_PolygonMessengerProxy and checked there.
*/
function sendCrossDomainMessage(bytes memory _calldata) public override {
_sendMessageToChild(
abi.encode(msg.sender, _calldata)
);
}
function verifySender(address l1BridgeCaller, bytes memory /*_data*/) public view override {
require(l1BridgeCaller == address(this), "L1_PLGN_WPR: Caller must be this contract");
}
function _processMessageFromChild(bytes memory message) internal override {
(bool success,) = l1BridgeAddress.call(message);
require(success, "L1_PLGN_WPR: Call to L1 Bridge failed");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {RLPReader} from "../lib/RLPReader.sol";
import {MerklePatriciaProof} from "../lib/MerklePatriciaProof.sol";
import {Merkle} from "../lib/Merkle.sol";
import "../lib/ExitPayloadReader.sol";
interface IFxStateSender {
function sendMessageToChild(address _receiver, bytes calldata _data) external;
}
contract ICheckpointManager {
struct HeaderBlock {
bytes32 root;
uint256 start;
uint256 end;
uint256 createdAt;
address proposer;
}
/**
* @notice mapping of checkpoint header numbers to block details
* @dev These checkpoints are submited by plasma contracts
*/
mapping(uint256 => HeaderBlock) public headerBlocks;
}
abstract contract FxBaseRootTunnel {
using RLPReader for RLPReader.RLPItem;
using Merkle for bytes32;
using ExitPayloadReader for bytes;
using ExitPayloadReader for ExitPayloadReader.ExitPayload;
using ExitPayloadReader for ExitPayloadReader.Log;
using ExitPayloadReader for ExitPayloadReader.LogTopics;
using ExitPayloadReader for ExitPayloadReader.Receipt;
// keccak256(MessageSent(bytes))
bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036;
// state sender contract
IFxStateSender public fxRoot;
// root chain manager
ICheckpointManager public checkpointManager;
// child tunnel contract which receives and sends messages
address public fxChildTunnel;
// storage to avoid duplicate exits
mapping(bytes32 => bool) public processedExits;
constructor(address _checkpointManager, address _fxRoot) {
checkpointManager = ICheckpointManager(_checkpointManager);
fxRoot = IFxStateSender(_fxRoot);
}
// set fxChildTunnel if not set already
function setFxChildTunnel(address _fxChildTunnel) public {
require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET");
fxChildTunnel = _fxChildTunnel;
}
/**
* @notice Send bytes message to Child Tunnel
* @param message bytes message that will be sent to Child Tunnel
* some message examples -
* abi.encode(tokenId);
* abi.encode(tokenId, tokenMetadata);
* abi.encode(messageType, messageData);
*/
function _sendMessageToChild(bytes memory message) internal {
fxRoot.sendMessageToChild(fxChildTunnel, message);
}
function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) {
ExitPayloadReader.ExitPayload memory payload = inputData.toExitPayload();
bytes memory branchMaskBytes = payload.getBranchMaskAsBytes();
uint256 blockNumber = payload.getBlockNumber();
// checking if exit has already been processed
// unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex)
bytes32 exitHash = keccak256(
abi.encodePacked(
blockNumber,
// first 2 nibbles are dropped while generating nibble array
// this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only)
// so converting to nibble array and then hashing it
MerklePatriciaProof._getNibbleArray(branchMaskBytes),
payload.getReceiptLogIndex()
)
);
require(processedExits[exitHash] == false, "FxRootTunnel: EXIT_ALREADY_PROCESSED");
processedExits[exitHash] = true;
ExitPayloadReader.Receipt memory receipt = payload.getReceipt();
ExitPayloadReader.Log memory log = receipt.getLog();
// check child tunnel
require(fxChildTunnel == log.getEmitter(), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL");
bytes32 receiptRoot = payload.getReceiptRoot();
// verify receipt inclusion
require(
MerklePatriciaProof.verify(receipt.toBytes(), branchMaskBytes, payload.getReceiptProof(), receiptRoot),
"FxRootTunnel: INVALID_RECEIPT_PROOF"
);
// verify checkpoint inclusion
_checkBlockMembershipInCheckpoint(
blockNumber,
payload.getBlockTime(),
payload.getTxRoot(),
receiptRoot,
payload.getHeaderNumber(),
payload.getBlockProof()
);
ExitPayloadReader.LogTopics memory topics = log.getTopics();
require(
bytes32(topics.getField(0).toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig
"FxRootTunnel: INVALID_SIGNATURE"
);
// received message data
bytes memory message = abi.decode(log.getData(), (bytes)); // event decodes params again, so decoding bytes to get message
return message;
}
function _checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
) private view returns (uint256) {
(bytes32 headerRoot, uint256 startBlock, , uint256 createdAt, ) = checkpointManager.headerBlocks(headerNumber);
require(
keccak256(abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)).checkMembership(
blockNumber - startBlock,
headerRoot,
blockProof
),
"FxRootTunnel: INVALID_HEADER"
);
return createdAt;
}
/**
* @notice receive message from L2 to L1, validated by proof
* @dev This function verifies if the transaction actually happened on child chain
*
* @param inputData RLP encoded data of the reference tx containing following list of fields
* 0 - headerNumber - Checkpoint header block number containing the reference tx
* 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* 2 - blockNumber - Block number containing the reference tx on child chain
* 3 - blockTime - Reference tx block time
* 4 - txRoot - Transactions root of block
* 5 - receiptRoot - Receipts root of block
* 6 - receipt - Receipt of the reference transaction
* 7 - receiptProof - Merkle proof of the reference receipt
* 8 - branchMask - 32 bits denoting the path of receipt in merkle tree
* 9 - receiptLogIndex - Log Index to read from the receipt
*/
function receiveMessage(bytes memory inputData) public virtual {
bytes memory message = _validateAndExtractMessage(inputData);
_processMessageFromChild(message);
}
/**
* @notice Process message received from Child Tunnel
* @dev function needs to be implemented to handle message as per requirement
* This is called by onStateReceive function.
* Since it is called via a system call, any event will not be emitted during its execution.
* @param message bytes message that was sent from Child Tunnel
*/
function _processMessageFromChild(bytes memory message) internal virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
pragma experimental ABIEncoderV2;
import "../interfaces/IMessengerWrapper.sol";
abstract contract MessengerWrapper is IMessengerWrapper {
address public immutable l1BridgeAddress;
constructor(address _l1BridgeAddress) internal {
l1BridgeAddress = _l1BridgeAddress;
}
modifier onlyL1Bridge {
require(msg.sender == l1BridgeAddress, "MW: Sender must be the L1 Bridge");
_;
}
}
/*
* @author Hamdi Allam [email protected]
* Please reach out with any questions or concerns
*/
pragma solidity ^0.8.0;
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint256 len;
uint256 memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint256 nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint256 ptr = self.nextPtr;
uint256 itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint256 memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint256 ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/
function rlpLen(RLPItem memory item) internal pure returns (uint256) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/
function payloadLen(RLPItem memory item) internal pure returns (uint256) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint256 items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint256 memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 dataLen;
for (uint256 i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if (item.len == 0) return false;
uint8 byte0;
uint256 memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START) return false;
return true;
}
/*
* @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.
* @return keccak256 hash of RLP encoded bytes.
*/
function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) {
uint256 ptr = item.memPtr;
uint256 len = item.len;
bytes32 result;
assembly {
result := keccak256(ptr, len)
}
return result;
}
function payloadLocation(RLPItem memory item) internal pure returns (uint256, uint256) {
uint256 offset = _payloadOffset(item.memPtr);
uint256 memPtr = item.memPtr + offset;
uint256 len = item.len - offset; // data length
return (memPtr, len);
}
/*
* @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory.
* @return keccak256 hash of the item payload.
*/
function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) {
(uint256 memPtr, uint256 len) = payloadLocation(item);
bytes32 result;
assembly {
result := keccak256(memPtr, len)
}
return result;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint256 ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint256 result;
uint256 memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(uint160(toUint(item)));
}
function toUint(RLPItem memory item) internal pure returns (uint256) {
require(item.len > 0 && item.len <= 33);
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset;
uint256 result;
uint256 memPtr = item.memPtr + offset;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint256) {
// one byte prefix
require(item.len == 33);
uint256 result;
uint256 memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
uint256 offset = _payloadOffset(item.memPtr);
uint256 len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint256 destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint256) {
if (item.len == 0) return 0;
uint256 count = 0;
uint256 currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint256 endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint256 memPtr) private pure returns (uint256) {
uint256 itemLen;
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) itemLen = 1;
else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
} else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
} else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint256 memPtr) private pure returns (uint256) {
uint256 byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START) return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1;
else if (byte0 < LIST_SHORT_START)
// being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(
uint256 src,
uint256 dest,
uint256 len
) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
if (len == 0) return;
// left over bytes. Mask is used to remove unwanted bytes from the word
uint256 mask = 256**(WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {RLPReader} from "./RLPReader.sol";
library MerklePatriciaProof {
/*
* @dev Verifies a merkle patricia proof.
* @param value The terminating value in the trie.
* @param encodedPath The path in the trie leading to value.
* @param rlpParentNodes The rlp encoded stack of nodes.
* @param root The root hash of the trie.
* @return The boolean validity of the proof.
*/
function verify(
bytes memory value,
bytes memory encodedPath,
bytes memory rlpParentNodes,
bytes32 root
) internal pure returns (bool) {
RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes);
RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item);
bytes memory currentNode;
RLPReader.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint256 pathPtr = 0;
bytes memory path = _getNibbleArray(encodedPath);
if (path.length == 0) {
return false;
}
for (uint256 i = 0; i < parentNodes.length; i++) {
if (pathPtr > path.length) {
return false;
}
currentNode = RLPReader.toRlpBytes(parentNodes[i]);
if (nodeKey != keccak256(currentNode)) {
return false;
}
currentNodeList = RLPReader.toList(parentNodes[i]);
if (currentNodeList.length == 17) {
if (pathPtr == path.length) {
if (keccak256(RLPReader.toBytes(currentNodeList[16])) == keccak256(value)) {
return true;
} else {
return false;
}
}
uint8 nextPathNibble = uint8(path[pathPtr]);
if (nextPathNibble > 16) {
return false;
}
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[nextPathNibble]));
pathPtr += 1;
} else if (currentNodeList.length == 2) {
uint256 traversed = _nibblesToTraverse(RLPReader.toBytes(currentNodeList[0]), path, pathPtr);
if (pathPtr + traversed == path.length) {
//leaf node
if (keccak256(RLPReader.toBytes(currentNodeList[1])) == keccak256(value)) {
return true;
} else {
return false;
}
}
//extension node
if (traversed == 0) {
return false;
}
pathPtr += traversed;
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1]));
} else {
return false;
}
}
}
function _nibblesToTraverse(
bytes memory encodedPartialPath,
bytes memory path,
uint256 pathPtr
) private pure returns (uint256) {
uint256 len = 0;
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath
// and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath);
bytes memory slicedPath = new bytes(partialPath.length);
// pathPtr counts nibbles in path
// partialPath.length is a number of nibbles
for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) {
bytes1 pathNibble = path[i];
slicedPath[i - pathPtr] = pathNibble;
}
if (keccak256(partialPath) == keccak256(slicedPath)) {
len = partialPath.length;
} else {
len = 0;
}
return len;
}
// bytes b must be hp encoded
function _getNibbleArray(bytes memory b) internal pure returns (bytes memory) {
bytes memory nibbles = "";
if (b.length > 0) {
uint8 offset;
uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));
if (hpNibble == 1 || hpNibble == 3) {
nibbles = new bytes(b.length * 2 - 1);
bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
nibbles[0] = oddNibble;
offset = 1;
} else {
nibbles = new bytes(b.length * 2 - 2);
offset = 0;
}
for (uint256 i = offset; i < nibbles.length; i++) {
nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);
}
}
return nibbles;
}
function _getNthNibbleOfBytes(uint256 n, bytes memory str) private pure returns (bytes1) {
return bytes1(n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Merkle {
function checkMembership(
bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytes memory proof
) internal pure returns (bool) {
require(proof.length % 32 == 0, "Invalid proof length");
uint256 proofHeight = proof.length / 32;
// Proof of size n means, height of the tree is n+1.
// In a tree of height n+1, max #leafs possible is 2 ^ n
require(index < 2**proofHeight, "Leaf index is too big");
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
proofElement := mload(add(proof, i))
}
if (index % 2 == 0) {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
index = index / 2;
}
return computedHash == rootHash;
}
}
pragma solidity ^0.8.0;
import {RLPReader} from "./RLPReader.sol";
library ExitPayloadReader {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
uint8 constant WORD_SIZE = 32;
struct ExitPayload {
RLPReader.RLPItem[] data;
}
struct Receipt {
RLPReader.RLPItem[] data;
bytes raw;
uint256 logIndex;
}
struct Log {
RLPReader.RLPItem data;
RLPReader.RLPItem[] list;
}
struct LogTopics {
RLPReader.RLPItem[] data;
}
// copy paste of private copy() from RLPReader to avoid changing of existing contracts
function copy(
uint256 src,
uint256 dest,
uint256 len
) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint256 mask = 256**(WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
function toExitPayload(bytes memory data) internal pure returns (ExitPayload memory) {
RLPReader.RLPItem[] memory payloadData = data.toRlpItem().toList();
return ExitPayload(payloadData);
}
function getHeaderNumber(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[0].toUint();
}
function getBlockProof(ExitPayload memory payload) internal pure returns (bytes memory) {
return payload.data[1].toBytes();
}
function getBlockNumber(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[2].toUint();
}
function getBlockTime(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[3].toUint();
}
function getTxRoot(ExitPayload memory payload) internal pure returns (bytes32) {
return bytes32(payload.data[4].toUint());
}
function getReceiptRoot(ExitPayload memory payload) internal pure returns (bytes32) {
return bytes32(payload.data[5].toUint());
}
function getReceipt(ExitPayload memory payload) internal pure returns (Receipt memory receipt) {
receipt.raw = payload.data[6].toBytes();
RLPReader.RLPItem memory receiptItem = receipt.raw.toRlpItem();
if (receiptItem.isList()) {
// legacy tx
receipt.data = receiptItem.toList();
} else {
// pop first byte before parsting receipt
bytes memory typedBytes = receipt.raw;
bytes memory result = new bytes(typedBytes.length - 1);
uint256 srcPtr;
uint256 destPtr;
assembly {
srcPtr := add(33, typedBytes)
destPtr := add(0x20, result)
}
copy(srcPtr, destPtr, result.length);
receipt.data = result.toRlpItem().toList();
}
receipt.logIndex = getReceiptLogIndex(payload);
return receipt;
}
function getReceiptProof(ExitPayload memory payload) internal pure returns (bytes memory) {
return payload.data[7].toBytes();
}
function getBranchMaskAsBytes(ExitPayload memory payload) internal pure returns (bytes memory) {
return payload.data[8].toBytes();
}
function getBranchMaskAsUint(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[8].toUint();
}
function getReceiptLogIndex(ExitPayload memory payload) internal pure returns (uint256) {
return payload.data[9].toUint();
}
// Receipt methods
function toBytes(Receipt memory receipt) internal pure returns (bytes memory) {
return receipt.raw;
}
function getLog(Receipt memory receipt) internal pure returns (Log memory) {
RLPReader.RLPItem memory logData = receipt.data[3].toList()[receipt.logIndex];
return Log(logData, logData.toList());
}
// Log methods
function getEmitter(Log memory log) internal pure returns (address) {
return RLPReader.toAddress(log.list[0]);
}
function getTopics(Log memory log) internal pure returns (LogTopics memory) {
return LogTopics(log.list[1].toList());
}
function getData(Log memory log) internal pure returns (bytes memory) {
return log.list[2].toBytes();
}
function toRlpBytes(Log memory log) internal pure returns (bytes memory) {
return log.data.toRlpBytes();
}
// LogTopics methods
function getField(LogTopics memory topics, uint256 index) internal pure returns (RLPReader.RLPItem memory) {
return topics.data[index];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <=0.8.9;
pragma experimental ABIEncoderV2;
interface IMessengerWrapper {
function sendCrossDomainMessage(bytes memory _calldata) external;
function verifySender(address l1BridgeCaller, bytes memory _data) external;
}
|
@returns raw rlp encoding in bytes
|
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint256 ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
| 159,472 |
[
1,
6154,
1831,
30717,
2688,
316,
1731,
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,
358,
54,
9953,
2160,
12,
54,
48,
1102,
874,
3778,
761,
13,
2713,
16618,
1135,
261,
3890,
3778,
13,
288,
203,
3639,
1731,
3778,
563,
273,
394,
1731,
12,
1726,
18,
1897,
1769,
203,
3639,
309,
261,
2088,
18,
2469,
422,
374,
13,
327,
563,
31,
203,
203,
3639,
2254,
5034,
6571,
31,
203,
3639,
19931,
288,
203,
5411,
6571,
519,
527,
12,
20,
92,
3462,
16,
563,
13,
203,
3639,
289,
203,
203,
3639,
1610,
12,
1726,
18,
3917,
5263,
16,
6571,
16,
761,
18,
1897,
1769,
203,
3639,
327,
563,
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
] |
./full_match/80001/0xa61609AEC3E86de4b35d3B4dB5e2893789E53856/sources/contracts/Web3_payment/BSC/MerchantFactory_fixed_bsc_test.sol
|
Function just confirming
|
IBEP20(_receiveToken).balanceOf(address(this));
| 9,449,513 |
[
1,
2083,
2537,
6932,
310,
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,
3639,
467,
5948,
52,
3462,
24899,
18149,
1345,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
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
] |
// SPDX-License-Identifier: AGPL-3.0-only
/*
Bounty.sol - SKALE Manager
Copyright (C) 2020-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./delegation/DelegationController.sol";
import "./delegation/PartialDifferences.sol";
import "./delegation/TimeHelpers.sol";
import "./delegation/ValidatorService.sol";
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./Permissions.sol";
contract BountyV2 is Permissions {
using PartialDifferences for PartialDifferences.Value;
using PartialDifferences for PartialDifferences.Sequence;
struct BountyHistory {
uint month;
uint bountyPaid;
}
uint public constant YEAR1_BOUNTY = 3850e5 * 1e18;
uint public constant YEAR2_BOUNTY = 3465e5 * 1e18;
uint public constant YEAR3_BOUNTY = 3080e5 * 1e18;
uint public constant YEAR4_BOUNTY = 2695e5 * 1e18;
uint public constant YEAR5_BOUNTY = 2310e5 * 1e18;
uint public constant YEAR6_BOUNTY = 1925e5 * 1e18;
uint public constant EPOCHS_PER_YEAR = 12;
uint public constant SECONDS_PER_DAY = 24 * 60 * 60;
uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY;
uint private _nextEpoch;
uint private _epochPool;
uint private _bountyWasPaidInCurrentEpoch;
bool public bountyReduction;
uint public nodeCreationWindowSeconds;
PartialDifferences.Value private _effectiveDelegatedSum;
// validatorId amount of nodes
mapping (uint => uint) public nodesByValidator; // deprecated
// validatorId => BountyHistory
mapping (uint => BountyHistory) private _bountyHistory;
function calculateBounty(uint nodeIndex)
external
allow("SkaleManager")
returns (uint)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
require(
_getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now,
"Transaction is sent too early"
);
uint validatorId = nodes.getValidatorId(nodeIndex);
if (nodesByValidator[validatorId] > 0) {
delete nodesByValidator[validatorId];
}
uint currentMonth = timeHelpers.getCurrentMonth();
_refillEpochPool(currentMonth, timeHelpers, constantsHolder);
_prepareBountyHistory(validatorId, currentMonth);
uint bounty = _calculateMaximumBountyAmount(
_epochPool,
_effectiveDelegatedSum.getAndUpdateValue(currentMonth),
_bountyWasPaidInCurrentEpoch,
nodeIndex,
_bountyHistory[validatorId].bountyPaid,
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getAndUpdateDelegatedToValidatorNow(validatorId),
constantsHolder,
nodes
);
_bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty);
bounty = _reduceBounty(
bounty,
nodeIndex,
nodes,
constantsHolder
);
_epochPool = _epochPool.sub(bounty);
_bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty);
return bounty;
}
function enableBountyReduction() external onlyOwner {
bountyReduction = true;
}
function disableBountyReduction() external onlyOwner {
bountyReduction = false;
}
function setNodeCreationWindowSeconds(uint window) external allow("Nodes") {
nodeCreationWindowSeconds = window;
}
function handleDelegationAdd(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.addToValue(amount, month);
}
function handleDelegationRemoving(
uint amount,
uint month
)
external
allow("DelegationController")
{
_effectiveDelegatedSum.subtractFromValue(amount, month);
}
function populate() external onlyOwner {
ValidatorService validatorService = ValidatorService(contractManager.getValidatorService());
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers());
uint currentMonth = timeHelpers.getCurrentMonth();
// clean existing data
for (
uint i = _effectiveDelegatedSum.firstUnprocessedMonth;
i < _effectiveDelegatedSum.lastChangedMonth.add(1);
++i
)
{
delete _effectiveDelegatedSum.addDiff[i];
delete _effectiveDelegatedSum.subtractDiff[i];
}
delete _effectiveDelegatedSum.value;
delete _effectiveDelegatedSum.lastChangedMonth;
_effectiveDelegatedSum.firstUnprocessedMonth = currentMonth;
uint[] memory validators = validatorService.getTrustedValidators();
for (uint i = 0; i < validators.length; ++i) {
uint validatorId = validators[i];
uint currentEffectiveDelegated =
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth);
uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId);
if (effectiveDelegated.length > 0) {
assert(currentEffectiveDelegated == effectiveDelegated[0]);
}
uint added = 0;
for (uint j = 0; j < effectiveDelegated.length; ++j) {
if (effectiveDelegated[j] != added) {
if (effectiveDelegated[j] > added) {
_effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j);
} else {
_effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j);
}
added = effectiveDelegated[j];
}
}
delete effectiveDelegated;
}
}
function estimateBounty(uint nodeIndex) external view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint currentMonth = timeHelpers.getCurrentMonth();
uint validatorId = nodes.getValidatorId(nodeIndex);
uint stagePoolSize;
(stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
return _calculateMaximumBountyAmount(
stagePoolSize,
_effectiveDelegatedSum.getValue(currentMonth),
_nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0,
nodeIndex,
_getBountyPaid(validatorId, currentMonth),
delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth),
delegationController.getDelegatedToValidator(validatorId, currentMonth),
constantsHolder,
nodes
);
}
function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) {
return _getNextRewardTimestamp(
nodeIndex,
Nodes(contractManager.getContract("Nodes")),
TimeHelpers(contractManager.getContract("TimeHelpers"))
);
}
function getEffectiveDelegatedSum() external view returns (uint[] memory) {
return _effectiveDelegatedSum.getValues();
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
_nextEpoch = 0;
_epochPool = 0;
_bountyWasPaidInCurrentEpoch = 0;
bountyReduction = false;
nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY;
}
// private
function _calculateMaximumBountyAmount(
uint epochPoolSize,
uint effectiveDelegatedSum,
uint bountyWasPaidInCurrentEpoch,
uint nodeIndex,
uint bountyPaidToTheValidator,
uint effectiveDelegated,
uint delegated,
ConstantsHolder constantsHolder,
Nodes nodes
)
private
view
returns (uint)
{
if (nodes.isNodeLeft(nodeIndex)) {
return 0;
}
if (now < constantsHolder.launchTimestamp()) {
// network is not launched
// bounty is turned off
return 0;
}
if (effectiveDelegatedSum == 0) {
// no delegations in the system
return 0;
}
if (constantsHolder.msr() == 0) {
return 0;
}
uint bounty = _calculateBountyShare(
epochPoolSize.add(bountyWasPaidInCurrentEpoch),
effectiveDelegated,
effectiveDelegatedSum,
delegated.div(constantsHolder.msr()),
bountyPaidToTheValidator
);
return bounty;
}
function _calculateBountyShare(
uint monthBounty,
uint effectiveDelegated,
uint effectiveDelegatedSum,
uint maxNodesAmount,
uint paidToValidator
)
private
pure
returns (uint)
{
if (maxNodesAmount > 0) {
uint totalBountyShare = monthBounty
.mul(effectiveDelegated)
.div(effectiveDelegatedSum);
return _min(
totalBountyShare.div(maxNodesAmount),
totalBountyShare.sub(paidToValidator)
);
} else {
return 0;
}
}
function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) {
return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp());
}
function _getEpochPool(
uint currentMonth,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint epochPool, uint nextEpoch)
{
epochPool = _epochPool;
for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) {
epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder));
}
}
function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private {
uint epochPool;
uint nextEpoch;
(epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder);
if (_nextEpoch < nextEpoch) {
(_epochPool, _nextEpoch) = (epochPool, nextEpoch);
_bountyWasPaidInCurrentEpoch = 0;
}
}
function _getEpochReward(
uint epoch,
TimeHelpers timeHelpers,
ConstantsHolder constantsHolder
)
private
view
returns (uint)
{
uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder);
if (epoch < firstEpoch) {
return 0;
}
uint epochIndex = epoch.sub(firstEpoch);
uint year = epochIndex.div(EPOCHS_PER_YEAR);
if (year >= 6) {
uint power = year.sub(6).div(3).add(1);
if (power < 256) {
return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR);
} else {
return 0;
}
} else {
uint[6] memory customBounties = [
YEAR1_BOUNTY,
YEAR2_BOUNTY,
YEAR3_BOUNTY,
YEAR4_BOUNTY,
YEAR5_BOUNTY,
YEAR6_BOUNTY
];
return customBounties[year].div(EPOCHS_PER_YEAR);
}
}
function _reduceBounty(
uint bounty,
uint nodeIndex,
Nodes nodes,
ConstantsHolder constants
)
private
returns (uint reducedBounty)
{
if (!bountyReduction) {
return bounty;
}
reducedBounty = bounty;
if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) {
reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT());
}
}
function _prepareBountyHistory(uint validatorId, uint currentMonth) private {
if (_bountyHistory[validatorId].month < currentMonth) {
_bountyHistory[validatorId].month = currentMonth;
delete _bountyHistory[validatorId].bountyPaid;
}
}
function _getBountyPaid(uint validatorId, uint month) private view returns (uint) {
require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid");
if (_bountyHistory[validatorId].month == month) {
return _bountyHistory[validatorId].bountyPaid;
} else {
return 0;
}
}
function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) {
uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex);
uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp);
uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth);
uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart);
uint currentMonth = timeHelpers.getCurrentMonth();
assert(lastRewardMonth <= currentMonth);
if (lastRewardMonth == currentMonth) {
uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1));
uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2));
if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) {
return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS);
} else {
return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS));
}
} else if (lastRewardMonth.add(1) == currentMonth) {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1));
return _min(
currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)),
currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS)
);
} else {
uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth);
return currentMonthStart.add(nodeCreationWindowSeconds);
}
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
function _max(uint a, uint b) private pure returns (uint) {
if (a < b) {
return b;
} else {
return a;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ConstantsHolder.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimelimit;
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
rewardPeriod = newRewardPeriod;
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external onlyOwner {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external onlyOwner {
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external onlyOwner {
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external onlyOwner {
require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched");
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external onlyOwner {
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner {
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner {
require(percentage <= 100, "Percentage value is incorrect");
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external onlyOwner {
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external onlyOwner {
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external onlyOwner {
minimalSchainLifetime = lifetime;
}
function setComplaintTimelimit(uint timelimit) external onlyOwner {
complaintTimelimit = timelimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = uint(-1);
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimelimit = 1800;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ContractManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol";
import "./utils/StringUtils.sol";
/**
* @title ContractManager
* @dev Contract contains the actual current mapping from contract IDs
* (in the form of human-readable strings) to addresses.
*/
contract ContractManager is OwnableUpgradeSafe {
using StringUtils for string;
using Address for address;
string public constant BOUNTY = "Bounty";
string public constant CONSTANTS_HOLDER = "ConstantsHolder";
string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager";
string public constant PUNISHER = "Punisher";
string public constant SKALE_TOKEN = "SkaleToken";
string public constant TIME_HELPERS = "TimeHelpers";
string public constant TOKEN_LAUNCH_LOCKER = "TokenLaunchLocker";
string public constant TOKEN_STATE = "TokenState";
string public constant VALIDATOR_SERVICE = "ValidatorService";
// mapping of actual smart contracts addresses
mapping (bytes32 => address) public contracts;
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external initializer {
OwnableUpgradeSafe.__Ownable_init();
}
/**
* @dev Allows the Owner to add contract to mapping of contract addresses.
*
* Emits a {ContractUpgraded} event.
*
* Requirements:
*
* - New address is non-zero.
* - Contract is not already added.
* - Contract address contains code.
*/
function setContractsAddress(string calldata contractsName, address newContractsAddress) external onlyOwner {
// check newContractsAddress is not equal to zero
require(newContractsAddress != address(0), "New address is equal zero");
// create hash of contractsName
bytes32 contractId = keccak256(abi.encodePacked(contractsName));
// check newContractsAddress is not equal the previous contract's address
require(contracts[contractId] != newContractsAddress, "Contract is already added");
require(newContractsAddress.isContract(), "Given contract address does not contain code");
// add newContractsAddress to mapping of actual contract addresses
contracts[contractId] = newContractsAddress;
emit ContractUpgraded(contractsName, newContractsAddress);
}
/**
* @dev Returns contract address.
*
* Requirements:
*
* - Contract must exist.
*/
function getDelegationPeriodManager() external view returns (address) {
return getContract(DELEGATION_PERIOD_MANAGER);
}
function getBounty() external view returns (address) {
return getContract(BOUNTY);
}
function getValidatorService() external view returns (address) {
return getContract(VALIDATOR_SERVICE);
}
function getTimeHelpers() external view returns (address) {
return getContract(TIME_HELPERS);
}
function getTokenLaunchLocker() external view returns (address) {
return getContract(TOKEN_LAUNCH_LOCKER);
}
function getConstantsHolder() external view returns (address) {
return getContract(CONSTANTS_HOLDER);
}
function getSkaleToken() external view returns (address) {
return getContract(SKALE_TOKEN);
}
function getTokenState() external view returns (address) {
return getContract(TOKEN_STATE);
}
function getPunisher() external view returns (address) {
return getContract(PUNISHER);
}
function getContract(string memory name) public view returns (address contractAddress) {
contractAddress = contracts[keccak256(abi.encodePacked(name))];
if (contractAddress == address(0)) {
revert(name.strConcat(" contract has not been found"));
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Decryption.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @title Decryption
* @dev This contract performs encryption and decryption functions.
* Decrypt is used by SkaleDKG contract to decrypt secret key contribution to
* validate complaints during the DKG procedure.
*/
contract Decryption {
/**
* @dev Returns an encrypted text given a secret and a key.
*/
function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) {
return bytes32(secretNumber) ^ key;
}
/**
* @dev Returns a secret given an encrypted text and a key.
*/
function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) {
return uint256(ciphertext ^ key);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
KeyStorage.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Decryption.sol";
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./thirdparty/ECDH.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
contract KeyStorage is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
using G2Operations for G2Operations.G2Point;
struct BroadcastedData {
KeyShare[] secretKeyContribution;
G2Operations.G2Point[] verificationVector;
}
struct KeyShare {
bytes32[2] publicKey;
bytes32 share;
}
// Unused variable!!
mapping(bytes32 => mapping(uint => BroadcastedData)) private _data;
//
mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress;
mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys;
// Unused variable
mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys;
//
mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys;
function deleteKey(bytes32 schainId) external allow("SkaleDKG") {
_previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]);
delete _schainsPublicKeys[schainId];
}
function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") {
_publicKeysInProgress[schainId] = G2Operations.getG2Zero();
}
function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") {
require(value.isG2(), "Incorrect g2 point");
_publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]);
}
function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") {
if (!_isSchainsPublicKeyZero(schainId)) {
_previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]);
}
_schainsPublicKeys[schainId] = _publicKeysInProgress[schainId];
delete _publicKeysInProgress[schainId];
}
function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) {
return _schainsPublicKeys[schainId];
}
function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) {
uint length = _previousSchainsPublicKeys[schainId].length;
if (length == 0) {
return G2Operations.getG2Zero();
}
return _previousSchainsPublicKeys[schainId][length - 1];
}
function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) {
return _previousSchainsPublicKeys[schainId];
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) {
return _schainsPublicKeys[schainId].x.a == 0 &&
_schainsPublicKeys[schainId].x.b == 0 &&
_schainsPublicKeys[schainId].y.a == 0 &&
_schainsPublicKeys[schainId].y.b == 0;
}
function _getData() private view returns (BroadcastedData memory) {
return _data[keccak256(abi.encodePacked("UnusedFunction"))][0];
}
function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) {
return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
NodeRotation.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol";
import "./Permissions.sol";
import "./ConstantsHolder.sol";
import "./SchainsInternal.sol";
import "./Schains.sol";
import "./Nodes.sol";
import "./interfaces/ISkaleDKG.sol";
/**
* @title NodeRotation
* @dev This contract handles all node rotation functionality.
*/
contract NodeRotation is Permissions {
using StringUtils for string;
using StringUtils for uint;
using Strings for uint;
/**
* nodeIndex - index of Node which is in process of rotation (left from schain)
* newNodeIndex - index of Node which is rotated(added to schain)
* freezeUntil - time till which Node should be turned on
* rotationCounter - how many rotations were on this schain
*/
struct Rotation {
uint nodeIndex;
uint newNodeIndex;
uint freezeUntil;
uint rotationCounter;
}
struct LeavingHistory {
bytes32 schainIndex;
uint finishedRotation;
}
mapping (bytes32 => Rotation) public rotations;
mapping (uint => LeavingHistory[]) public leavingHistory;
mapping (bytes32 => bool) public waitForNewNode;
/**
* @dev Allows SkaleManager to remove, find new node, and rotate node from
* schain.
*
* Requirements:
*
* - A free node must exist.
*/
function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex);
require(_checkRotation(schainId), "No free Nodes available for rotating");
rotateNode(nodeIndex, schainId, true);
return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false;
}
/**
* @dev Allows SkaleManager contract to freeze all schains on a given node.
*/
function freezeSchains(uint nodeIndex) external allow("SkaleManager") {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex);
for (uint i = 0; i < schains.length; i++) {
Rotation memory rotation = rotations[schains[i]];
if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) {
continue;
}
string memory schainName = schainsInternal.getSchainName(schains[i]);
string memory revertMessage = "Node cannot rotate on Schain ";
revertMessage = revertMessage.strConcat(schainName);
revertMessage = revertMessage.strConcat(", occupied by Node ");
revertMessage = revertMessage.strConcat(rotation.nodeIndex.toString());
string memory dkgRevert = "DKG process did not finish on schain ";
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(
skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))),
dkgRevert.strConcat(schainName));
require(rotation.freezeUntil < now, revertMessage);
_startRotation(schains[i], nodeIndex);
}
}
/**
* @dev Allows Schains contract to remove a rotation from an schain.
*/
function removeRotation(bytes32 schainIndex) external allow("Schains") {
delete rotations[schainIndex];
}
/**
* @dev Allows Owner to immediately rotate an schain.
*/
function skipRotationDelay(bytes32 schainIndex) external onlyOwner {
rotations[schainIndex].freezeUntil = now;
}
/**
* @dev Returns rotation details for a given schain.
*/
function getRotation(bytes32 schainIndex) external view returns (Rotation memory) {
return rotations[schainIndex];
}
/**
* @dev Returns leaving history for a given node.
*/
function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) {
return leavingHistory[nodeIndex];
}
function isRotationInProgress(bytes32 schainIndex) external view returns (bool) {
return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex];
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an
* schain.
*/
function rotateNode(
uint nodeIndex,
bytes32 schainId,
bool shouldDelay
)
public
allowTwo("SkaleDKG", "SkaleManager")
returns (uint newNode)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
Schains schains = Schains(contractManager.getContract("Schains"));
schainsInternal.removeNodeFromSchain(nodeIndex, schainId);
newNode = selectNodeToGroup(schainId);
uint8 space = schainsInternal.getSchainsPartOfNode(schainId);
schains.addSpace(nodeIndex, space);
_finishRotation(schainId, nodeIndex, newNode, shouldDelay);
}
/**
* @dev Allows SkaleManager, Schains, and SkaleDKG contracts to
* pseudo-randomly select a new Node for an Schain.
*
* Requirements:
*
* - Schain is active.
* - A free node already exists.
* - Free space can be allocated from the node.
*/
function selectNodeToGroup(bytes32 schainId)
public
allowThree("SkaleManager", "Schains", "SkaleDKG")
returns (uint)
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
require(schainsInternal.isSchainActive(schainId), "Group is not active");
uint8 space = schainsInternal.getSchainsPartOfNode(schainId);
uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId);
require(possibleNodes.length > 0, "No free Nodes available for rotation");
uint nodeIndex;
uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId)));
do {
uint index = random % possibleNodes.length;
nodeIndex = possibleNodes[index];
random = uint(keccak256(abi.encodePacked(random, nodeIndex)));
} while (schainsInternal.checkException(schainId, nodeIndex));
require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex");
schainsInternal.addSchainForNode(nodeIndex, schainId);
schainsInternal.setException(schainId, nodeIndex);
schainsInternal.setNodeInGroup(schainId, nodeIndex);
return nodeIndex;
}
/**
* @dev Initiates rotation of a node from an schain.
*/
function _startRotation(bytes32 schainIndex, uint nodeIndex) private {
ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
rotations[schainIndex].nodeIndex = nodeIndex;
rotations[schainIndex].newNodeIndex = nodeIndex;
rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay());
waitForNewNode[schainIndex] = true;
}
/**
* @dev Completes rotation of a node from an schain.
*/
function _finishRotation(
bytes32 schainIndex,
uint nodeIndex,
uint newNodeIndex,
bool shouldDelay)
private
{
ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
leavingHistory[nodeIndex].push(
LeavingHistory(schainIndex, shouldDelay ? now.add(constants.rotationDelay()) : now)
);
rotations[schainIndex].newNodeIndex = newNodeIndex;
rotations[schainIndex].rotationCounter++;
delete waitForNewNode[schainIndex];
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex);
}
/**
* @dev Checks whether a rotation can be performed.
*
* Requirements:
*
* - Schain must exist.
*/
function _checkRotation(bytes32 schainId ) private view returns (bool) {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation");
return schainsInternal.isAnyFreeNode(schainId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Nodes.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol";
import "./delegation/DelegationController.sol";
import "./delegation/ValidatorService.sol";
import "./BountyV2.sol";
import "./ConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title Nodes
* @dev This contract contains all logic to manage SKALE Network nodes states,
* space availability, stake requirement checks, and exit functions.
*
* Nodes may be in one of several states:
*
* - Active: Node is registered and is in network operation.
* - Leaving: Node has begun exiting from the network.
* - Left: Node has left the network.
* - In_Maintenance: Node is temporarily offline or undergoing infrastructure
* maintenance
*
* Note: Online nodes contain both Active and Leaving states.
*/
contract Nodes is Permissions {
using SafeCast for uint;
// All Nodes states
enum NodeStatus {Active, Leaving, Left, In_Maintenance}
struct Node {
string name;
bytes4 ip;
bytes4 publicIP;
uint16 port;
bytes32[2] publicKey;
uint startBlock;
uint lastRewardDate;
uint finishTime;
NodeStatus status;
uint validatorId;
string domainName;
}
// struct to note which Nodes and which number of Nodes owned by user
struct CreatedNodes {
mapping (uint => bool) isNodeExist;
uint numberOfNodes;
}
struct SpaceManaging {
uint8 freeSpace;
uint indexInSpaceMap;
}
// TODO: move outside the contract
struct NodeCreationParams {
string name;
bytes4 ip;
bytes4 publicIp;
uint16 port;
bytes32[2] publicKey;
uint16 nonce;
string domainName;
}
// array which contain all Nodes
Node[] public nodes;
SpaceManaging[] public spaceOfNodes;
// mapping for checking which Nodes and which number of Nodes owned by user
mapping (address => CreatedNodes) public nodeIndexes;
// mapping for checking is IP address busy
mapping (bytes4 => bool) public nodesIPCheck;
// mapping for checking is Name busy
mapping (bytes32 => bool) public nodesNameCheck;
// mapping for indication from Name to Index
mapping (bytes32 => uint) public nodesNameToIndex;
// mapping for indication from space to Nodes
mapping (uint8 => uint[]) public spaceToNodes;
mapping (uint => uint[]) public validatorToNodeIndexes;
uint public numberOfActiveNodes;
uint public numberOfLeavingNodes;
uint public numberOfLeftNodes;
/**
* @dev Emitted when a node is created.
*/
event NodeCreated(
uint nodeIndex,
address owner,
string name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
uint16 nonce,
string domainName,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node completes a network exit.
*/
event ExitCompleted(
uint nodeIndex,
uint time,
uint gasSpend
);
/**
* @dev Emitted when a node begins to exit from the network.
*/
event ExitInitialized(
uint nodeIndex,
uint startLeavingPeriod,
uint time,
uint gasSpend
);
modifier checkNodeExists(uint nodeIndex) {
require(nodeIndex < nodes.length, "Node with such index does not exist");
_;
}
modifier onlyNodeOrAdmin(uint nodeIndex) {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(
isNodeExist(msg.sender, nodeIndex) ||
_isAdmin(msg.sender) ||
getValidatorId(nodeIndex) == validatorService.getValidatorId(msg.sender),
"Sender is not permitted to call this function"
);
_;
}
/**
* @dev Allows Schains and SchainsInternal contracts to occupy available
* space on a node.
*
* Returns whether operation is successful.
*/
function removeSpaceFromNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allowTwo("NodeRotation", "SchainsInternal")
returns (bool)
{
if (spaceOfNodes[nodeIndex].freeSpace < space) {
return false;
}
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8()
);
}
return true;
}
/**
* @dev Allows Schains contract to occupy free space on a node.
*
* Returns whether operation is successful.
*/
function addSpaceToNode(uint nodeIndex, uint8 space)
external
checkNodeExists(nodeIndex)
allow("Schains")
{
if (space > 0) {
_moveNodeToNewSpaceMap(
nodeIndex,
uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8()
);
}
}
/**
* @dev Allows SkaleManager to change a node's last reward date.
*/
function changeNodeLastRewardDate(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].lastRewardDate = block.timestamp;
}
/**
* @dev Allows SkaleManager to change a node's finish time.
*/
function changeNodeFinishTime(uint nodeIndex, uint time)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
nodes[nodeIndex].finishTime = time;
}
/**
* @dev Allows SkaleManager contract to create new node and add it to the
* Nodes contract.
*
* Emits a {NodeCreated} event.
*
* Requirements:
*
* - Node IP must be non-zero.
* - Node IP must be available.
* - Node name must not already be registered.
* - Node port must be greater than zero.
*/
function createNode(address from, NodeCreationParams calldata params)
external
allow("SkaleManager")
// returns (uint nodeIndex)
{
// checks that Node has correct data
require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available");
require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered");
require(params.port > 0, "Port is zero");
require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect");
uint validatorId = ValidatorService(
contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from);
// adds Node to Nodes contract
uint nodeIndex = _addNode(
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.publicKey,
params.domainName,
validatorId);
emit NodeCreated(
nodeIndex,
from,
params.name,
params.ip,
params.publicIp,
params.port,
params.nonce,
params.domainName,
block.timestamp,
gasleft());
}
/**
* @dev Allows SkaleManager contract to initiate a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitInitialized} event.
*/
function initExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeActive(nodeIndex), "Node should be Active");
_setNodeLeaving(nodeIndex);
emit ExitInitialized(
nodeIndex,
block.timestamp,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to complete a node exit procedure.
*
* Returns whether the operation is successful.
*
* Emits an {ExitCompleted} event.
*
* Requirements:
*
* - Node must have already initialized a node exit procedure.
*/
function completeExit(uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
returns (bool)
{
require(isNodeLeaving(nodeIndex), "Node is not Leaving");
_setNodeLeft(nodeIndex);
_deleteNode(nodeIndex);
emit ExitCompleted(
nodeIndex,
block.timestamp,
gasleft());
return true;
}
/**
* @dev Allows SkaleManager contract to delete a validator's node.
*
* Requirements:
*
* - Validator ID must exist.
*/
function deleteNodeForValidator(uint validatorId, uint nodeIndex)
external
checkNodeExists(nodeIndex)
allow("SkaleManager")
{
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
if (position < validatorNodes.length) {
validatorToNodeIndexes[validatorId][position] =
validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)];
}
validatorToNodeIndexes[validatorId].pop();
address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey);
if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) {
if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) {
validatorService.removeNodeAddress(validatorId, nodeOwner);
}
nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false;
nodeIndexes[nodeOwner].numberOfNodes--;
}
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to create another node.
*
* Requirements:
*
* - Validator must be included on trusted list if trusted list is enabled.
* - Validator must have sufficient stake to operate an additional node.
*/
function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress);
require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr();
require(
validatorNodes.length.add(1).mul(msr) <= delegationsTotal,
"Validator must meet the Minimum Staking Requirement");
}
/**
* @dev Allows SkaleManager contract to check whether a validator has
* sufficient stake to maintain a node.
*
* Returns whether validator can maintain node with current stake.
*
* Requirements:
*
* - Validator ID and nodeIndex must both exist.
*/
function checkPossibilityToMaintainNode(
uint validatorId,
uint nodeIndex
)
external
checkNodeExists(nodeIndex)
allow("Bounty")
returns (bool)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
uint[] memory validatorNodes = validatorToNodeIndexes[validatorId];
uint position = _findNode(validatorNodes, nodeIndex);
require(position < validatorNodes.length, "Node does not exist for this Validator");
uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId);
uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr();
return position.add(1).mul(msr) <= delegationsTotal;
}
/**
* @dev Allows Node to set In_Maintenance status.
*
* Requirements:
*
* - Node must already be Active.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active");
_setNodeInMaintenance(nodeIndex);
}
/**
* @dev Allows Node to remove In_Maintenance status.
*
* Requirements:
*
* - Node must already be In Maintenance.
* - `msg.sender` must be owner of Node, validator, or SkaleManager.
*/
function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrAdmin(nodeIndex) {
require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance");
_setNodeActive(nodeIndex);
}
function setDomainName(uint nodeIndex, string memory domainName)
external
onlyNodeOrAdmin(nodeIndex)
{
nodes[nodeIndex].domainName = domainName;
}
/**
* @dev Returns nodes with space availability.
*/
function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace));
uint cursor = 0;
uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE();
for (uint8 i = freeSpace; i <= totalSpace; ++i) {
for (uint j = 0; j < spaceToNodes[i].length; j++) {
nodesWithFreeSpace[cursor] = spaceToNodes[i][j];
++cursor;
}
}
return nodesWithFreeSpace;
}
/**
* @dev Checks whether it is time for a node's reward.
*/
function isTimeForReward(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now;
}
/**
* @dev Returns IP address of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeIP(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes4)
{
require(nodeIndex < nodes.length, "Node does not exist");
return nodes[nodeIndex].ip;
}
/**
* @dev Returns domain name of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodeDomainName(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (string memory)
{
return nodes[nodeIndex].domainName;
}
/**
* @dev Returns the port of a given node.
*
* Requirements:
*
* - Node must exist.
*/
function getNodePort(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint16)
{
return nodes[nodeIndex].port;
}
/**
* @dev Returns the public key of a given node.
*/
function getNodePublicKey(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bytes32[2] memory)
{
return nodes[nodeIndex].publicKey;
}
/**
* @dev Returns an address of a given node.
*/
function getNodeAddress(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (address)
{
return _publicKeyToAddress(nodes[nodeIndex].publicKey);
}
/**
* @dev Returns the finish exit time of a given node.
*/
function getNodeFinishTime(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].finishTime;
}
/**
* @dev Checks whether a node has left the network.
*/
function isNodeLeft(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Left;
}
function isNodeInMaintenance(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.In_Maintenance;
}
/**
* @dev Returns a given node's last reward date.
*/
function getNodeLastRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].lastRewardDate;
}
/**
* @dev Returns a given node's next reward date.
*/
function getNodeNextRewardDate(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (uint)
{
return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex);
}
/**
* @dev Returns the total number of registered nodes.
*/
function getNumberOfNodes() external view returns (uint) {
return nodes.length;
}
/**
* @dev Returns the total number of online nodes.
*
* Note: Online nodes are equal to the number of active plus leaving nodes.
*/
function getNumberOnlineNodes() external view returns (uint) {
return numberOfActiveNodes.add(numberOfLeavingNodes);
}
/**
* @dev Returns IPs of active nodes.
*/
function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) {
activeNodeIPs = new bytes4[](numberOfActiveNodes);
uint indexOfActiveNodeIPs = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip;
indexOfActiveNodeIPs++;
}
}
}
/**
* @dev Returns active nodes linked to the `msg.sender` (validator address).
*/
function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) {
activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes);
uint indexOfActiveNodesByAddress = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeExist(msg.sender, indexOfNodes) && isNodeActive(indexOfNodes)) {
activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes;
indexOfActiveNodesByAddress++;
}
}
}
/**
* @dev Return active node IDs.
*/
function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) {
activeNodeIds = new uint[](numberOfActiveNodes);
uint indexOfActiveNodeIds = 0;
for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) {
if (isNodeActive(indexOfNodes)) {
activeNodeIds[indexOfActiveNodeIds] = indexOfNodes;
indexOfActiveNodeIds++;
}
}
}
/**
* @dev Return a given node's current status.
*/
function getNodeStatus(uint nodeIndex)
external
view
checkNodeExists(nodeIndex)
returns (NodeStatus)
{
return nodes[nodeIndex].status;
}
/**
* @dev Return a validator's linked nodes.
*
* Requirements:
*
* - Validator ID must exist.
*/
function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
require(validatorService.validatorExists(validatorId), "Validator ID does not exist");
return validatorToNodeIndexes[validatorId];
}
/**
* @dev constructor in Permissions approach.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
numberOfActiveNodes = 0;
numberOfLeavingNodes = 0;
numberOfLeftNodes = 0;
}
/**
* @dev Returns the Validator ID for a given node.
*/
function getValidatorId(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (uint)
{
return nodes[nodeIndex].validatorId;
}
/**
* @dev Checks whether a node exists for a given address.
*/
function isNodeExist(address from, uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodeIndexes[from].isNodeExist[nodeIndex];
}
/**
* @dev Checks whether a node's status is Active.
*/
function isNodeActive(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Active;
}
/**
* @dev Checks whether a node's status is Leaving.
*/
function isNodeLeaving(uint nodeIndex)
public
view
checkNodeExists(nodeIndex)
returns (bool)
{
return nodes[nodeIndex].status == NodeStatus.Leaving;
}
/**
* @dev Returns number of nodes with available space.
*/
function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
count = 0;
uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE();
for (uint8 i = freeSpace; i <= totalSpace; ++i) {
count = count.add(spaceToNodes[i].length);
}
}
/**
* @dev Returns the index of a given node within the validator's node index.
*/
function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) {
uint i;
for (i = 0; i < validatorNodeIndexes.length; i++) {
if (validatorNodeIndexes[i] == nodeIndex) {
return i;
}
}
return validatorNodeIndexes.length;
}
/**
* @dev Moves a node to a new space mapping.
*/
function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private {
uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace;
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) {
uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)];
spaceToNodes[previousSpace][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
spaceToNodes[previousSpace].pop();
} else {
spaceToNodes[previousSpace].pop();
}
spaceToNodes[newSpace].push(nodeIndex);
spaceOfNodes[nodeIndex].freeSpace = newSpace;
spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1);
}
/**
* @dev Changes a node's status to Active.
*/
function _setNodeActive(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Active;
numberOfActiveNodes = numberOfActiveNodes.add(1);
}
/**
* @dev Changes a node's status to In_Maintenance.
*/
function _setNodeInMaintenance(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.In_Maintenance;
numberOfActiveNodes = numberOfActiveNodes.sub(1);
}
/**
* @dev Changes a node's status to Left.
*/
function _setNodeLeft(uint nodeIndex) private {
nodesIPCheck[nodes[nodeIndex].ip] = false;
nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false;
delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))];
if (nodes[nodeIndex].status == NodeStatus.Active) {
numberOfActiveNodes--;
} else {
numberOfLeavingNodes--;
}
nodes[nodeIndex].status = NodeStatus.Left;
numberOfLeftNodes++;
}
/**
* @dev Changes a node's status to Leaving.
*/
function _setNodeLeaving(uint nodeIndex) private {
nodes[nodeIndex].status = NodeStatus.Leaving;
numberOfActiveNodes--;
numberOfLeavingNodes++;
}
/**
* @dev Adds node to array.
*/
function _addNode(
address from,
string memory name,
bytes4 ip,
bytes4 publicIP,
uint16 port,
bytes32[2] memory publicKey,
string memory domainName,
uint validatorId
)
private
returns (uint nodeIndex)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
nodes.push(Node({
name: name,
ip: ip,
publicIP: publicIP,
port: port,
//owner: from,
publicKey: publicKey,
startBlock: block.number,
lastRewardDate: block.timestamp,
finishTime: 0,
status: NodeStatus.Active,
validatorId: validatorId,
domainName: domainName
}));
nodeIndex = nodes.length.sub(1);
validatorToNodeIndexes[validatorId].push(nodeIndex);
bytes32 nodeId = keccak256(abi.encodePacked(name));
nodesIPCheck[ip] = true;
nodesNameCheck[nodeId] = true;
nodesNameToIndex[nodeId] = nodeIndex;
nodeIndexes[from].isNodeExist[nodeIndex] = true;
nodeIndexes[from].numberOfNodes++;
spaceOfNodes.push(SpaceManaging({
freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(),
indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length
}));
spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex);
numberOfActiveNodes++;
}
/**
* @dev Deletes node from array.
*/
function _deleteNode(uint nodeIndex) private {
uint8 space = spaceOfNodes[nodeIndex].freeSpace;
uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap;
if (indexInArray < spaceToNodes[space].length.sub(1)) {
uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)];
spaceToNodes[space][indexInArray] = shiftedIndex;
spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray;
spaceToNodes[space].pop();
} else {
spaceToNodes[space].pop();
}
delete spaceOfNodes[nodeIndex].freeSpace;
delete spaceOfNodes[nodeIndex].indexInSpaceMap;
}
function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) {
bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1]));
bytes20 addr;
for (uint8 i = 12; i < 32; i++) {
addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8);
}
return address(addr);
}
function _min(uint a, uint b) private pure returns (uint) {
if (a < b) {
return a;
} else {
return b;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "./ContractManager.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeSafe {
using SafeMath for uint;
using Address for address;
ContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual initializer {
AccessControlUpgradeSafe.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = ContractManager(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Schains.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./ConstantsHolder.sol";
import "./KeyStorage.sol";
import "./SkaleVerifier.sol";
import "./utils/FieldOperations.sol";
import "./NodeRotation.sol";
import "./interfaces/ISkaleDKG.sol";
/**
* @title Schains
* @dev Contains functions to manage Schains such as Schain creation,
* deletion, and rotation.
*/
contract Schains is Permissions {
using StringUtils for string;
using StringUtils for uint;
struct SchainParameters {
uint lifetime;
uint8 typeOfSchain;
uint16 nonce;
string name;
}
/**
* @dev Emitted when an schain is created.
*/
event SchainCreated(
string name,
address owner,
uint partOfNode,
uint lifetime,
uint numberOfNodes,
uint deposit,
uint16 nonce,
bytes32 schainId,
uint time,
uint gasSpend
);
/**
* @dev Emitted when an schain is deleted.
*/
event SchainDeleted(
address owner,
string name,
bytes32 indexed schainId
);
/**
* @dev Emitted when a node in an schain is rotated.
*/
event NodeRotated(
bytes32 schainId,
uint oldNode,
uint newNode
);
/**
* @dev Emitted when a node is added to an schain.
*/
event NodeAdded(
bytes32 schainId,
uint newNode
);
/**
* @dev Emitted when a group of nodes is created for an schain.
*/
event SchainNodes(
string name,
bytes32 schainId,
uint[] nodesInGroup,
uint time,
uint gasSpend
);
bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE");
/**
* @dev Allows SkaleManager contract to create an Schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type is valid.
* - There is sufficient deposit to create type of schain.
*/
function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") {
SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data);
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp();
uint minSchainLifetime = constantsHolder.minimalSchainLifetime();
require(now >= schainCreationTimeStamp, "It is not a time for creating Schain");
require(
schainParameters.lifetime >= minSchainLifetime,
"Minimal schain lifetime should be satisfied"
);
require(
getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit,
"Not enough money to create Schain");
_addSchain(from, deposit, schainParameters);
}
function addSchainByFoundation(
uint lifetime,
uint8 typeOfSchain,
uint16 nonce,
string calldata name
)
external
{
require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain");
SchainParameters memory schainParameters = SchainParameters({
lifetime: lifetime,
typeOfSchain: typeOfSchain,
nonce: nonce,
name: name
});
_addSchain(msg.sender, 0, schainParameters);
}
/**
* @dev Allows SkaleManager to remove an schain from the network.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Executed by schain owner.
*/
function deleteSchain(address from, string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
bytes32 schainId = keccak256(abi.encodePacked(name));
require(
schainsInternal.isOwnerAddress(from, schainId),
"Message sender is not the owner of the Schain"
);
address nodesAddress = contractManager.getContract("Nodes");
// removes Schain from Nodes
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId);
uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId);
for (uint i = 0; i < nodesInGroup.length; i++) {
uint schainIndex = schainsInternal.findSchainAtSchainsForNode(
nodesInGroup[i],
schainId
);
if (schainsInternal.checkHoleForSchain(schainId, i)) {
continue;
}
require(
schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]),
"Some Node does not contain given Schain");
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId);
schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]);
if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) {
this.addSpace(nodesInGroup[i], partOfNode);
}
}
schainsInternal.deleteGroup(schainId);
schainsInternal.removeSchain(schainId, from);
schainsInternal.removeHolesForSchain(schainId);
nodeRotation.removeRotation(schainId);
emit SchainDeleted(from, name, schainId);
}
/**
* @dev Allows SkaleManager to delete any Schain.
* Upon removal, the space availability of each node is updated.
*
* Emits an {SchainDeleted} event.
*
* Requirements:
*
* - Schain exists.
*/
function deleteSchainByRoot(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainId = keccak256(abi.encodePacked(name));
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isSchainExist(schainId), "Schain does not exist");
// removes Schain from Nodes
uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId);
uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId);
for (uint i = 0; i < nodesInGroup.length; i++) {
uint schainIndex = schainsInternal.findSchainAtSchainsForNode(
nodesInGroup[i],
schainId
);
if (schainsInternal.checkHoleForSchain(schainId, i)) {
continue;
}
require(
schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]),
"Some Node does not contain given Schain");
schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId);
schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]);
this.addSpace(nodesInGroup[i], partOfNode);
}
schainsInternal.deleteGroup(schainId);
address from = schainsInternal.getSchainOwner(schainId);
schainsInternal.removeSchain(schainId, from);
schainsInternal.removeHolesForSchain(schainId);
nodeRotation.removeRotation(schainId);
emit SchainDeleted(from, name, schainId);
}
/**
* @dev Allows SkaleManager contract to restart schain creation by forming a
* new schain group. Executed when DKG procedure fails and becomes stuck.
*
* Emits a {NodeAdded} event.
*
* Requirements:
*
* - Previous DKG procedure must have failed.
* - DKG failure got stuck because there were no free nodes to rotate in.
* - A free node must be released in the network.
*/
function restartSchainCreation(string calldata name) external allow("SkaleManager") {
NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation"));
bytes32 schainId = keccak256(abi.encodePacked(name));
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success");
SchainsInternal schainsInternal = SchainsInternal(
contractManager.getContract("SchainsInternal"));
require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation");
uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId);
skaleDKG.openChannel(schainId);
emit NodeAdded(schainId, newNodeIndex);
}
/**
* @dev addSpace - return occupied space to Node
* @param nodeIndex - index of Node at common array of Nodes
* @param partOfNode - divisor of given type of Schain
*/
function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
nodes.addSpaceToNode(nodeIndex, partOfNode);
}
/**
* @dev Checks whether schain group signature is valid.
*/
function verifySchainSignature(
uint signatureA,
uint signatureB,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
string calldata schainName
)
external
view
returns (bool)
{
SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier"));
G2Operations.G2Point memory publicKey = KeyStorage(
contractManager.getContract("KeyStorage")
).getCommonPublicKey(
keccak256(abi.encodePacked(schainName))
);
return skaleVerifier.verify(
Fp2Operations.Fp2Point({
a: signatureA,
b: signatureB
}),
hash, counter,
hashA, hashB,
publicKey
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
/**
* @dev Returns the current price in SKL tokens for given Schain type and lifetime.
*/
function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint nodeDeposit = constantsHolder.NODE_DEPOSIT();
uint numberOfNodes;
uint8 divisor;
(numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(typeOfSchain);
if (divisor == 0) {
return 1e18;
} else {
uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2)));
uint down = uint(
uint(constantsHolder.SMALL_DIVISOR())
.mul(uint(constantsHolder.SECONDS_TO_YEAR()))
.div(divisor)
);
return up.div(down);
}
}
/**
* @dev Returns the number of Nodes and resource divisor that is needed for a
* given Schain type.
*/
function getNodesDataFromTypeOfSchain(uint typeOfSchain)
public
view
returns (uint numberOfNodes, uint8 partOfNode)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN();
if (typeOfSchain == 1) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR();
} else if (typeOfSchain == 2) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR();
} else if (typeOfSchain == 3) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR();
} else if (typeOfSchain == 4) {
partOfNode = 0;
numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN();
} else if (typeOfSchain == 5) {
partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR();
numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN();
} else {
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
(partOfNode, numberOfNodes) = schainsInternal.schainTypes(typeOfSchain);
if (numberOfNodes == 0) {
revert("Bad schain type");
}
}
}
/**
* @dev Initializes an schain in the SchainsInternal contract.
*
* Requirements:
*
* - Schain name is not already in use.
*/
function _initializeSchainInSchainsInternal(
string memory name,
address from,
uint deposit,
uint lifetime) private
{
address dataAddress = contractManager.getContract("SchainsInternal");
require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available");
// initialize Schain
SchainsInternal(dataAddress).initializeSchain(
name,
from,
lifetime,
deposit);
SchainsInternal(dataAddress).setSchainIndex(keccak256(abi.encodePacked(name)), from);
}
/**
* @dev Converts data from bytes to normal schain parameters of lifetime,
* type, nonce, and name.
*/
function _fallbackSchainParametersDataConverter(bytes memory data)
private
pure
returns (SchainParameters memory schainParameters)
{
(schainParameters.lifetime,
schainParameters.typeOfSchain,
schainParameters.nonce,
schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string));
}
/**
* @dev Allows creation of node group for Schain.
*
* Emits an {SchainNodes} event.
*/
function _createGroupForSchain(
string memory schainName,
bytes32 schainId,
uint numberOfNodes,
uint8 partOfNode
)
private
{
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode);
ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId);
emit SchainNodes(
schainName,
schainId,
nodesInGroup,
block.timestamp,
gasleft());
}
/**
* @dev Creates an schain.
*
* Emits an {SchainCreated} event.
*
* Requirements:
*
* - Schain type must be valid.
*/
function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private {
uint numberOfNodes;
uint8 partOfNode;
SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));
require(schainParameters.typeOfSchain <= schainsInternal.numberOfSchainTypes(), "Invalid type of Schain");
//initialize Schain
_initializeSchainInSchainsInternal(
schainParameters.name,
from,
deposit,
schainParameters.lifetime);
// create a group for Schain
(numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain);
_createGroupForSchain(
schainParameters.name,
keccak256(abi.encodePacked(schainParameters.name)),
numberOfNodes,
partOfNode
);
emit SchainCreated(
schainParameters.name,
from,
partOfNode,
schainParameters.lifetime,
numberOfNodes,
deposit,
schainParameters.nonce,
keccak256(abi.encodePacked(schainParameters.name)),
block.timestamp,
gasleft());
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SchainsInternal.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./ConstantsHolder.sol";
import "./Nodes.sol";
import "./interfaces/ISkaleDKG.sol";
/**
* @title SchainsInternal
* @dev Contract contains all functionality logic to internally manage Schains.
*/
contract SchainsInternal is Permissions {
struct Schain {
string name;
address owner;
uint indexInOwnerList;
uint8 partOfNode;
uint lifetime;
uint startDate;
uint startBlock;
uint deposit;
uint64 index;
}
struct SchainType {
uint8 partOfNode;
uint numberOfNodes;
}
// mapping which contain all schains
mapping (bytes32 => Schain) public schains;
mapping (bytes32 => bool) public isSchainActive;
mapping (bytes32 => uint[]) public schainsGroups;
mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups;
// mapping shows schains by owner's address
mapping (address => bytes32[]) public schainIndexes;
// mapping shows schains which Node composed in
mapping (uint => bytes32[]) public schainsForNodes;
mapping (uint => uint[]) public holesForNodes;
mapping (bytes32 => uint[]) public holesForSchains;
// array which contain all schains
bytes32[] public schainsAtSystem;
uint64 public numberOfSchains;
// total resources that schains occupied
uint public sumOfSchainsResources;
mapping (bytes32 => bool) public usedSchainNames;
mapping (uint => SchainType) public schainTypes;
uint public numberOfSchainTypes;
// schain hash => node index => index of place
// index of place is a number from 1 to max number of slots on node(128)
mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode;
/**
* @dev Allows Schain contract to initialize an schain.
*/
function initializeSchain(
string calldata name,
address from,
uint lifetime,
uint deposit) external allow("Schains")
{
bytes32 schainId = keccak256(abi.encodePacked(name));
schains[schainId].name = name;
schains[schainId].owner = from;
schains[schainId].startDate = block.timestamp;
schains[schainId].startBlock = block.number;
schains[schainId].lifetime = lifetime;
schains[schainId].deposit = deposit;
schains[schainId].index = numberOfSchains;
isSchainActive[schainId] = true;
numberOfSchains++;
schainsAtSystem.push(schainId);
usedSchainNames[schainId] = true;
}
/**
* @dev Allows Schain contract to create a node group for an schain.
*/
function createGroupForSchain(
bytes32 schainId,
uint numberOfNodes,
uint8 partOfNode
)
external
allow("Schains")
returns (uint[] memory)
{
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
schains[schainId].partOfNode = partOfNode;
if (partOfNode > 0) {
sumOfSchainsResources = sumOfSchainsResources.add(
numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode)
);
}
return _generateGroup(schainId, numberOfNodes);
}
/**
* @dev Allows Schains contract to set index in owner list.
*/
function setSchainIndex(bytes32 schainId, address from) external allow("Schains") {
schains[schainId].indexInOwnerList = schainIndexes[from].length;
schainIndexes[from].push(schainId);
}
/**
* @dev Allows Schains contract to change the Schain lifetime through
* an additional SKL token deposit.
*/
function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") {
schains[schainId].deposit = schains[schainId].deposit.add(deposit);
schains[schainId].lifetime = schains[schainId].lifetime.add(lifetime);
}
/**
* @dev Allows Schains contract to remove an schain from the network.
* Generally schains are not removed from the system; instead they are
* simply allowed to expire.
*/
function removeSchain(bytes32 schainId, address from) external allow("Schains") {
isSchainActive[schainId] = false;
uint length = schainIndexes[from].length;
uint index = schains[schainId].indexInOwnerList;
if (index != length.sub(1)) {
bytes32 lastSchainId = schainIndexes[from][length.sub(1)];
schains[lastSchainId].indexInOwnerList = index;
schainIndexes[from][index] = lastSchainId;
}
schainIndexes[from].pop();
// TODO:
// optimize
for (uint i = 0; i + 1 < schainsAtSystem.length; i++) {
if (schainsAtSystem[i] == schainId) {
schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)];
break;
}
}
schainsAtSystem.pop();
delete schains[schainId];
numberOfSchains--;
}
/**
* @dev Allows Schains and SkaleDKG contracts to remove a node from an
* schain for node rotation or DKG failure.
*/
function removeNodeFromSchain(
uint nodeIndex,
bytes32 schainHash
)
external
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint indexOfNode = _findNode(schainHash, nodeIndex);
uint indexOfLastNode = schainsGroups[schainHash].length.sub(1);
if (indexOfNode == indexOfLastNode) {
schainsGroups[schainHash].pop();
} else {
delete schainsGroups[schainHash][indexOfNode];
if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) {
uint hole = holesForSchains[schainHash][0];
holesForSchains[schainHash][0] = indexOfNode;
holesForSchains[schainHash].push(hole);
} else {
holesForSchains[schainHash].push(indexOfNode);
}
}
uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash);
removeSchainForNode(nodeIndex, schainIndexOnNode);
delete placeOfSchainOnNode[schainHash][nodeIndex];
}
/**
* @dev Allows Schains contract to remove node from exceptions
*/
function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") {
_exceptionsForGroups[schainHash][nodeIndex] = false;
}
/**
* @dev Allows Schains contract to delete a group of schains
*/
function deleteGroup(bytes32 schainId) external allow("Schains") {
// delete channel
ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));
delete schainsGroups[schainId];
skaleDKG.deleteChannel(schainId);
}
/**
* @dev Allows Schain and NodeRotation contracts to set a Node like
* exception for a given schain and nodeIndex.
*/
function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
_exceptionsForGroups[schainId][nodeIndex] = true;
}
/**
* @dev Allows Schains and NodeRotation contracts to add node to an schain
* group.
*/
function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") {
if (holesForSchains[schainId].length == 0) {
schainsGroups[schainId].push(nodeIndex);
} else {
schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex;
uint min = uint(-1);
uint index = 0;
for (uint i = 1; i < holesForSchains[schainId].length; i++) {
if (min > holesForSchains[schainId][i]) {
min = holesForSchains[schainId][i];
index = i;
}
}
if (min == uint(-1)) {
delete holesForSchains[schainId];
} else {
holesForSchains[schainId][0] = min;
holesForSchains[schainId][index] =
holesForSchains[schainId][holesForSchains[schainId].length - 1];
holesForSchains[schainId].pop();
}
}
}
/**
* @dev Allows Schains contract to remove holes for schains
*/
function removeHolesForSchain(bytes32 schainHash) external allow("Schains") {
delete holesForSchains[schainHash];
}
/**
* @dev Allows Admin to add schain type
*/
function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlyAdmin {
schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode;
schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes;
numberOfSchainTypes++;
}
/**
* @dev Allows Admin to remove schain type
*/
function removeSchainType(uint typeOfSchain) external onlyAdmin {
delete schainTypes[typeOfSchain].partOfNode;
delete schainTypes[typeOfSchain].numberOfNodes;
}
/**
* @dev Allows Admin to set number of schain types
*/
function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin {
numberOfSchainTypes = newNumberOfSchainTypes;
}
/**
* @dev Allows Admin to move schain to placeOfSchainOnNode map
*/
function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin {
for (uint i = 0; i < schainsGroups[schainHash].length; i++) {
uint nodeIndex = schainsGroups[schainHash][i];
for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) {
if (schainsForNodes[nodeIndex][j] == schainHash) {
placeOfSchainOnNode[schainHash][nodeIndex] = j + 1;
}
}
}
}
/**
* @dev Returns all Schains in the network.
*/
function getSchains() external view returns (bytes32[] memory) {
return schainsAtSystem;
}
/**
* @dev Returns all occupied resources on one node for an Schain.
*/
function getSchainsPartOfNode(bytes32 schainId) external view returns (uint8) {
return schains[schainId].partOfNode;
}
/**
* @dev Returns number of schains by schain owner.
*/
function getSchainListSize(address from) external view returns (uint) {
return schainIndexes[from].length;
}
/**
* @dev Returns hashes of schain names by schain owner.
*/
function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) {
return schainIndexes[from];
}
/**
* @dev Returns hashes of schain names running on a node.
*/
function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) {
return schainsForNodes[nodeIndex];
}
/**
* @dev Returns the owner of an schain.
*/
function getSchainOwner(bytes32 schainId) external view returns (address) {
return schains[schainId].owner;
}
/**
* @dev Checks whether schain name is available.
* TODO Need to delete - copy of web3.utils.soliditySha3
*/
function isSchainNameAvailable(string calldata name) external view returns (bool) {
bytes32 schainId = keccak256(abi.encodePacked(name));
return schains[schainId].owner == address(0) &&
!usedSchainNames[schainId] &&
keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet"));
}
/**
* @dev Checks whether schain lifetime has expired.
*/
function isTimeExpired(bytes32 schainId) external view returns (bool) {
return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp;
}
/**
* @dev Checks whether address is owner of schain.
*/
function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) {
return schains[schainId].owner == from;
}
/**
* @dev Checks whether schain exists.
*/
function isSchainExist(bytes32 schainId) external view returns (bool) {
return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked(""));
}
/**
* @dev Returns schain name.
*/
function getSchainName(bytes32 schainId) external view returns (string memory) {
return schains[schainId].name;
}
/**
* @dev Returns last active schain of a node.
*/
function getActiveSchain(uint nodeIndex) external view returns (bytes32) {
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
return schainsForNodes[nodeIndex][i - 1];
}
}
return bytes32(0);
}
/**
* @dev Returns active schains of a node.
*/
function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) {
uint activeAmount = 0;
for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) {
if (schainsForNodes[nodeIndex][i] != bytes32(0)) {
activeAmount++;
}
}
uint cursor = 0;
activeSchains = new bytes32[](activeAmount);
for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) {
if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) {
activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1];
}
}
}
/**
* @dev Returns number of nodes in an schain group.
*/
function getNumberOfNodesInGroup(bytes32 schainId) external view returns (uint) {
return schainsGroups[schainId].length;
}
/**
* @dev Returns nodes in an schain group.
*/
function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) {
return schainsGroups[schainId];
}
/**
* @dev Checks whether sender is a node address from a given schain group.
*/
function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
for (uint i = 0; i < schainsGroups[schainId].length; i++) {
if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) {
return true;
}
}
return false;
}
/**
* @dev Returns node index in schain group.
*/
function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) {
for (uint index = 0; index < schainsGroups[schainId].length; index++) {
if (schainsGroups[schainId][index] == nodeId) {
return index;
}
}
return schainsGroups[schainId].length;
}
/**
* @dev Checks whether there are any nodes with free resources for given
* schain.
*/
function isAnyFreeNode(bytes32 schainId) external view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space);
for (uint i = 0; i < nodesWithFreeSpace.length; i++) {
if (_isCorrespond(schainId, nodesWithFreeSpace[i])) {
return true;
}
}
return false;
}
/**
* @dev Returns whether any exceptions exist for node in a schain group.
*/
function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) {
return _exceptionsForGroups[schainId][nodeIndex];
}
function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) {
for (uint i = 0; i < holesForSchains[schainHash].length; i++) {
if (holesForSchains[schainHash][i] == indexOfNode) {
return true;
}
}
return false;
}
/**
* @dev Returns number of Schains on a node.
*/
function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) {
return schainsForNodes[nodeIndex].length;
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
numberOfSchains = 0;
sumOfSchainsResources = 0;
numberOfSchainTypes = 5;
}
/**
* @dev Allows Schains and NodeRotation contracts to add schain to node.
*/
function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") {
if (holesForNodes[nodeIndex].length == 0) {
schainsForNodes[nodeIndex].push(schainId);
placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length;
} else {
uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1];
schainsForNodes[nodeIndex][lastHoleOfNode] = schainId;
placeOfSchainOnNode[schainId][nodeIndex] = lastHoleOfNode + 1;
holesForNodes[nodeIndex].pop();
}
}
/**
* @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an
* schain from a node.
*/
function removeSchainForNode(uint nodeIndex, uint schainIndex)
public
allowThree("NodeRotation", "SkaleDKG", "Schains")
{
uint length = schainsForNodes[nodeIndex].length;
if (schainIndex == length.sub(1)) {
schainsForNodes[nodeIndex].pop();
} else {
schainsForNodes[nodeIndex][schainIndex] = bytes32(0);
if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) {
uint hole = holesForNodes[nodeIndex][0];
holesForNodes[nodeIndex][0] = schainIndex;
holesForNodes[nodeIndex].push(hole);
} else {
holesForNodes[nodeIndex].push(schainIndex);
}
}
}
/**
* @dev Returns index of Schain in list of schains for a given node.
*/
function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) {
if (placeOfSchainOnNode[schainId][nodeIndex] == 0)
return schainsForNodes[nodeIndex].length;
return placeOfSchainOnNode[schainId][nodeIndex] - 1;
}
function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space);
uint counter = 0;
for (uint i = 0; i < nodesWithFreeSpace.length; i++) {
if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) {
counter++;
}
}
if (counter < nodesWithFreeSpace.length) {
result = new uint[](nodesWithFreeSpace.length.sub(counter));
counter = 0;
for (uint i = 0; i < nodesWithFreeSpace.length; i++) {
if (_isCorrespond(schainId, nodesWithFreeSpace[i])) {
result[counter] = nodesWithFreeSpace[i];
counter++;
}
}
}
}
/**
* @dev Generates schain group using a pseudo-random generator.
*/
function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
uint8 space = schains[schainId].partOfNode;
nodesInGroup = new uint[](numberOfNodes);
uint[] memory possibleNodes = isEnoughNodes(schainId);
require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain");
uint ignoringTail = 0;
uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId)));
for (uint i = 0; i < nodesInGroup.length; ++i) {
uint index = random % (possibleNodes.length.sub(ignoringTail));
uint node = possibleNodes[index];
nodesInGroup[i] = node;
_swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1));
++ignoringTail;
_exceptionsForGroups[schainId][node] = true;
addSchainForNode(node, schainId);
require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node");
}
// set generated group
schainsGroups[schainId] = nodesInGroup;
}
function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) {
Nodes nodes = Nodes(contractManager.getContract("Nodes"));
return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex);
}
/**
* @dev Swaps one index for another in an array.
*/
function _swap(uint[] memory array, uint index1, uint index2) private pure {
uint buffer = array[index1];
array[index1] = array[index2];
array[index2] = buffer;
}
/**
* @dev Returns local index of node in schain group.
*/
function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) {
uint[] memory nodesInGroup = schainsGroups[schainId];
uint index;
for (index = 0; index < nodesInGroup.length; index++) {
if (nodesInGroup[index] == nodeIndex) {
return index;
}
}
return index;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
SkaleVerifier.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "./Permissions.sol";
import "./SchainsInternal.sol";
import "./utils/Precompiled.sol";
import "./utils/FieldOperations.sol";
/**
* @title SkaleVerifier
* @dev Contains verify function to perform BLS signature verification.
*/
contract SkaleVerifier is Permissions {
using Fp2Operations for Fp2Operations.Fp2Point;
/**
* @dev Verifies a BLS signature.
*
* Requirements:
*
* - Signature is in G1.
* - Hash is in G1.
* - G2.one in G2.
* - Public Key in G2.
*/
function verify(
Fp2Operations.Fp2Point calldata signature,
bytes32 hash,
uint counter,
uint hashA,
uint hashB,
G2Operations.G2Point calldata publicKey
)
external
view
returns (bool)
{
require(G1Operations.checkRange(signature), "Signature is not valid");
if (!_checkHashToGroupWithHelper(
hash,
counter,
hashA,
hashB
)
)
{
return false;
}
uint newSignB = G1Operations.negate(signature.b);
require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1");
require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1");
G2Operations.G2Point memory g2 = G2Operations.getG2Generator();
require(
G2Operations.isG2(publicKey),
"Public Key not in G2"
);
return Precompiled.bn256Pairing(
signature.a, newSignB,
g2.x.b, g2.x.a, g2.y.b, g2.y.a,
hashA, hashB,
publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a
);
}
function initialize(address newContractsAddress) public override initializer {
Permissions.initialize(newContractsAddress);
}
function _checkHashToGroupWithHelper(
bytes32 hash,
uint counter,
uint hashA,
uint hashB
)
private
pure
returns (bool)
{
if (counter > 100) {
return false;
}
uint xCoord = uint(hash) % Fp2Operations.P;
xCoord = (xCoord.add(counter)) % Fp2Operations.P;
uint ySquared = addmod(
mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P),
3,
Fp2Operations.P
);
if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) {
return false;
}
return true;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol";
import "../BountyV2.sol";
import "../Nodes.sol";
import "../Permissions.sol";
import "../utils/FractionUtils.sol";
import "../utils/MathUtils.sol";
import "./DelegationPeriodManager.sol";
import "./PartialDifferences.sol";
import "./Punisher.sol";
import "./TokenLaunchLocker.sol";
import "./TokenState.sol";
import "./ValidatorService.sol";
/**
* @title Delegation Controller
* @dev This contract performs all delegation functions including delegation
* requests, and undelegation, etc.
*
* Delegators and validators may both perform delegations. Validators who perform
* delegations to themselves are effectively self-delegating or self-bonding.
*
* IMPORTANT: Undelegation may be requested at any time, but undelegation is only
* performed at the completion of the current delegation period.
*
* Delegated tokens may be in one of several states:
*
* - PROPOSED: token holder proposes tokens to delegate to a validator.
* - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation.
* - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator.
* - REJECTED: token proposal expires at the UTC start of the next month.
* - DELEGATED: accepted delegations are delegated at the UTC start of the month.
* - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator.
* - COMPLETED: undelegation request is completed at the end of the delegation period.
*/
contract DelegationController is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Sequence;
using PartialDifferences for PartialDifferences.Value;
using FractionUtils for FractionUtils.Fraction;
uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60;
enum State {
PROPOSED,
ACCEPTED,
CANCELED,
REJECTED,
DELEGATED,
UNDELEGATION_REQUESTED,
COMPLETED
}
struct Delegation {
address holder; // address of token owner
uint validatorId;
uint amount;
uint delegationPeriod;
uint created; // time of delegation creation
uint started; // month when a delegation becomes active
uint finished; // first month after a delegation ends
string info;
}
struct SlashingLogEvent {
FractionUtils.Fraction reducingCoefficient;
uint nextMonth;
}
struct SlashingLog {
// month => slashing event
mapping (uint => SlashingLogEvent) slashes;
uint firstMonth;
uint lastMonth;
}
struct DelegationExtras {
uint lastSlashingMonthBeforeDelegation;
}
struct SlashingEvent {
FractionUtils.Fraction reducingCoefficient;
uint validatorId;
uint month;
}
struct SlashingSignal {
address holder;
uint penalty;
}
struct LockedInPending {
uint amount;
uint month;
}
struct FirstDelegationMonth {
// month
uint value;
//validatorId => month
mapping (uint => uint) byValidator;
}
struct ValidatorsStatistics {
// number of validators
uint number;
//validatorId => bool - is Delegated or not
mapping (uint => uint) delegated;
}
/**
* @dev Emitted when a delegation is proposed to a validator.
*/
event DelegationProposed(
uint delegationId
);
/**
* @dev Emitted when a delegation is accepted by a validator.
*/
event DelegationAccepted(
uint delegationId
);
/**
* @dev Emitted when a delegation is cancelled by the delegator.
*/
event DelegationRequestCanceledByUser(
uint delegationId
);
/**
* @dev Emitted when a delegation is requested to undelegate.
*/
event UndelegationRequested(
uint delegationId
);
/// @dev delegations will never be deleted to index in this array may be used like delegation id
Delegation[] public delegations;
// validatorId => delegationId[]
mapping (uint => uint[]) public delegationsByValidator;
// holder => delegationId[]
mapping (address => uint[]) public delegationsByHolder;
// delegationId => extras
mapping(uint => DelegationExtras) private _delegationExtras;
// validatorId => sequence
mapping (uint => PartialDifferences.Value) private _delegatedToValidator;
// validatorId => sequence
mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator;
// validatorId => slashing log
mapping (uint => SlashingLog) private _slashesOfValidator;
// holder => sequence
mapping (address => PartialDifferences.Value) private _delegatedByHolder;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator;
// holder => validatorId => sequence
mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator;
SlashingEvent[] private _slashes;
// holder => index in _slashes;
mapping (address => uint) private _firstUnprocessedSlashByHolder;
// holder => validatorId => month
mapping (address => FirstDelegationMonth) private _firstDelegationMonth;
// holder => locked in pending
mapping (address => LockedInPending) private _lockedInPendingDelegations;
mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator;
/**
* @dev Modifier to make a function callable only if delegation exists.
*/
modifier checkDelegationExists(uint delegationId) {
require(delegationId < delegations.length, "Delegation does not exist");
_;
}
/**
* @dev Update and return a validator's delegations.
*/
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth());
}
/**
* @dev Update and return the amount delegated.
*/
function getAndUpdateDelegatedAmount(address holder) external returns (uint) {
return _getAndUpdateDelegatedByHolder(holder);
}
/**
* @dev Update and return the effective amount delegated (minus slash) for
* the given month.
*/
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external
allow("Distributor") returns (uint effectiveDelegated)
{
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder);
effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId]
.getAndUpdateValueInSequence(month);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev Allows a token holder to create a delegation proposal of an `amount`
* and `delegationPeriod` to a `validatorId`. Delegation must be accepted
* by the validator before the UTC start of the month, otherwise the
* delegation will be rejected.
*
* The token holder may add additional information in each proposal.
*
* Emits a {DelegationProposed} event.
*
* Requirements:
*
* - Holder must have sufficient delegatable tokens.
* - Delegation must be above the validator's minimum delegation amount.
* - Delegation period must be allowed.
* - Validator must be authorized if trusted list is enabled.
* - Validator must be accepting new delegation requests.
*/
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external
{
require(
_getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod),
"This delegation period is not allowed");
_getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount);
_checkIfDelegationIsAllowed(msg.sender, validatorId);
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender);
uint delegationId = _addDelegation(
msg.sender,
validatorId,
amount,
delegationPeriod,
info);
// check that there is enough money
uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender);
uint forbiddenForDelegation = TokenState(contractManager.getTokenState())
.getAndUpdateForbiddenForDelegationAmount(msg.sender);
require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate");
emit DelegationProposed(delegationId);
_sendSlashingSignals(slashingSignals);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows token holder to cancel a delegation proposal.
*
* Emits a {DelegationRequestCanceledByUser} event.
*
* Requirements:
*
* - `msg.sender` must be the token holder of the delegation proposal.
* - Delegation state must be PROPOSED.
*/
function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request");
require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations");
delegations[delegationId].finished = _getCurrentMonth();
_subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
emit DelegationRequestCanceledByUser(delegationId);
}
/**
* @dev Allows a validator to accept a proposed delegation.
* Successful acceptance of delegations transition the tokens from a
* PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the
* delegation period.
*
* Emits a {DelegationAccepted} event.
*
* Requirements:
*
* - Validator must be recipient of proposal.
* - Delegation state must be PROPOSED.
*/
function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(
_getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId),
"No permissions to accept request");
_accept(delegationId);
}
/**
* @dev Allows delegator to undelegate a specific delegation.
*
* Emits UndelegationRequested event.
*
* Requirements:
*
* - `msg.sender` must be the delegator.
* - Delegation state must be DELEGATED.
*/
function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) {
require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation");
ValidatorService validatorService = _getValidatorService();
require(
delegations[delegationId].holder == msg.sender ||
(validatorService.validatorAddressExists(msg.sender) &&
delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)),
"Permission denied to request undelegation");
_removeValidatorFromValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId);
processAllSlashes(msg.sender);
delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId);
require(
now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS)
< _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished),
"Undelegation requests must be sent 3 days before the end of delegation period"
);
_subtractFromAllStatistics(delegationId);
emit UndelegationRequested(delegationId);
}
/**
* @dev Allows Punisher contract to slash an `amount` of stake from
* a validator. This slashes an amount of delegations of the validator,
* which reduces the amount that the validator has staked. This consequence
* may force the SKALE Manager to reduce the number of nodes a validator is
* operating so the validator can meet the Minimum Staking Requirement.
*
* Emits a {SlashingEvent}.
*
* See {Punisher}.
*/
function confiscate(uint validatorId, uint amount) external allow("Punisher") {
uint currentMonth = _getCurrentMonth();
FractionUtils.Fraction memory coefficient =
_delegatedToValidator[validatorId].reduceValue(amount, currentMonth);
uint initialEffectiveDelegated =
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth);
uint[] memory initialSubtractions = new uint[](0);
if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) {
initialSubtractions = new uint[](
_effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth)
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId]
.subtractDiff[currentMonth.add(i).add(1)];
}
}
_effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth);
_putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth);
_slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth}));
BountyV2 bounty = _getBounty();
bounty.handleDelegationRemoving(
initialEffectiveDelegated.sub(
_effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth)
),
currentMonth
);
for (uint i = 0; i < initialSubtractions.length; ++i) {
bounty.handleDelegationAdd(
initialSubtractions[i].sub(
_effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)]
),
currentMonth.add(i).add(1)
);
}
}
/**
* @dev Allows Distributor contract to return and update the effective
* amount delegated (minus slash) to a validator for a given month.
*/
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month)
external allowTwo("Bounty", "Distributor") returns (uint)
{
return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month);
}
/**
* @dev Return and update the amount delegated to a validator for the
* current month.
*/
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) {
return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth());
}
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) {
return _effectiveDelegatedToValidator[validatorId].getValuesInSequence();
}
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month);
}
function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) {
return _delegatedToValidator[validatorId].getValue(month);
}
/**
* @dev Return Delegation struct.
*/
function getDelegation(uint delegationId)
external view checkDelegationExists(delegationId) returns (Delegation memory)
{
return delegations[delegationId];
}
/**
* @dev Returns the first delegation month.
*/
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) {
return _firstDelegationMonth[holder].byValidator[validatorId];
}
/**
* @dev Returns a validator's total number of delegations.
*/
function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) {
return delegationsByValidator[validatorId].length;
}
/**
* @dev Returns a holder's total number of delegations.
*/
function getDelegationsByHolderLength(address holder) external view returns (uint) {
return delegationsByHolder[holder].length;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
}
/**
* @dev Process slashes up to the given limit.
*/
function processSlashes(address holder, uint limit) public {
_sendSlashingSignals(_processSlashesWithoutSignals(holder, limit));
}
/**
* @dev Process all slashes.
*/
function processAllSlashes(address holder) public {
processSlashes(holder, 0);
}
/**
* @dev Returns the token state of a given delegation.
*/
function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) {
if (delegations[delegationId].started == 0) {
if (delegations[delegationId].finished == 0) {
if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) {
return State.PROPOSED;
} else {
return State.REJECTED;
}
} else {
return State.CANCELED;
}
} else {
if (_getCurrentMonth() < delegations[delegationId].started) {
return State.ACCEPTED;
} else {
if (delegations[delegationId].finished == 0) {
return State.DELEGATED;
} else {
if (_getCurrentMonth() < delegations[delegationId].finished) {
return State.UNDELEGATION_REQUESTED;
} else {
return State.COMPLETED;
}
}
}
}
}
/**
* @dev Returns the amount of tokens in PENDING delegation state.
*/
function getLockedInPendingDelegations(address holder) public view returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
return 0;
} else {
return _lockedInPendingDelegations[holder].amount;
}
}
/**
* @dev Checks whether there are any unprocessed slashes.
*/
function hasUnprocessedSlashes(address holder) public view returns (bool) {
return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length;
}
// private
/**
* @dev Allows Nodes contract to get and update the amount delegated
* to validator for a given month.
*/
function _getAndUpdateDelegatedToValidator(uint validatorId, uint month)
private returns (uint)
{
return _delegatedToValidator[validatorId].getAndUpdateValue(month);
}
/**
* @dev Adds a new delegation proposal.
*/
function _addDelegation(
address holder,
uint validatorId,
uint amount,
uint delegationPeriod,
string memory info
)
private
returns (uint delegationId)
{
delegationId = delegations.length;
delegations.push(Delegation(
holder,
validatorId,
amount,
delegationPeriod,
now,
0,
0,
info
));
delegationsByValidator[validatorId].push(delegationId);
delegationsByHolder[holder].push(delegationId);
_addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount);
}
/**
* @dev Returns the month when a delegation ends.
*/
function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) {
uint currentMonth = _getCurrentMonth();
uint started = delegations[delegationId].started;
if (currentMonth < started) {
return started.add(delegations[delegationId].delegationPeriod);
} else {
uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod);
return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod));
}
}
function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].addToValue(amount, month);
}
function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month);
}
function _addToDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].addToValue(amount, month);
}
function _addToDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month);
}
function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1);
}
function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private {
_delegatedByHolder[holder].subtractFromValue(amount, month);
}
function _removeFromDelegatedByHolderToValidator(
address holder, uint validatorId, uint amount, uint month) private
{
_delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month);
}
function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private {
if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) {
_numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1);
}
_numberOfValidatorsPerDelegator[holder].
delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1);
}
function _addToEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month);
}
function _removeFromEffectiveDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint effectiveAmount,
uint month)
private
{
_effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month);
}
function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) {
uint currentMonth = _getCurrentMonth();
processAllSlashes(holder);
return _delegatedByHolder[holder].getAndUpdateValue(currentMonth);
}
function _getAndUpdateDelegatedByHolderToValidator(
address holder,
uint validatorId,
uint month)
private returns (uint)
{
return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month);
}
function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
if (_lockedInPendingDelegations[holder].month < currentMonth) {
_lockedInPendingDelegations[holder].amount = amount;
_lockedInPendingDelegations[holder].month = currentMonth;
} else {
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount);
}
}
function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) {
uint currentMonth = _getCurrentMonth();
assert(_lockedInPendingDelegations[holder].month == currentMonth);
_lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount);
}
function _getCurrentMonth() private view returns (uint) {
return _getTimeHelpers().getCurrentMonth();
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet));
}
function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private {
if (_firstDelegationMonth[holder].value == 0) {
_firstDelegationMonth[holder].value = month;
_firstUnprocessedSlashByHolder[holder] = _slashes.length;
}
if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) {
_firstDelegationMonth[holder].byValidator[validatorId] = month;
}
}
/**
* @dev Checks whether the holder has performed a delegation.
*/
function _everDelegated(address holder) private view returns (bool) {
return _firstDelegationMonth[holder].value > 0;
}
function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private {
_delegatedToValidator[validatorId].subtractFromValue(amount, month);
}
function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private {
_effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month);
}
/**
* @dev Returns the delegated amount after a slashing event.
*/
function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) {
uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation;
uint validatorId = delegations[delegationId].validatorId;
uint amount = delegations[delegationId].amount;
if (startMonth == 0) {
startMonth = _slashesOfValidator[validatorId].firstMonth;
if (startMonth == 0) {
return amount;
}
}
for (uint i = startMonth;
i > 0 && i < delegations[delegationId].finished;
i = _slashesOfValidator[validatorId].slashes[i].nextMonth) {
if (i >= delegations[delegationId].started) {
amount = amount
.mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator)
.div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator);
}
}
return amount;
}
function _putToSlashingLog(
SlashingLog storage log,
FractionUtils.Fraction memory coefficient,
uint month)
private
{
if (log.firstMonth == 0) {
log.firstMonth = month;
log.lastMonth = month;
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
} else {
require(log.lastMonth <= month, "Cannot put slashing event in the past");
if (log.lastMonth == month) {
log.slashes[month].reducingCoefficient =
log.slashes[month].reducingCoefficient.multiplyFraction(coefficient);
} else {
log.slashes[month].reducingCoefficient = coefficient;
log.slashes[month].nextMonth = 0;
log.slashes[log.lastMonth].nextMonth = month;
log.lastMonth = month;
}
}
}
function _processSlashesWithoutSignals(address holder, uint limit)
private returns (SlashingSignal[] memory slashingSignals)
{
if (hasUnprocessedSlashes(holder)) {
uint index = _firstUnprocessedSlashByHolder[holder];
uint end = _slashes.length;
if (limit > 0 && index.add(limit) < end) {
end = index.add(limit);
}
slashingSignals = new SlashingSignal[](end.sub(index));
uint begin = index;
for (; index < end; ++index) {
uint validatorId = _slashes[index].validatorId;
uint month = _slashes[index].month;
uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month);
if (oldValue.muchGreater(0)) {
_delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum(
_delegatedByHolder[holder],
_slashes[index].reducingCoefficient,
month);
_effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence(
_slashes[index].reducingCoefficient,
month);
slashingSignals[index.sub(begin)].holder = holder;
slashingSignals[index.sub(begin)].penalty
= oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month));
}
}
_firstUnprocessedSlashByHolder[holder] = end;
}
}
function _processAllSlashesWithoutSignals(address holder)
private returns (SlashingSignal[] memory slashingSignals)
{
return _processSlashesWithoutSignals(holder, 0);
}
function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private {
Punisher punisher = Punisher(contractManager.getPunisher());
address previousHolder = address(0);
uint accumulatedPenalty = 0;
for (uint i = 0; i < slashingSignals.length; ++i) {
if (slashingSignals[i].holder != previousHolder) {
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
previousHolder = slashingSignals[i].holder;
accumulatedPenalty = slashingSignals[i].penalty;
} else {
accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty);
}
}
if (accumulatedPenalty > 0) {
punisher.handleSlash(previousHolder, accumulatedPenalty);
}
}
function _addToAllStatistics(uint delegationId) private {
uint currentMonth = _getCurrentMonth();
delegations[delegationId].started = currentMonth.add(1);
if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) {
_delegationExtras[delegationId].lastSlashingMonthBeforeDelegation =
_slashesOfValidator[delegations[delegationId].validatorId].lastMonth;
}
_addToDelegatedToValidator(
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolder(
delegations[delegationId].holder,
delegations[delegationId].amount,
currentMonth.add(1));
_addToDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
delegations[delegationId].amount,
currentMonth.add(1));
_updateFirstDelegationMonth(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
currentMonth.add(1));
uint effectiveAmount = delegations[delegationId].amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_addToEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addToEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
currentMonth.add(1));
_addValidatorToValidatorsPerDelegators(
delegations[delegationId].holder,
delegations[delegationId].validatorId
);
}
function _subtractFromAllStatistics(uint delegationId) private {
uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId);
_removeFromDelegatedToValidator(
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolder(
delegations[delegationId].holder,
amountAfterSlashing,
delegations[delegationId].finished);
_removeFromDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
amountAfterSlashing,
delegations[delegationId].finished);
uint effectiveAmount = amountAfterSlashing.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod));
_removeFromEffectiveDelegatedToValidator(
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_removeFromEffectiveDelegatedByHolderToValidator(
delegations[delegationId].holder,
delegations[delegationId].validatorId,
effectiveAmount,
delegations[delegationId].finished);
_getTokenLaunchLocker().handleDelegationRemoving(
delegations[delegationId].holder,
delegationId,
delegations[delegationId].finished);
_getBounty().handleDelegationRemoving(
effectiveAmount,
delegations[delegationId].finished);
}
/**
* @dev Checks whether delegation to a validator is allowed.
*
* Requirements:
*
* - Delegator must not have reached the validator limit.
* - Delegation must be made in or after the first delegation month.
*/
function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) {
require(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 ||
(
_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 &&
_numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator()
),
"Limit of validators is reached"
);
}
function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) {
return DelegationPeriodManager(contractManager.getDelegationPeriodManager());
}
function _getBounty() private view returns (BountyV2) {
return BountyV2(contractManager.getBounty());
}
function _getValidatorService() private view returns (ValidatorService) {
return ValidatorService(contractManager.getValidatorService());
}
function _getTimeHelpers() private view returns (TimeHelpers) {
return TimeHelpers(contractManager.getTimeHelpers());
}
function _getTokenLaunchLocker() private view returns (TokenLaunchLocker) {
return TokenLaunchLocker(contractManager.getTokenLaunchLocker());
}
function _getConstantsHolder() private view returns (ConstantsHolder) {
return ConstantsHolder(contractManager.getConstantsHolder());
}
function _accept(uint delegationId) private {
_checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId);
State currentState = getState(delegationId);
if (currentState != State.PROPOSED) {
if (currentState == State.ACCEPTED ||
currentState == State.DELEGATED ||
currentState == State.UNDELEGATION_REQUESTED ||
currentState == State.COMPLETED)
{
revert("The delegation has been already accepted");
} else if (currentState == State.CANCELED) {
revert("The delegation has been cancelled by token holder");
} else if (currentState == State.REJECTED) {
revert("The delegation request is outdated");
}
}
require(currentState == State.PROPOSED, "Cannot set delegation state to accepted");
SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder);
_addToAllStatistics(delegationId);
uint amount = delegations[delegationId].amount;
_getTokenLaunchLocker().handleDelegationAdd(
delegations[delegationId].holder,
delegationId,
amount,
delegations[delegationId].started
);
uint effectiveAmount = amount.mul(
_getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)
);
_getBounty().handleDelegationAdd(
effectiveAmount,
delegations[delegationId].started
);
_sendSlashingSignals(slashingSignals);
emit DelegationAccepted(delegationId);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
DelegationPeriodManager.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
/**
* @title Delegation Period Manager
* @dev This contract handles all delegation offerings. Delegations are held for
* a specified period (months), and different durations can have different
* returns or `stakeMultiplier`. Currently, only delegation periods can be added.
*/
contract DelegationPeriodManager is Permissions {
mapping (uint => uint) public stakeMultipliers;
/**
* @dev Emitted when a new delegation period is specified.
*/
event DelegationPeriodWasSet(
uint length,
uint stakeMultiplier
);
/**
* @dev Allows the Owner to create a new available delegation period and
* stake multiplier in the network.
*
* Emits a {DelegationPeriodWasSet} event.
*/
function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external onlyOwner {
require(stakeMultipliers[monthsCount] == 0, "Delegation perios is already set");
stakeMultipliers[monthsCount] = stakeMultiplier;
emit DelegationPeriodWasSet(monthsCount, stakeMultiplier);
}
/**
* @dev Checks whether given delegation period is allowed.
*/
function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) {
return stakeMultipliers[monthsCount] != 0;
}
/**
* @dev Initial delegation period and multiplier settings.
*/
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
stakeMultipliers[2] = 100; // 2 months at 100
// stakeMultipliers[6] = 150; // 6 months at 150
// stakeMultipliers[12] = 200; // 12 months at 200
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
PartialDifferences.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../utils/MathUtils.sol";
import "../utils/FractionUtils.sol";
/**
* @title Partial Differences Library
* @dev This library contains functions to manage Partial Differences data
* structure. Partial Differences is an array of value differences over time.
*
* For example: assuming an array [3, 6, 3, 1, 2], partial differences can
* represent this array as [_, 3, -3, -2, 1].
*
* This data structure allows adding values on an open interval with O(1)
* complexity.
*
* For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3),
* instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows
* performing [_, 3, -3+5, -2, 1]. The original array can be restored by
* adding values from partial differences.
*/
library PartialDifferences {
using SafeMath for uint;
using MathUtils for uint;
struct Sequence {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
// month => value
mapping (uint => uint) value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
struct Value {
// month => diff
mapping (uint => uint) addDiff;
// month => diff
mapping (uint => uint) subtractDiff;
uint value;
uint firstUnprocessedMonth;
uint lastChangedMonth;
}
// functions for sequence
function addToSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
}
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
if (sequence.lastChangedMonth != month) {
sequence.lastChangedMonth = month;
}
}
function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.value[i] != nextValue) {
sequence.value[i] = nextValue;
}
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value[month];
}
function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) {
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value[month];
}
}
function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)];
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceSequence(
Sequence storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValueInSequence(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
sequence.value[month] = sequence.value[month]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
sequence.subtractDiff[i] = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
}
}
// functions for value
function addToValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.addDiff[month] = sequence.addDiff[month].add(diff);
} else {
sequence.value = sequence.value.add(diff);
}
}
function subtractFromValue(Value storage sequence, uint diff, uint month) internal {
require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past");
if (sequence.firstUnprocessedMonth == 0) {
sequence.firstUnprocessedMonth = month;
sequence.lastChangedMonth = month;
}
if (month > sequence.lastChangedMonth) {
sequence.lastChangedMonth = month;
}
if (month >= sequence.firstUnprocessedMonth) {
sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff);
} else {
sequence.value = sequence.value.boundedSub(diff);
}
}
function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]);
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value != value) {
sequence.value = value;
}
sequence.firstUnprocessedMonth = month.add(1);
}
return sequence.value;
}
function getValue(Value storage sequence, uint month) internal view returns (uint) {
require(
month.add(1) >= sequence.firstUnprocessedMonth,
"Cannot calculate value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return 0;
}
if (sequence.firstUnprocessedMonth <= month) {
uint value = sequence.value;
for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) {
value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]);
}
return value;
} else {
return sequence.value;
}
}
function getValues(Value storage sequence) internal view returns (uint[] memory values) {
if (sequence.firstUnprocessedMonth == 0) {
return values;
}
uint begin = sequence.firstUnprocessedMonth.sub(1);
uint end = sequence.lastChangedMonth.add(1);
if (end <= begin) {
end = begin.add(1);
}
values = new uint[](end.sub(begin));
values[0] = sequence.value;
for (uint i = 0; i.add(1) < values.length; ++i) {
uint month = sequence.firstUnprocessedMonth.add(i);
values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]);
}
}
function reduceValue(
Value storage sequence,
uint amount,
uint month)
internal returns (FractionUtils.Fraction memory)
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (sequence.firstUnprocessedMonth == 0) {
return FractionUtils.createFraction(0);
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return FractionUtils.createFraction(0);
}
uint _amount = amount;
if (value < amount) {
_amount = value;
}
FractionUtils.Fraction memory reducingCoefficient =
FractionUtils.createFraction(value.boundedSub(_amount), value);
reduceValueByCoefficient(sequence, reducingCoefficient, month);
return reducingCoefficient;
}
function reduceValueByCoefficient(
Value storage sequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month)
internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sequence,
reducingCoefficient,
month,
false);
}
function reduceValueByCoefficientAndUpdateSum(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month) internal
{
reduceValueByCoefficientAndUpdateSumIfNeeded(
sequence,
sumSequence,
reducingCoefficient,
month,
true);
}
function reduceValueByCoefficientAndUpdateSumIfNeeded(
Value storage sequence,
Value storage sumSequence,
FractionUtils.Fraction memory reducingCoefficient,
uint month,
bool hasSumSequence) internal
{
require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past");
if (hasSumSequence) {
require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past");
}
require(
reducingCoefficient.numerator <= reducingCoefficient.denominator,
"Increasing of values is not implemented");
if (sequence.firstUnprocessedMonth == 0) {
return;
}
uint value = getAndUpdateValue(sequence, month);
if (value.approximatelyEqual(0)) {
return;
}
uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator);
if (hasSumSequence) {
subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month);
}
sequence.value = newValue;
for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) {
uint newDiff = sequence.subtractDiff[i]
.mul(reducingCoefficient.numerator)
.div(reducingCoefficient.denominator);
if (hasSumSequence) {
sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i]
.boundedSub(sequence.subtractDiff[i].boundedSub(newDiff));
}
sequence.subtractDiff[i] = newDiff;
}
}
function clear(Value storage sequence) internal {
for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) {
if (sequence.addDiff[i] > 0) {
delete sequence.addDiff[i];
}
if (sequence.subtractDiff[i] > 0) {
delete sequence.subtractDiff[i];
}
}
if (sequence.value > 0) {
delete sequence.value;
}
if (sequence.firstUnprocessedMonth > 0) {
delete sequence.firstUnprocessedMonth;
}
if (sequence.lastChangedMonth > 0) {
delete sequence.lastChangedMonth;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Punisher.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "./ValidatorService.sol";
import "./DelegationController.sol";
/**
* @title Punisher
* @dev This contract handles all slashing and forgiving operations.
*/
contract Punisher is Permissions, ILocker {
// holder => tokens
mapping (address => uint) private _locked;
/**
* @dev Emitted upon slashing condition.
*/
event Slash(
uint validatorId,
uint amount
);
/**
* @dev Emitted upon forgive condition.
*/
event Forgive(
address wallet,
uint amount
);
/**
* @dev Allows SkaleDKG contract to execute slashing on a validator and
* validator's delegations by an `amount` of tokens.
*
* Emits a {Slash} event.
*
* Requirements:
*
* - Validator must exist.
*/
function slash(uint validatorId, uint amount) external allow("SkaleDKG") {
ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService"));
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(validatorService.validatorExists(validatorId), "Validator does not exist");
delegationController.confiscate(validatorId, amount);
emit Slash(validatorId, amount);
}
/**
* @dev Allows the Admin to forgive a slashing condition.
*
* Emits a {Forgive} event.
*
* Requirements:
*
* - All slashes must have been processed.
*/
function forgive(address holder, uint amount) external onlyAdmin {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated");
if (amount > _locked[holder]) {
delete _locked[holder];
} else {
_locked[holder] = _locked[holder].sub(amount);
}
emit Forgive(holder, amount);
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) {
return _getAndUpdateLockedAmount(wallet);
}
/**
* @dev Allows DelegationController contract to execute slashing of
* delegations.
*/
function handleSlash(address holder, uint amount) external allow("DelegationController") {
_locked[holder] = _locked[holder].add(amount);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function _getAndUpdateLockedAmount(address wallet) private returns (uint) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
delegationController.processAllSlashes(wallet);
return _locked[wallet];
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TimeHelpers.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol";
/**
* @title TimeHelpers
* @dev The contract performs time operations.
*
* These functions are used to calculate monthly and Proof of Use epochs.
*/
contract TimeHelpers {
using SafeMath for uint;
uint constant private _ZERO_YEAR = 2020;
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) {
timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays);
}
function addDays(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n);
}
function addMonths(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n);
}
function addYears(uint fromTimestamp, uint n) external pure returns (uint) {
return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n);
}
function getCurrentMonth() external view virtual returns (uint) {
return timestampToMonth(now);
}
function timestampToDay(uint timestamp) external view returns (uint) {
uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) /
BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY;
require(wholeDays >= zeroDay, "Timestamp is too far in the past");
return wholeDays - zeroDay;
}
function timestampToYear(uint timestamp) external view virtual returns (uint) {
uint year;
(year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
return year - _ZERO_YEAR;
}
function timestampToMonth(uint timestamp) public view virtual returns (uint) {
uint year;
uint month;
(year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp);
require(year >= _ZERO_YEAR, "Timestamp is too far in the past");
month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12));
require(month > 0, "Timestamp is too far in the past");
return month;
}
function monthToTimestamp(uint month) public view virtual returns (uint timestamp) {
uint year = _ZERO_YEAR;
uint _month = month;
year = year.add(_month.div(12));
_month = _month.mod(12);
_month = _month.add(1);
return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenLaunchLocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "../Permissions.sol";
import "../interfaces/delegation/ILocker.sol";
import "../ConstantsHolder.sol";
import "../utils/MathUtils.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
import "./PartialDifferences.sol";
/**
* @title TokenLaunchLocker
* @dev This contract manages lockers applied to the launch process.
*/
contract TokenLaunchLocker is Permissions, ILocker {
using MathUtils for uint;
using PartialDifferences for PartialDifferences.Value;
/**
* @dev Emitted when an `amount` is unlocked.
*/
event Unlocked(
address holder,
uint amount
);
/**
* @dev Emitted when an `amount` is locked.
*/
event Locked(
address holder,
uint amount
);
struct DelegatedAmountAndMonth {
uint delegated;
uint month;
}
// holder => tokens
mapping (address => uint) private _locked;
// holder => tokens
mapping (address => PartialDifferences.Value) private _delegatedAmount;
mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount;
// delegationId => tokens
mapping (uint => uint) private _delegationAmount;
/**
* @dev Allows TokenLaunchManager contract to lock an amount of tokens in a
* holder wallet.
*
* Emits a {Locked} event.
*/
function lock(address holder, uint amount) external allow("TokenLaunchManager") {
_locked[holder] = _locked[holder].add(amount);
emit Locked(holder, amount);
}
/**
* @dev Allows DelegationController contract to notify TokenLaunchLocker
* about new delegations.
*/
function handleDelegationAdd(
address holder, uint delegationId, uint amount, uint month)
external allow("DelegationController")
{
if (_locked[holder] > 0) {
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint fromLocked = amount;
uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth));
if (fromLocked > locked) {
fromLocked = locked;
}
if (fromLocked > 0) {
require(_delegationAmount[delegationId] == 0, "Delegation was already added");
_addToDelegatedAmount(holder, fromLocked, month);
_addToTotalDelegatedAmount(holder, fromLocked, month);
_delegationAmount[delegationId] = fromLocked;
}
}
}
/**
* @dev Allows DelegationController contract to notify TokenLaunchLocker
* about new undelegation requests.
*/
function handleDelegationRemoving(
address holder,
uint delegationId,
uint month)
external allow("DelegationController")
{
if (_delegationAmount[delegationId] > 0) {
if (_locked[holder] > 0) {
_removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month);
}
delete _delegationAmount[delegationId];
}
}
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address wallet) external override returns (uint) {
if (_locked[wallet] > 0) {
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController"));
TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
uint currentMonth = timeHelpers.getCurrentMonth();
if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) &&
timeHelpers.calculateProofOfUseLockEndTime(
_totalDelegatedAmount[wallet].month,
constantsHolder.proofOfUseLockUpPeriodDays()
) <= now) {
_unlock(wallet);
return 0;
} else {
uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth)
.add(delegationController.getLockedInPendingDelegations(wallet));
if (_locked[wallet] > lockedByDelegationController) {
return _locked[wallet].boundedSub(lockedByDelegationController);
} else {
return 0;
}
}
} else {
return 0;
}
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) {
return 0;
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
}
// private
/**
* @dev Returns and updates the current delegated amount.
*/
function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) {
return _delegatedAmount[holder].getAndUpdateValue(currentMonth);
}
/**
* @dev Adds a delegated amount to the given month.
*/
function _addToDelegatedAmount(address holder, uint amount, uint month) private {
_delegatedAmount[holder].addToValue(amount, month);
}
/**
* @dev Removes a delegated amount from the given month.
*/
function _removeFromDelegatedAmount(address holder, uint amount, uint month) private {
_delegatedAmount[holder].subtractFromValue(amount, month);
}
/**
* @dev Adds the amount to the total delegated for the given month.
*/
function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private {
require(
_totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month,
"Cannot add to total delegated in the past");
// do not update counter if it is big enough
// because it will override month value
if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) {
_totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount);
_totalDelegatedAmount[holder].month = month;
}
}
/**
* @dev Unlocks tokens.
*
* Emits an {Unlocked} event.
*/
function _unlock(address holder) private {
emit Unlocked(holder, _locked[holder]);
delete _locked[holder];
_deleteDelegatedAmount(holder);
_deleteTotalDelegatedAmount(holder);
}
/**
* @dev Deletes the delegated amount.
*/
function _deleteDelegatedAmount(address holder) private {
_delegatedAmount[holder].clear();
}
/**
* @dev Deletes the total delegated amount.
*/
function _deleteTotalDelegatedAmount(address holder) private {
delete _totalDelegatedAmount[holder].delegated;
delete _totalDelegatedAmount[holder].month;
}
/**
* @dev Checks whether total delegated satisfies Proof-of-Use.
*/
function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) {
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
return _totalDelegatedAmount[holder].delegated.mul(100) >=
_locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage());
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
TokenState.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "../interfaces/delegation/ILocker.sol";
import "../Permissions.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title Token State
* @dev This contract manages lockers to control token transferability.
*
* The SKALE Network has three types of locked tokens:
*
* - Tokens that are transferrable but are currently locked into delegation with
* a validator.
*
* - Tokens that are not transferable from one address to another, but may be
* delegated to a validator `getAndUpdateLockedAmount`. This lock enforces
* Proof-of-Use requirements.
*
* - Tokens that are neither transferable nor delegatable
* `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing.
*/
contract TokenState is Permissions, ILocker {
string[] private _lockers;
DelegationController private _delegationController;
/**
* @dev Emitted when a contract is added to the locker.
*/
event LockerWasAdded(
string locker
);
/**
* @dev Emitted when a contract is removed from the locker.
*/
event LockerWasRemoved(
string locker
);
/**
* @dev See {ILocker-getAndUpdateLockedAmount}.
*/
function getAndUpdateLockedAmount(address holder) external override returns (uint) {
if (address(_delegationController) == address(0)) {
_delegationController =
DelegationController(contractManager.getContract("DelegationController"));
}
uint locked = 0;
if (_delegationController.getDelegationsByHolderLength(holder) > 0) {
// the holder ever delegated
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
locked = locked.add(locker.getAndUpdateLockedAmount(holder));
}
}
return locked;
}
/**
* @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}.
*/
function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) {
uint forbidden = 0;
for (uint i = 0; i < _lockers.length; ++i) {
ILocker locker = ILocker(contractManager.getContract(_lockers[i]));
forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder));
}
return forbidden;
}
/**
* @dev Allows the Owner to remove a contract from the locker.
*
* Emits a {LockerWasRemoved} event.
*/
function removeLocker(string calldata locker) external onlyOwner {
uint index;
bytes32 hash = keccak256(abi.encodePacked(locker));
for (index = 0; index < _lockers.length; ++index) {
if (keccak256(abi.encodePacked(_lockers[index])) == hash) {
break;
}
}
if (index < _lockers.length) {
if (index < _lockers.length.sub(1)) {
_lockers[index] = _lockers[_lockers.length.sub(1)];
}
delete _lockers[_lockers.length.sub(1)];
_lockers.pop();
emit LockerWasRemoved(locker);
}
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
addLocker("DelegationController");
addLocker("Punisher");
addLocker("TokenLaunchLocker");
}
/**
* @dev Allows the Owner to add a contract to the Locker.
*
* Emits a {LockerWasAdded} event.
*/
function addLocker(string memory locker) public onlyOwner {
_lockers.push(locker);
emit LockerWasAdded(locker);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ValidatorService.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
@author Artem Payvin
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "./DelegationController.sol";
import "./TimeHelpers.sol";
/**
* @title ValidatorService
* @dev This contract handles all validator operations including registration,
* node management, validator-specific delegation parameters, and more.
*
* TIP: For more information see our main instructions
* https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ].
*
* Validators register an address, and use this address to accept delegations and
* register nodes.
*/
contract ValidatorService is Permissions {
using ECDSA for bytes32;
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
mapping (uint => Validator) public validators;
mapping (uint => bool) private _trustedValidators;
uint[] public trustedValidatorsList;
// address => validatorId
mapping (address => uint) private _validatorAddressToId;
// address => validatorId
mapping (address => uint) private _nodeAddressToValidatorId;
// validatorId => nodeAddress[]
mapping (uint => address[]) private _nodeAddresses;
uint public numberOfValidators;
bool public useWhitelist;
modifier checkValidatorExists(uint validatorId) {
require(validatorExists(validatorId), "Validator with such ID does not exist");
_;
}
/**
* @dev Creates a new validator ID that includes a validator name, description,
* commission or fee rate, and a minimum delegation amount accepted by the validator.
*
* Emits a {ValidatorRegistered} event.
*
* Requirements:
*
* - Sender must not already have registered a validator ID.
* - Fee rate must be between 0 - 1000‰. Note: in per mille.
*/
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId)
{
require(!validatorAddressExists(msg.sender), "Validator with such address already exists");
require(feeRate <= 1000, "Fee rate of validator should be lower than 100%");
validatorId = ++numberOfValidators;
validators[validatorId] = Validator(
name,
msg.sender,
address(0),
description,
feeRate,
now,
minimumDelegationAmount,
true
);
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorRegistered(validatorId);
}
/**
* @dev Allows Admin to enable a validator by adding their ID to the
* trusted list.
*
* Emits a {ValidatorWasEnabled} event.
*
* Requirements:
*
* - Validator must not already be enabled.
*/
function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(!_trustedValidators[validatorId], "Validator is already enabled");
_trustedValidators[validatorId] = true;
trustedValidatorsList.push(validatorId);
emit ValidatorWasEnabled(validatorId);
}
/**
* @dev Allows Admin to disable a validator by removing their ID from
* the trusted list.
*
* Emits a {ValidatorWasDisabled} event.
*
* Requirements:
*
* - Validator must not already be disabled.
*/
function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyAdmin {
require(_trustedValidators[validatorId], "Validator is already disabled");
_trustedValidators[validatorId] = false;
uint position = _find(trustedValidatorsList, validatorId);
if (position < trustedValidatorsList.length) {
trustedValidatorsList[position] =
trustedValidatorsList[trustedValidatorsList.length.sub(1)];
}
trustedValidatorsList.pop();
emit ValidatorWasDisabled(validatorId);
}
/**
* @dev Owner can disable the trusted validator list. Once turned off, the
* trusted list cannot be re-enabled.
*/
function disableWhitelist() external onlyOwner {
useWhitelist = false;
}
/**
* @dev Allows `msg.sender` to request a new address.
*
* Requirements:
*
* - `msg.sender` must already be a validator.
* - New address must not be null.
* - New address must not be already registered as a validator.
*/
function requestForNewAddress(address newValidatorAddress) external {
require(newValidatorAddress != address(0), "New address cannot be null");
require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered");
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].requestedAddress = newValidatorAddress;
}
/**
* @dev Allows msg.sender to confirm an address change.
*
* Emits a {ValidatorAddressChanged} event.
*
* Requirements:
*
* - Must be owner of new address.
*/
function confirmNewAddress(uint validatorId)
external
checkValidatorExists(validatorId)
{
require(
getValidator(validatorId).requestedAddress == msg.sender,
"The validator address cannot be changed because it is not the actual owner"
);
delete validators[validatorId].requestedAddress;
_setValidatorAddress(validatorId, msg.sender);
emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress);
}
/**
* @dev Links a node address to validator ID. Validator must present
* the node signature of the validator ID.
*
* Requirements:
*
* - Signature must be valid.
* - Address must not be assigned to a validator.
*/
function linkNodeAddress(address nodeAddress, bytes calldata sig) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(
keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress,
"Signature is not pass"
);
require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator");
_addNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasAdded(validatorId, nodeAddress);
}
/**
* @dev Unlinks a node address from a validator.
*
* Emits a {NodeAddressWasRemoved} event.
*/
function unlinkNodeAddress(address nodeAddress) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
this.removeNodeAddress(validatorId, nodeAddress);
emit NodeAddressWasRemoved(validatorId, nodeAddress);
}
/**
* @dev Allows a validator to set a minimum delegation amount.
*/
function setValidatorMDA(uint minimumDelegationAmount) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].minimumDelegationAmount = minimumDelegationAmount;
}
/**
* @dev Allows a validator to set a new validator name.
*/
function setValidatorName(string calldata newName) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].name = newName;
}
/**
* @dev Allows a validator to set a new validator description.
*/
function setValidatorDescription(string calldata newDescription) external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
validators[validatorId].description = newDescription;
}
/**
* @dev Allows a validator to start accepting new delegation requests.
*
* Requirements:
*
* - Must not have already enabled accepting new requests.
*/
function startAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled");
validators[validatorId].acceptNewRequests = true;
}
/**
* @dev Allows a validator to stop accepting new delegation requests.
*
* Requirements:
*
* - Must not have already stopped accepting new requests.
*/
function stopAcceptingNewRequests() external {
// check Validator Exist inside getValidatorId
uint validatorId = getValidatorId(msg.sender);
require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled");
validators[validatorId].acceptNewRequests = false;
}
function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") {
require(_nodeAddressToValidatorId[nodeAddress] == validatorId,
"Validator does not have permissions to unlink node");
delete _nodeAddressToValidatorId[nodeAddress];
for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) {
if (_nodeAddresses[validatorId][i] == nodeAddress) {
if (i + 1 < _nodeAddresses[validatorId].length) {
_nodeAddresses[validatorId][i] =
_nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
}
delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)];
_nodeAddresses[validatorId].pop();
break;
}
}
}
/**
* @dev Returns the amount of validator bond (self-delegation).
*/
function getAndUpdateBondAmount(uint validatorId)
external
returns (uint)
{
DelegationController delegationController = DelegationController(
contractManager.getContract("DelegationController")
);
return delegationController.getAndUpdateDelegatedByHolderToValidatorNow(
getValidator(validatorId).validatorAddress,
validatorId
);
}
/**
* @dev Returns node addresses linked to the msg.sender.
*/
function getMyNodesAddresses() external view returns (address[] memory) {
return getNodeAddresses(getValidatorId(msg.sender));
}
/**
* @dev Returns the list of trusted validators.
*/
function getTrustedValidators() external view returns (uint[] memory) {
return trustedValidatorsList;
}
/**
* @dev Checks whether the validator ID is linked to the validator address.
*/
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool)
{
return getValidatorId(validatorAddress) == validatorId ? true : false;
}
/**
* @dev Returns the validator ID linked to a node address.
*
* Requirements:
*
* - Node address must be linked to a validator.
*/
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) {
validatorId = _nodeAddressToValidatorId[nodeAddress];
require(validatorId != 0, "Node address is not assigned to a validator");
}
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view {
require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request");
require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests");
require(
validators[validatorId].minimumDelegationAmount <= amount,
"Amount does not meet the validator's minimum delegation amount"
);
}
function initialize(address contractManagerAddress) public override initializer {
Permissions.initialize(contractManagerAddress);
useWhitelist = true;
}
/**
* @dev Returns a validator's node addresses.
*/
function getNodeAddresses(uint validatorId) public view returns (address[] memory) {
return _nodeAddresses[validatorId];
}
/**
* @dev Checks whether validator ID exists.
*/
function validatorExists(uint validatorId) public view returns (bool) {
return validatorId <= numberOfValidators && validatorId != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function validatorAddressExists(address validatorAddress) public view returns (bool) {
return _validatorAddressToId[validatorAddress] != 0;
}
/**
* @dev Checks whether validator address exists.
*/
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
/**
* @dev Returns the Validator struct.
*/
function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) {
return validators[validatorId];
}
/**
* @dev Returns the validator ID for the given validator address.
*/
function getValidatorId(address validatorAddress) public view returns (uint) {
checkIfValidatorAddressExists(validatorAddress);
return _validatorAddressToId[validatorAddress];
}
/**
* @dev Checks whether the validator is currently accepting new delegation requests.
*/
function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return validators[validatorId].acceptNewRequests;
}
function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) {
return _trustedValidators[validatorId] || !useWhitelist;
}
// private
/**
* @dev Links a validator address to a validator ID.
*
* Requirements:
*
* - Address is not already in use by another validator.
*/
function _setValidatorAddress(uint validatorId, address validatorAddress) private {
if (_validatorAddressToId[validatorAddress] == validatorId) {
return;
}
require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator");
address oldAddress = validators[validatorId].validatorAddress;
delete _validatorAddressToId[oldAddress];
_nodeAddressToValidatorId[validatorAddress] = validatorId;
validators[validatorId].validatorAddress = validatorAddress;
_validatorAddressToId[validatorAddress] = validatorId;
}
/**
* @dev Links a node address to a validator ID.
*
* Requirements:
*
* - Node address must not be already linked to a validator.
*/
function _addNodeAddress(uint validatorId, address nodeAddress) private {
if (_nodeAddressToValidatorId[nodeAddress] == validatorId) {
return;
}
require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address");
_nodeAddressToValidatorId[nodeAddress] = validatorId;
_nodeAddresses[validatorId].push(nodeAddress);
}
function _find(uint[] memory array, uint index) private pure returns (uint) {
uint i;
for (i = 0; i < array.length; i++) {
if (array[i] == index) {
return i;
}
}
return array.length;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ISkaleDKG.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Artem Payvin
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface to {SkaleDKG}.
*/
interface ISkaleDKG {
/**
* @dev See {SkaleDKG-openChannel}.
*/
function openChannel(bytes32 schainId) external;
/**
* @dev See {SkaleDKG-deleteChannel}.
*/
function deleteChannel(bytes32 schainId) external;
/**
* @dev See {SkaleDKG-isLastDKGSuccessful}.
*/
function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool);
/**
* @dev See {SkaleDKG-isChannelOpened}.
*/
function isChannelOpened(bytes32 schainId) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ILocker.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
/**
* @dev Interface of the Locker functions.
*/
interface ILocker {
/**
* @dev Returns and updates the total amount of locked tokens of a given
* `holder`.
*/
function getAndUpdateLockedAmount(address wallet) external returns (uint);
/**
* @dev Returns and updates the total non-transferrable and un-delegatable
* amount of a given `holder`.
*/
function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint);
}
pragma solidity ^0.6.0;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
uint year;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
uint year;
uint month;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
uint year;
uint month;
uint day;
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
uint fromYear;
uint fromMonth;
uint fromDay;
uint toYear;
uint toMonth;
uint toDay;
(fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
/*
Modifications Copyright (C) 2018 SKALE Labs
ec.sol by @jbaylina under GPL-3.0 License
*/
/** @file ECDH.sol
* @author Jordi Baylina (@jbaylina)
* @date 2016
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title ECDH
* @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to
* support the DKG process.
*/
contract ECDH {
using SafeMath for uint256;
uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
uint256 constant private _A = 0;
function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) {
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
_GX,
_GY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function deriveKey(
uint256 privKey,
uint256 pubX,
uint256 pubY
)
external
pure
returns (uint256 qx, uint256 qy)
{
uint256 x;
uint256 y;
uint256 z;
(x, y, z) = ecMul(
privKey,
pubX,
pubY,
1
);
z = inverse(z);
qx = mulmod(x, z, _N);
qy = mulmod(y, z, _N);
}
function jAdd(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N));
}
function jSub(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N));
}
function jMul(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N));
}
function jDiv(
uint256 x1,
uint256 z1,
uint256 x2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 z3)
{
(x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N));
}
function inverse(uint256 a) public pure returns (uint256 invA) {
require(a > 0 && a < _N, "Input is incorrect");
uint256 t = 0;
uint256 newT = 1;
uint256 r = _N;
uint256 newR = a;
uint256 q;
while (newR != 0) {
q = r.div(newR);
(t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N));
(r, newR) = (newR, r % newR);
}
return t;
}
function ecAdd(
uint256 x1,
uint256 y1,
uint256 z1,
uint256 x2,
uint256 y2,
uint256 z2
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 ln;
uint256 lz;
uint256 da;
uint256 db;
// we use (0 0 1) as zero point, z always equal 1
if ((x1 == 0) && (y1 == 0)) {
return (x2, y2, z2);
}
// we use (0 0 1) as zero point, z always equal 1
if ((x2 == 0) && (y2 == 0)) {
return (x1, y1, z1);
}
if ((x1 == x2) && (y1 == y2)) {
(ln, lz) = jMul(x1, z1, x1, z1);
(ln, lz) = jMul(ln,lz,3,1);
(ln, lz) = jAdd(ln,lz,_A,1);
(da, db) = jMul(y1,z1,2,1);
} else {
(ln, lz) = jSub(y2,z2,y1,z1);
(da, db) = jSub(x2,z2,x1,z1);
}
(ln, lz) = jDiv(ln,lz,da,db);
(x3, da) = jMul(ln,lz,ln,lz);
(x3, da) = jSub(x3,da,x1,z1);
(x3, da) = jSub(x3,da,x2,z2);
(y3, db) = jSub(x1,z1,x3,da);
(y3, db) = jMul(y3,db,ln,lz);
(y3, db) = jSub(y3,db,y1,z1);
if (da != db) {
x3 = mulmod(x3, db, _N);
y3 = mulmod(y3, da, _N);
z3 = mulmod(da, db, _N);
} else {
z3 = da;
}
}
function ecDouble(
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
(x3, y3, z3) = ecAdd(
x1,
y1,
z1,
x1,
y1,
z1
);
}
function ecMul(
uint256 d,
uint256 x1,
uint256 y1,
uint256 z1
)
public
pure
returns (uint256 x3, uint256 y3, uint256 z3)
{
uint256 remaining = d;
uint256 px = x1;
uint256 py = y1;
uint256 pz = z1;
uint256 acx = 0;
uint256 acy = 0;
uint256 acz = 1;
if (d == 0) {
return (0, 0, 1);
}
while (remaining != 0) {
if ((remaining & 1) != 0) {
(acx, acy, acz) = ecAdd(
acx,
acy,
acz,
px,
py,
pz
);
}
remaining = remaining.div(2);
(px, py, pz) = ecDouble(px, py, pz);
}
(x3, y3, z3) = (acx, acy, acz);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FieldOperations.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./Precompiled.sol";
library Fp2Operations {
using SafeMath for uint;
struct Fp2Point {
uint a;
uint b;
}
uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) });
}
function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) {
return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) });
}
function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure
returns (Fp2Point memory difference)
{
uint p = P;
if (diminished.a >= subtracted.a) {
difference.a = addmod(diminished.a, p - subtracted.a, p);
} else {
difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p);
}
if (diminished.b >= subtracted.b) {
difference.b = addmod(diminished.b, p - subtracted.b, p);
} else {
difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p);
}
}
function mulFp2(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (Fp2Point memory result)
{
uint p = P;
Fp2Point memory point = Fp2Point({
a: mulmod(value1.a, value2.a, p),
b: mulmod(value1.b, value2.b, p)});
result.a = addmod(
point.a,
mulmod(p - 1, point.b, p),
p);
result.b = addmod(
mulmod(
addmod(value1.a, value1.b, p),
addmod(value2.a, value2.b, p),
p),
p - addmod(point.a, point.b, p),
p);
}
function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) {
uint p = P;
uint ab = mulmod(value.a, value.b, p);
uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p);
return Fp2Point({ a: mult, b: addmod(ab, ab, p) });
}
function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) {
uint p = P;
uint t0 = mulmod(value.a, value.a, p);
uint t1 = mulmod(value.b, value.b, p);
uint t2 = mulmod(p - 1, t1, p);
if (t0 >= t2) {
t2 = addmod(t0, p - t2, p);
} else {
t2 = (p - addmod(t2, p - t0, p)).mod(p);
}
uint t3 = Precompiled.bigModExp(t2, p - 2, p);
result.a = mulmod(value.a, t3, p);
result.b = (p - mulmod(value.b, t3, p)).mod(p);
}
function isEqual(
Fp2Point memory value1,
Fp2Point memory value2
)
internal
pure
returns (bool)
{
return value1.a == value2.a && value1.b == value2.b;
}
}
library G1Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 1,
b: 2
});
}
function isG1Point(uint x, uint y) internal pure returns (bool) {
uint p = Fp2Operations.P;
return mulmod(y, y, p) ==
addmod(mulmod(mulmod(x, x, p), x, p), 3, p);
}
function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return isG1Point(point.a, point.b);
}
function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) {
return point.a < Fp2Operations.P && point.b < Fp2Operations.P;
}
function negate(uint y) internal pure returns (uint) {
return Fp2Operations.P.sub(y).mod(Fp2Operations.P);
}
}
library G2Operations {
using SafeMath for uint;
using Fp2Operations for Fp2Operations.Fp2Point;
struct G2Point {
Fp2Operations.Fp2Point x;
Fp2Operations.Fp2Point y;
}
function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return Fp2Operations.Fp2Point({
a: 19485874751759354771024239261021720505790618469301721065564631296452457478373,
b: 266929791119991161246907387137283842545076965332900288569378510910307636690
});
}
function getG2Generator() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 10857046999023057135944570762232829481370756359578518086990519993285655852781,
b: 11559732032986387107991004021392285783925812861821192530917403151452391805634
}),
y: Fp2Operations.Fp2Point({
a: 8495653923123431417604973247489272438418190587263600148770280649306958101930,
b: 4082367875863433681332203403145435568316851327593401208105741076214120093531
})
});
}
function getG2Zero() internal pure returns (G2Point memory) {
// Current solidity version does not support Constants of non-value type
// so we implemented this function
return G2Point({
x: Fp2Operations.Fp2Point({
a: 0,
b: 0
}),
y: Fp2Operations.Fp2Point({
a: 1,
b: 0
})
});
}
function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) {
if (isG2ZeroPoint(x, y)) {
return true;
}
Fp2Operations.Fp2Point memory squaredY = y.squaredFp2();
Fp2Operations.Fp2Point memory res = squaredY.minusFp2(
x.squaredFp2().mulFp2(x)
).minusFp2(getTWISTB());
return res.a == 0 && res.b == 0;
}
function isG2(G2Point memory value) internal pure returns (bool) {
return isG2Point(value.x, value.y);
}
function isG2ZeroPoint(
Fp2Operations.Fp2Point memory x,
Fp2Operations.Fp2Point memory y
)
internal
pure
returns (bool)
{
return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0;
}
function isG2Zero(G2Point memory value) internal pure returns (bool) {
return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0;
// return isG2ZeroPoint(value.x, value.y);
}
function addG2(
G2Point memory value1,
G2Point memory value2
)
internal
view
returns (G2Point memory sum)
{
if (isG2Zero(value1)) {
return value2;
}
if (isG2Zero(value2)) {
return value1;
}
if (isEqual(value1, value2)) {
return doubleG2(value1);
}
Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2());
sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x));
sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x)));
uint p = Fp2Operations.P;
sum.y.a = (p - sum.y.a).mod(p);
sum.y.b = (p - sum.y.b).mod(p);
}
function isEqual(
G2Point memory value1,
G2Point memory value2
)
internal
pure
returns (bool)
{
return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y);
}
function doubleG2(G2Point memory value)
internal
view
returns (G2Point memory result)
{
if (isG2Zero(value)) {
return value;
} else {
Fp2Operations.Fp2Point memory s =
value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2());
result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x));
result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x)));
uint p = Fp2Operations.P;
result.y.a = (p - result.y.a).mod(p);
result.y.b = (p - result.y.b).mod(p);
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
FractionUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library FractionUtils {
using SafeMath for uint;
struct Fraction {
uint numerator;
uint denominator;
}
function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) {
require(denominator > 0, "Division by zero");
Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator});
reduceFraction(fraction);
return fraction;
}
function createFraction(uint value) internal pure returns (Fraction memory) {
return createFraction(value, 1);
}
function reduceFraction(Fraction memory fraction) internal pure {
uint _gcd = gcd(fraction.numerator, fraction.denominator);
fraction.numerator = fraction.numerator.div(_gcd);
fraction.denominator = fraction.denominator.div(_gcd);
}
// numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1
function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) {
return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator));
}
function gcd(uint a, uint b) internal pure returns (uint) {
uint _a = a;
uint _b = b;
if (_b > _a) {
(_a, _b) = swap(_a, _b);
}
while (_b > 0) {
_a = _a.mod(_b);
(_a, _b) = swap (_a, _b);
}
return _a;
}
function swap(uint a, uint b) internal pure returns (uint, uint) {
return (b, a);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library MathUtils {
uint constant private _EPS = 1e6;
event UnderflowError(
uint a,
uint b
);
function boundedSub(uint256 a, uint256 b) internal returns (uint256) {
if (a >= b) {
return a - b;
} else {
emit UnderflowError(a, b);
return 0;
}
}
function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return 0;
}
}
function muchGreater(uint256 a, uint256 b) internal pure returns (bool) {
assert(uint(-1) - _EPS > b);
return a > b + _EPS;
}
function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (a > b) {
return a - b < _EPS;
} else {
return b - a < _EPS;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Precompiled.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
library Precompiled {
function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) {
uint[6] memory inputToBigModExp;
inputToBigModExp[0] = 32;
inputToBigModExp[1] = 32;
inputToBigModExp[2] = 32;
inputToBigModExp[3] = base;
inputToBigModExp[4] = power;
inputToBigModExp[5] = modulus;
uint[1] memory out;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20)
}
require(success, "BigModExp failed");
return out[0];
}
function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) {
uint[3] memory inputToMul;
uint[2] memory output;
inputToMul[0] = x;
inputToMul[1] = y;
inputToMul[2] = k;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40)
}
require(success, "Multiplication failed");
return (output[0], output[1]);
}
function bn256Pairing(
uint x1,
uint y1,
uint a1,
uint b1,
uint c1,
uint d1,
uint x2,
uint y2,
uint a2,
uint b2,
uint c2,
uint d2)
internal view returns (bool)
{
bool success;
uint[12] memory inputToPairing;
inputToPairing[0] = x1;
inputToPairing[1] = y1;
inputToPairing[2] = a1;
inputToPairing[3] = b1;
inputToPairing[4] = c1;
inputToPairing[5] = d1;
inputToPairing[6] = x2;
inputToPairing[7] = y2;
inputToPairing[8] = a2;
inputToPairing[9] = b2;
inputToPairing[10] = c2;
inputToPairing[11] = d2;
uint[1] memory out;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20)
}
require(success, "Pairing check failed");
return out[0] != 0;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
StringUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Vadim Yavorsky
SKALE Manager is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SKALE Manager is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.6.10;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
library StringUtils {
using SafeMath for uint;
function strConcat(string memory a, string memory b) internal pure returns (string memory) {
bytes memory _ba = bytes(a);
bytes memory _bb = bytes(b);
string memory ab = new string(_ba.length.add(_bb.length));
bytes memory strBytes = bytes(ab);
uint k = 0;
uint i = 0;
for (i = 0; i < _ba.length; i++) {
strBytes[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
strBytes[k++] = _bb[i];
}
return string(strBytes);
}
}
pragma solidity ^0.6.0;
import "../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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_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());
}
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../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.
*/
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
revert("ECDSA: invalid signature 's' value");
}
if (v != 27 && v != 28) {
revert("ECDSA: invalid signature 'v' value");
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity ^0.6.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.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));
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @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 Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
|
* @dev Checks whether validator address exists./
|
function checkIfValidatorAddressExists(address validatorAddress) public view {
require(validatorAddressExists(validatorAddress), "Validator address does not exist");
}
| 401,488 |
[
1,
4081,
2856,
4213,
1758,
1704,
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,
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,
445,
19130,
5126,
1887,
4002,
12,
2867,
4213,
1887,
13,
1071,
1476,
288,
203,
3639,
2583,
12,
7357,
1887,
4002,
12,
7357,
1887,
3631,
315,
5126,
1758,
1552,
486,
1005,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.17;
import "./SafeMath.sol";
import "./Iupgradable.sol";
import "./RANCEToken.sol";
import "./IPooledStaking.sol";
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract IERC1132 {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
/**
* @dev Records data of all the tokens Locked
*/
event Locked(
address indexed _of,
bytes32 indexed _reason,
uint256 _amount,
uint256 _validity
);
/**
* @dev Records data of all the tokens unlocked
*/
event Unlocked(
address indexed _of,
bytes32 indexed _reason,
uint256 _amount
);
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lock(bytes32 _reason, uint256 _amount, uint256 _time)
public returns (bool);
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public view returns (uint256 amount);
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public view returns (uint256 amount);
/**
* @dev Returns total tokens held by an address (locked + transferable)
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of)
public view returns (uint256 amount);
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLock(bytes32 _reason, uint256 _time)
public returns (bool);
/**
* @dev Increase number of tokens locked for a specified reason
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(bytes32 _reason, uint256 _amount)
public returns (bool);
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public view returns (uint256 amount);
/**
* @dev Unlocks the unlockable tokens of a specified address
* @param _of Address of user, claiming back unlockable tokens
*/
function unlock(address _of)
public returns (uint256 unlockableTokens);
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public view returns (uint256 unlockableTokens);
}
contract TokenController is IERC1132, Iupgradable {
using SafeMath for uint256;
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
RANCEToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime = uint(30).mul(1 days);
bytes32 private constant CLA = bytes32("CLA");
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = RANCEToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress('PS'));
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) {
require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address");
require(token.operatorTransfer(_from, _value), "Operator transfer failed");
require(token.transfer(_to, _value), "Internal transfer failed");
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
require(minCALockTime <= _time,"Should lock for minimum time");
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(msg.sender, _reason, _amount, _time);
return true;
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _time Lock extension time in seconds
*/
function extendLock(bytes32 _reason, uint256 _time)
public
checkPause
returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
_extendLock(msg.sender, _reason, _time);
return true;
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _reason The reason to lock tokens, currently restricted to CLA
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(bytes32 _reason, uint256 _amount)
public
checkPause
returns (bool)
{
require(_reason == CLA,"Restricted to reason CLA");
require(_tokensLocked(msg.sender, _reason) > 0);
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount);
emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity);
return true;
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom (address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the unlockable tokens against CLA of a specified address
* @param _of Address of user, claiming back unlockable tokens against CLA
*/
function unlock(address _of)
public
checkPause
returns (uint256 unlockableTokens)
{
unlockableTokens = _tokensUnlockable(_of, CLA);
if (unlockableTokens > 0) {
locked[_of][CLA].claimed = true;
emit Unlocked(_of, CLA, unlockableTokens);
require(token.transfer(_of, unlockableTokens));
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "MNCLT") {
minCALockTime = val.mul(1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason)
public
view
returns (uint256 validity)
{
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total locked tokens at time
* Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility
* for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment.
* Does not take into account pending burns.
*
* @param _of member whose locked tokens are to be calculate
* @param _time timestamp when the tokens should be locked
*/
function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0);
require(_amount != 0);
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
require(token.operatorTransfer(_of, _amount));
uint256 validUntil = now.add(_time); //solhint-disable-line
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0);
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0);
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount);
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
if (locked[_of][_reason].amount == 0) {
_removeReason(_of, _reason);
}
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount);
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
if (locked[_of][_reason].amount == 0) {
_removeReason(_of, _reason);
}
require(token.transfer(_of, _amount));
emit Unlocked(_of, _reason, _amount);
}
function _removeReason(address _of, bytes32 _reason) internal {
uint len = lockReason[_of].length;
for (uint i = 0; i < len; i++) {
if (lockReason[_of][i] == _reason) {
lockReason[_of][i] = lockReason[_of][len.sub(1)];
lockReason[_of].pop();
break;
}
}
}
}
|
* @dev Just for interface/
|
function lock(bytes32 _reason, uint256 _amount, uint256 _time)
public returns (bool);
function tokensLocked(address _of, bytes32 _reason)
public view returns (uint256 amount);
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public view returns (uint256 amount);
function totalBalanceOf(address _of)
public view returns (uint256 amount);
function extendLock(bytes32 _reason, uint256 _time)
public returns (bool);
function increaseLockAmount(bytes32 _reason, uint256 _amount)
public returns (bool);
function tokensUnlockable(address _of, bytes32 _reason)
public view returns (uint256 amount);
function unlock(address _of)
public returns (uint256 unlockableTokens);
function getUnlockableTokens(address _of)
public view returns (uint256 unlockableTokens);
}
function changeDependentContractAddress() public {
token = RANCEToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress('PS'));
}
| 12,663,033 |
[
1,
19642,
364,
1560,
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,
565,
445,
2176,
12,
3890,
1578,
389,
10579,
16,
2254,
5034,
389,
8949,
16,
2254,
5034,
389,
957,
13,
203,
3639,
1071,
1135,
261,
6430,
1769,
203,
21281,
565,
445,
2430,
8966,
12,
2867,
389,
792,
16,
1731,
1578,
389,
10579,
13,
203,
3639,
1071,
1476,
1135,
261,
11890,
5034,
3844,
1769,
203,
377,
203,
565,
445,
2430,
8966,
861,
950,
12,
2867,
389,
792,
16,
1731,
1578,
389,
10579,
16,
2254,
5034,
389,
957,
13,
203,
3639,
1071,
1476,
1135,
261,
11890,
5034,
3844,
1769,
203,
377,
203,
565,
445,
2078,
13937,
951,
12,
2867,
389,
792,
13,
203,
3639,
1071,
1476,
1135,
261,
11890,
5034,
3844,
1769,
203,
377,
203,
565,
445,
2133,
2531,
12,
3890,
1578,
389,
10579,
16,
2254,
5034,
389,
957,
13,
203,
3639,
1071,
1135,
261,
6430,
1769,
203,
377,
203,
565,
445,
10929,
2531,
6275,
12,
3890,
1578,
389,
10579,
16,
2254,
5034,
389,
8949,
13,
203,
3639,
1071,
1135,
261,
6430,
1769,
203,
203,
565,
445,
2430,
7087,
429,
12,
2867,
389,
792,
16,
1731,
1578,
389,
10579,
13,
203,
3639,
1071,
1476,
1135,
261,
11890,
5034,
3844,
1769,
203,
7010,
565,
445,
7186,
12,
2867,
389,
792,
13,
203,
3639,
1071,
1135,
261,
11890,
5034,
7186,
429,
5157,
1769,
203,
203,
565,
445,
336,
7087,
429,
5157,
12,
2867,
389,
792,
13,
203,
3639,
1071,
1476,
1135,
261,
11890,
5034,
7186,
429,
5157,
1769,
203,
203,
97,
203,
565,
445,
2549,
18571,
8924,
1887,
1435,
1071,
288,
203,
3639,
1147,
273,
534,
4722,
1345,
12,
2
] |
// File: ERC20.sol
pragma solidity ^0.5.10;
/// @title ERC20 interface is a subset of the ERC20 specification.
/// @notice see https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
function allowance(address _owner, address _spender) external view returns (uint256);
function approve(address _spender, uint256 _value) external returns (bool);
function balanceOf(address _who) external view returns (uint256);
function totalSupply() external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
// File: SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: Address.sol
pragma solidity ^0.5.0;
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* > It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
// File: SafeERC20.sol
/**
* The MIT License (MIT)
*
* Copyright (c) 2016-2019 zOS Global Limited
*
* 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.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(ERC20 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(ERC20 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(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(ERC20 token, bytes memory data) internal {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: transferrable.sol
/**
* Transferrable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title SafeTransfer, allowing contract to withdraw tokens accidentally sent to itself
contract Transferrable {
using SafeERC20 for ERC20;
/// @dev This function is used to move tokens sent accidentally to this contract method.
/// @dev The owner can chose the new destination address
/// @param _to is the recipient's address.
/// @param _asset is the address of an ERC20 token or 0x0 for ether.
/// @param _amount is the amount to be transferred in base units.
function _safeTransfer(address payable _to, address _asset, uint _amount) internal {
// address(0) is used to denote ETH
if (_asset == address(0)) {
_to.transfer(_amount);
} else {
ERC20(_asset).safeTransfer(_to, _amount);
}
}
}
// File: balanceable.sol
/**
* Balanceable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Balanceable - This is a contract used to get a balance
contract Balanceable {
/// @dev This function is used to get a balance
/// @param _address of which balance we are trying to ascertain
/// @param _asset is the address of an ERC20 token or 0x0 for ether.
/// @return balance associated with an address, for any token, in the wei equivalent
function _balance(address _address, address _asset) internal view returns (uint) {
if (_asset != address(0)) {
return ERC20(_asset).balanceOf(_address);
} else {
return _address.balance;
}
}
}
// File: burner.sol
/**
* IBurner - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
// The BurnerToken interface is the interface to a token contract which
// provides the total burnable supply for the TokenHolder contract.
interface IBurner {
function currentSupply() external view returns (uint);
}
// File: ownable.sol
/**
* Ownable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Ownable has an owner address and provides basic authorization control functions.
/// This contract is modified version of the MIT OpenZepplin Ownable contract
/// This contract allows for the transferOwnership operation to be made impossible
/// https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol
contract Ownable {
event TransferredOwnership(address _from, address _to);
event LockedOwnership(address _locked);
address payable private _owner;
bool private _isTransferable;
/// @notice Constructor sets the original owner of the contract and whether or not it is one time transferable.
constructor(address payable _account_, bool _transferable_) internal {
_owner = _account_;
_isTransferable = _transferable_;
// Emit the LockedOwnership event if no longer transferable.
if (!_isTransferable) {
emit LockedOwnership(_account_);
}
emit TransferredOwnership(address(0), _account_);
}
/// @notice Reverts if called by any account other than the owner.
modifier onlyOwner() {
require(_isOwner(msg.sender), "sender is not an owner");
_;
}
/// @notice Allows the current owner to transfer control of the contract to a new address.
/// @param _account address to transfer ownership to.
/// @param _transferable indicates whether to keep the ownership transferable.
function transferOwnership(address payable _account, bool _transferable) external onlyOwner {
// Require that the ownership is transferable.
require(_isTransferable, "ownership is not transferable");
// Require that the new owner is not the zero address.
require(_account != address(0), "owner cannot be set to zero address");
// Set the transferable flag to the value _transferable passed in.
_isTransferable = _transferable;
// Emit the LockedOwnership event if no longer transferable.
if (!_transferable) {
emit LockedOwnership(_account);
}
// Emit the ownership transfer event.
emit TransferredOwnership(_owner, _account);
// Set the owner to the provided address.
_owner = _account;
}
/// @notice check if the ownership is transferable.
/// @return true if the ownership is transferable.
function isTransferable() external view returns (bool) {
return _isTransferable;
}
/// @notice Allows the current owner to relinquish control of the contract.
/// @dev Renouncing to ownership will leave the contract without an owner and unusable.
/// @dev It will not be possible to call the functions with the `onlyOwner` modifier anymore.
function renounceOwnership() external onlyOwner {
// Require that the ownership is transferable.
require(_isTransferable, "ownership is not transferable");
// note that this could be terminal
_owner = address(0);
emit TransferredOwnership(_owner, address(0));
}
/// @notice Find out owner address
/// @return address of the owner.
function owner() public view returns (address payable) {
return _owner;
}
/// @notice Check if owner address
/// @return true if sender is the owner of the contract.
function _isOwner(address _address) internal view returns (bool) {
return _address == _owner;
}
}
// File: controller.sol
/**
* Controller - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title The IController interface provides access to the isController and isAdmin checks.
interface IController {
function isController(address) external view returns (bool);
function isAdmin(address) external view returns (bool);
}
/// @title Controller stores a list of controller addresses that can be used for authentication in other contracts.
/// @notice The Controller implements a hierarchy of concepts, Owner, Admin, and the Controllers.
/// @dev Owner can change the Admins
/// @dev Admins and can the Controllers
/// @dev Controllers are used by the application.
contract Controller is IController, Ownable, Transferrable {
event AddedController(address _sender, address _controller);
event RemovedController(address _sender, address _controller);
event AddedAdmin(address _sender, address _admin);
event RemovedAdmin(address _sender, address _admin);
event Claimed(address _to, address _asset, uint _amount);
event Stopped(address _sender);
event Started(address _sender);
mapping (address => bool) private _isAdmin;
uint private _adminCount;
mapping (address => bool) private _isController;
uint private _controllerCount;
bool private _stopped;
/// @notice Constructor initializes the owner with the provided address.
/// @param _ownerAddress_ address of the owner.
constructor(address payable _ownerAddress_) Ownable(_ownerAddress_, false) public {}
/// @notice Checks if message sender is an admin.
modifier onlyAdmin() {
require(isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @notice Check if Owner or Admin
modifier onlyAdminOrOwner() {
require(_isOwner(msg.sender) || isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @notice Check if controller is stopped
modifier notStopped() {
require(!isStopped(), "controller is stopped");
_;
}
/// @notice Add a new admin to the list of admins.
/// @param _account address to add to the list of admins.
function addAdmin(address _account) external onlyOwner notStopped {
_addAdmin(_account);
}
/// @notice Remove a admin from the list of admins.
/// @param _account address to remove from the list of admins.
function removeAdmin(address _account) external onlyOwner {
_removeAdmin(_account);
}
/// @return the current number of admins.
function adminCount() external view returns (uint) {
return _adminCount;
}
/// @notice Add a new controller to the list of controllers.
/// @param _account address to add to the list of controllers.
function addController(address _account) external onlyAdminOrOwner notStopped {
_addController(_account);
}
/// @notice Remove a controller from the list of controllers.
/// @param _account address to remove from the list of controllers.
function removeController(address _account) external onlyAdminOrOwner {
_removeController(_account);
}
/// @notice count the Controllers
/// @return the current number of controllers.
function controllerCount() external view returns (uint) {
return _controllerCount;
}
/// @notice is an address an Admin?
/// @return true if the provided account is an admin.
function isAdmin(address _account) public view notStopped returns (bool) {
return _isAdmin[_account];
}
/// @notice is an address a Controller?
/// @return true if the provided account is a controller.
function isController(address _account) public view notStopped returns (bool) {
return _isController[_account];
}
/// @notice this function can be used to see if the controller has been stopped
/// @return true is the Controller has been stopped
function isStopped() public view returns (bool) {
return _stopped;
}
/// @notice Internal-only function that adds a new admin.
function _addAdmin(address _account) private {
require(!_isAdmin[_account], "provided account is already an admin");
require(!_isController[_account], "provided account is already a controller");
require(!_isOwner(_account), "provided account is already the owner");
require(_account != address(0), "provided account is the zero address");
_isAdmin[_account] = true;
_adminCount++;
emit AddedAdmin(msg.sender, _account);
}
/// @notice Internal-only function that removes an existing admin.
function _removeAdmin(address _account) private {
require(_isAdmin[_account], "provided account is not an admin");
_isAdmin[_account] = false;
_adminCount--;
emit RemovedAdmin(msg.sender, _account);
}
/// @notice Internal-only function that adds a new controller.
function _addController(address _account) private {
require(!_isAdmin[_account], "provided account is already an admin");
require(!_isController[_account], "provided account is already a controller");
require(!_isOwner(_account), "provided account is already the owner");
require(_account != address(0), "provided account is the zero address");
_isController[_account] = true;
_controllerCount++;
emit AddedController(msg.sender, _account);
}
/// @notice Internal-only function that removes an existing controller.
function _removeController(address _account) private {
require(_isController[_account], "provided account is not a controller");
_isController[_account] = false;
_controllerCount--;
emit RemovedController(msg.sender, _account);
}
/// @notice stop our controllers and admins from being useable
function stop() external onlyAdminOrOwner {
_stopped = true;
emit Stopped(msg.sender);
}
/// @notice start our controller again
function start() external onlyOwner {
_stopped = false;
emit Started(msg.sender);
}
//// @notice Withdraw tokens from the smart contract to the specified account.
function claim(address payable _to, address _asset, uint _amount) external onlyAdmin notStopped {
_safeTransfer(_to, _asset, _amount);
emit Claimed(_to, _asset, _amount);
}
}
// File: ENS.sol
/**
* BSD 2-Clause License
*
* Copyright (c) 2018, True Names Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
pragma solidity ^0.5.0;
interface ENS {
// Logged when the owner of a node assigns a new owner to a subnode.
event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner);
// Logged when the owner of a node transfers ownership to a new account.
event Transfer(bytes32 indexed node, address owner);
// Logged when the resolver for a node changes.
event NewResolver(bytes32 indexed node, address resolver);
// Logged when the TTL of a node changes
event NewTTL(bytes32 indexed node, uint64 ttl);
function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external;
function setResolver(bytes32 node, address resolver) external;
function setOwner(bytes32 node, address owner) external;
function setTTL(bytes32 node, uint64 ttl) external;
function owner(bytes32 node) external view returns (address);
function resolver(bytes32 node) external view returns (address);
function ttl(bytes32 node) external view returns (uint64);
}
// File: ResolverBase.sol
pragma solidity ^0.5.0;
contract ResolverBase {
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_META_ID;
}
function isAuthorised(bytes32 node) internal view returns(bool);
modifier authorised(bytes32 node) {
require(isAuthorised(node));
_;
}
}
// File: ABIResolver.sol
pragma solidity ^0.5.0;
contract ABIResolver is ResolverBase {
bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56;
event ABIChanged(bytes32 indexed node, uint256 indexed contentType);
mapping(bytes32=>mapping(uint256=>bytes)) abis;
/**
* Sets the ABI associated with an ENS node.
* Nodes may have one ABI of each content type. To remove an ABI, set it to
* the empty string.
* @param node The node to update.
* @param contentType The content type of the ABI
* @param data The ABI data.
*/
function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) {
// Content types must be powers of 2
require(((contentType - 1) & contentType) == 0);
abis[node][contentType] = data;
emit ABIChanged(node, contentType);
}
/**
* Returns the ABI associated with an ENS node.
* Defined in EIP205.
* @param node The ENS node to query
* @param contentTypes A bitwise OR of the ABI formats accepted by the caller.
* @return contentType The content type of the return value
* @return data The ABI data
*/
function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) {
mapping(uint256=>bytes) storage abiset = abis[node];
for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) {
if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) {
return (contentType, abiset[contentType]);
}
}
return (0, bytes(""));
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: AddrResolver.sol
pragma solidity ^0.5.0;
contract AddrResolver is ResolverBase {
bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de;
event AddrChanged(bytes32 indexed node, address a);
mapping(bytes32=>address) addresses;
/**
* Sets the address associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param addr The address to set.
*/
function setAddr(bytes32 node, address addr) external authorised(node) {
addresses[node] = addr;
emit AddrChanged(node, addr);
}
/**
* Returns the address associated with an ENS node.
* @param node The ENS node to query.
* @return The associated address.
*/
function addr(bytes32 node) public view returns (address) {
return addresses[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == ADDR_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: ContentHashResolver.sol
pragma solidity ^0.5.0;
contract ContentHashResolver is ResolverBase {
bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1;
event ContenthashChanged(bytes32 indexed node, bytes hash);
mapping(bytes32=>bytes) hashes;
/**
* Sets the contenthash associated with an ENS node.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param hash The contenthash to set
*/
function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) {
hashes[node] = hash;
emit ContenthashChanged(node, hash);
}
/**
* Returns the contenthash associated with an ENS node.
* @param node The ENS node to query.
* @return The associated contenthash.
*/
function contenthash(bytes32 node) external view returns (bytes memory) {
return hashes[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: InterfaceResolver.sol
pragma solidity ^0.5.0;
contract InterfaceResolver is ResolverBase, AddrResolver {
bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)"));
bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7;
event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer);
mapping(bytes32=>mapping(bytes4=>address)) interfaces;
/**
* Sets an interface associated with a name.
* Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support.
* @param node The node to update.
* @param interfaceID The EIP 168 interface ID.
* @param implementer The address of a contract that implements this interface for this node.
*/
function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) {
interfaces[node][interfaceID] = implementer;
emit InterfaceChanged(node, interfaceID, implementer);
}
/**
* Returns the address of a contract that implements the specified interface for this name.
* If an implementer has not been set for this interfaceID and name, the resolver will query
* the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that
* contract implements EIP168 and returns `true` for the specified interfaceID, its address
* will be returned.
* @param node The ENS node to query.
* @param interfaceID The EIP 168 interface ID to check for.
* @return The address that implements this interface, or 0 if the interface is unsupported.
*/
function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) {
address implementer = interfaces[node][interfaceID];
if(implementer != address(0)) {
return implementer;
}
address a = addr(node);
if(a == address(0)) {
return address(0);
}
(bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// EIP 168 not supported by target
return address(0);
}
(success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID));
if(!success || returnData.length < 32 || returnData[31] == 0) {
// Specified interface not supported by target
return address(0);
}
return a;
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: NameResolver.sol
pragma solidity ^0.5.0;
contract NameResolver is ResolverBase {
bytes4 constant private NAME_INTERFACE_ID = 0x691f3431;
event NameChanged(bytes32 indexed node, string name);
mapping(bytes32=>string) names;
/**
* Sets the name associated with an ENS node, for reverse records.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param name The name to set.
*/
function setName(bytes32 node, string calldata name) external authorised(node) {
names[node] = name;
emit NameChanged(node, name);
}
/**
* Returns the name associated with an ENS node, for reverse records.
* Defined in EIP181.
* @param node The ENS node to query.
* @return The associated name.
*/
function name(bytes32 node) external view returns (string memory) {
return names[node];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: PubkeyResolver.sol
pragma solidity ^0.5.0;
contract PubkeyResolver is ResolverBase {
bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233;
event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y);
struct PublicKey {
bytes32 x;
bytes32 y;
}
mapping(bytes32=>PublicKey) pubkeys;
/**
* Sets the SECP256k1 public key associated with an ENS node.
* @param node The ENS node to query
* @param x the X coordinate of the curve point for the public key.
* @param y the Y coordinate of the curve point for the public key.
*/
function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) {
pubkeys[node] = PublicKey(x, y);
emit PubkeyChanged(node, x, y);
}
/**
* Returns the SECP256k1 public key associated with an ENS node.
* Defined in EIP 619.
* @param node The ENS node to query
* @return x, y the X and Y coordinates of the curve point for the public key.
*/
function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) {
return (pubkeys[node].x, pubkeys[node].y);
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: TextResolver.sol
pragma solidity ^0.5.0;
contract TextResolver is ResolverBase {
bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c;
event TextChanged(bytes32 indexed node, string indexedKey, string key);
mapping(bytes32=>mapping(string=>string)) texts;
/**
* Sets the text data associated with an ENS node and key.
* May only be called by the owner of that node in the ENS registry.
* @param node The node to update.
* @param key The key to set.
* @param value The text data value to set.
*/
function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) {
texts[node][key] = value;
emit TextChanged(node, key, key);
}
/**
* Returns the text data associated with an ENS node and key.
* @param node The ENS node to query.
* @param key The text data key to query.
* @return The associated text data.
*/
function text(bytes32 node, string calldata key) external view returns (string memory) {
return texts[node][key];
}
function supportsInterface(bytes4 interfaceID) public pure returns(bool) {
return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID);
}
}
// File: PublicResolver.sol
/**
* BSD 2-Clause License
*
* Copyright (c) 2018, True Names Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
pragma solidity ^0.5.0;
/**
* A simple resolver anyone can use; only allows the owner of a node to set its
* address.
*/
contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver {
ENS ens;
/**
* A mapping of authorisations. An address that is authorised for a name
* may make any changes to the name that the owner could, but may not update
* the set of authorisations.
* (node, owner, caller) => isAuthorised
*/
mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations;
event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised);
constructor(ENS _ens) public {
ens = _ens;
}
/**
* @dev Sets or clears an authorisation.
* Authorisations are specific to the caller. Any account can set an authorisation
* for any name, but the authorisation that is checked will be that of the
* current owner of a name. Thus, transferring a name effectively clears any
* existing authorisations, and new authorisations can be set in advance of
* an ownership transfer if desired.
*
* @param node The name to change the authorisation on.
* @param target The address that is to be authorised or deauthorised.
* @param isAuthorised True if the address should be authorised, or false if it should be deauthorised.
*/
function setAuthorisation(bytes32 node, address target, bool isAuthorised) external {
authorisations[node][msg.sender][target] = isAuthorised;
emit AuthorisationChanged(node, msg.sender, target, isAuthorised);
}
function isAuthorised(bytes32 node) internal view returns(bool) {
address owner = ens.owner(node);
return owner == msg.sender || authorisations[node][owner][msg.sender];
}
}
// File: ensResolvable.sol
/**
* ENSResolvable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
///@title ENSResolvable - Ethereum Name Service Resolver
///@notice contract should be used to get an address for an ENS node
contract ENSResolvable {
/// @notice _ens is an instance of ENS
ENS private _ens;
/// @notice _ensRegistry points to the ENS registry smart contract.
address private _ensRegistry;
/// @param _ensReg_ is the ENS registry used
constructor(address _ensReg_) internal {
_ensRegistry = _ensReg_;
_ens = ENS(_ensRegistry);
}
/// @notice this is used to that one can observe which ENS registry is being used
function ensRegistry() external view returns (address) {
return _ensRegistry;
}
/// @notice helper function used to get the address of a node
/// @param _node of the ENS entry that needs resolving
/// @return the address of the said node
function _ensResolve(bytes32 _node) internal view returns (address) {
return PublicResolver(_ens.resolver(_node)).addr(_node);
}
}
// File: controllable.sol
/**
* Controllable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Controllable implements access control functionality of the Controller found via ENS.
contract Controllable is ENSResolvable {
/// @dev Is the registered ENS node identifying the controller contract.
bytes32 private _controllerNode;
/// @notice Constructor initializes the controller contract object.
/// @param _controllerNode_ is the ENS node of the Controller.
constructor(bytes32 _controllerNode_) internal {
_controllerNode = _controllerNode_;
}
/// @notice Checks if message sender is a controller.
modifier onlyController() {
require(_isController(msg.sender), "sender is not a controller");
_;
}
/// @notice Checks if message sender is an admin.
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "sender is not an admin");
_;
}
/// @return the controller node registered in ENS.
function controllerNode() external view returns (bytes32) {
return _controllerNode;
}
/// @return true if the provided account is a controller.
function _isController(address _account) internal view returns (bool) {
return IController(_ensResolve(_controllerNode)).isController(_account);
}
/// @return true if the provided account is an admin.
function _isAdmin(address _account) internal view returns (bool) {
return IController(_ensResolve(_controllerNode)).isAdmin(_account);
}
}
// File: bytesUtils.sol
/**
* BytesUtils - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title BytesUtils provides basic byte slicing and casting functionality.
library BytesUtils {
using SafeMath for uint256;
/// @dev This function converts to an address
/// @param _bts bytes
/// @param _from start position
function _bytesToAddress(bytes memory _bts, uint _from) internal pure returns (address) {
require(_bts.length >= _from.add(20), "slicing out of range");
bytes20 convertedAddress;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
convertedAddress := mload(add(_bts, startByte))
}
return address(convertedAddress);
}
/// @dev This function slices bytes into bytes4
/// @param _bts some bytes
/// @param _from start position
function _bytesToBytes4(bytes memory _bts, uint _from) internal pure returns (bytes4) {
require(_bts.length >= _from.add(4), "slicing out of range");
bytes4 slicedBytes4;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
slicedBytes4 := mload(add(_bts, startByte))
}
return slicedBytes4;
}
/// @dev This function slices a uint
/// @param _bts some bytes
/// @param _from start position
// credit to https://ethereum.stackexchange.com/questions/51229/how-to-convert-bytes-to-uint-in-solidity
// and Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity/4177#4177
function _bytesToUint256(bytes memory _bts, uint _from) internal pure returns (uint) {
require(_bts.length >= _from.add(32), "slicing out of range");
uint convertedUint256;
uint startByte = _from.add(32); //first 32 bytes denote the array length
assembly {
convertedUint256 := mload(add(_bts, startByte))
}
return convertedUint256;
}
}
// File: strings.sol
/*
* Copyright 2016 Nick Johnson
*
* 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.
*/
/*
* @title String & slice utility library for Solidity contracts.
* @author Nick Johnson <[email protected]>
*
* @dev Functionality in this library is largely implemented using an
* abstraction called a 'slice'. A slice represents a part of a string -
* anything from the entire string to a single character, or even no
* characters at all (a 0-length slice). Since a slice only has to specify
* an offset and a length, copying and manipulating slices is a lot less
* expensive than copying and manipulating the strings they reference.
*
* To further reduce gas costs, most functions on slice that need to return
* a slice modify the original one instead of allocating a new one; for
* instance, `s.split(".")` will return the text up to the first '.',
* modifying s to only contain the remainder of the string after the '.'.
* In situations where you do not want to modify the original slice, you
* can make a copy first with `.copy()`, for example:
* `s.copy().split(".")`. Try and avoid using this idiom in loops; since
* Solidity has no memory management, it will result in allocating many
* short-lived slices that are later discarded.
*
* Functions that return two slices come in two versions: a non-allocating
* version that takes the second slice as an argument, modifying it in
* place, and an allocating version that allocates and returns the second
* slice; see `nextRune` for example.
*
* Functions that have to copy string data will return strings rather than
* slices; these can be cast back to slices for further processing if
* required.
*
* For convenience, some functions are provided with non-modifying
* variants that create a new slice and return both; for instance,
* `s.splitNew('.')` leaves s unmodified, and returns two values
* corresponding to the left and right parts of the string.
*/
pragma solidity ^0.5.0;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// 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))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if (b < 0xE0) {
ptr += 2;
} else if (b < 0xF0) {
ptr += 3;
} else if (b < 0xF8) {
ptr += 4;
} else if (b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if (shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if (b < 0xE0) {
l = 2;
} else if (b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if (b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if (b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for (uint i = 0; i < parts.length; i++) {
length += parts[i]._len;
}
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for (uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
// File: tokenWhitelist.sol
/**
* TokenWhitelist - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title The ITokenWhitelist interface provides access to a whitelist of tokens.
interface ITokenWhitelist {
function getTokenInfo(address) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);
function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256);
function tokenAddressArray() external view returns (address[] memory);
function redeemableTokens() external view returns (address[] memory);
function methodIdWhitelist(bytes4) external view returns (bool);
function getERC20RecipientAndAmount(address, bytes calldata) external view returns (address, uint);
function stablecoin() external view returns (address);
function updateTokenRate(address, uint, uint) external;
}
/// @title TokenWhitelist stores a list of tokens used by the Consumer Contract Wallet, the Oracle, the TKN Holder and the TKN Licence Contract
contract TokenWhitelist is ENSResolvable, Controllable, Transferrable {
using strings for *;
using SafeMath for uint256;
using BytesUtils for bytes;
event UpdatedTokenRate(address _sender, address _token, uint _rate);
event UpdatedTokenLoadable(address _sender, address _token, bool _loadable);
event UpdatedTokenRedeemable(address _sender, address _token, bool _redeemable);
event AddedToken(address _sender, address _token, string _symbol, uint _magnitude, bool _loadable, bool _redeemable);
event RemovedToken(address _sender, address _token);
event AddedMethodId(bytes4 _methodId);
event RemovedMethodId(bytes4 _methodId);
event AddedExclusiveMethod(address _token, bytes4 _methodId);
event RemovedExclusiveMethod(address _token, bytes4 _methodId);
event Claimed(address _to, address _asset, uint _amount);
/// @dev these are the methods whitelisted by default in executeTransaction() for protected tokens
bytes4 private constant _APPROVE = 0x095ea7b3; // keccak256(approve(address,uint256)) => 0x095ea7b3
bytes4 private constant _BURN = 0x42966c68; // keccak256(burn(uint256)) => 0x42966c68
bytes4 private constant _TRANSFER= 0xa9059cbb; // keccak256(transfer(address,uint256)) => 0xa9059cbb
bytes4 private constant _TRANSFER_FROM = 0x23b872dd; // keccak256(transferFrom(address,address,uint256)) => 0x23b872dd
struct Token {
string symbol; // Token symbol
uint magnitude; // 10^decimals
uint rate; // Token exchange rate in wei
bool available; // Flags if the token is available or not
bool loadable; // Flags if token is loadable to the TokenCard
bool redeemable; // Flags if token is redeemable in the TKN Holder contract
uint lastUpdate; // Time of the last rate update
}
mapping(address => Token) private _tokenInfoMap;
// @notice specifies whitelisted methodIds for protected tokens in wallet's excuteTranaction() e.g. keccak256(transfer(address,uint256)) => 0xa9059cbb
mapping(bytes4 => bool) private _methodIdWhitelist;
address[] private _tokenAddressArray;
/// @notice keeping track of how many redeemable tokens are in the tokenWhitelist
uint private _redeemableCounter;
/// @notice Address of the stablecoin.
address private _stablecoin;
/// @notice is registered ENS node identifying the oracle contract.
bytes32 private _oracleNode;
/// @notice Constructor initializes ENSResolvable, and Controllable.
/// @param _ens_ is the ENS registry address.
/// @param _oracleNode_ is the ENS node of the Oracle.
/// @param _controllerNode_ is our Controllers node.
/// @param _stablecoinAddress_ is the address of the stablecoint used by the wallet for the card load limit.
constructor(address _ens_, bytes32 _oracleNode_, bytes32 _controllerNode_, address _stablecoinAddress_) ENSResolvable(_ens_) Controllable(_controllerNode_) public {
_oracleNode = _oracleNode_;
_stablecoin = _stablecoinAddress_;
//a priori ERC20 whitelisted methods
_methodIdWhitelist[_APPROVE] = true;
_methodIdWhitelist[_BURN] = true;
_methodIdWhitelist[_TRANSFER] = true;
_methodIdWhitelist[_TRANSFER_FROM] = true;
}
modifier onlyAdminOrOracle() {
address oracleAddress = _ensResolve(_oracleNode);
require (_isAdmin(msg.sender) || msg.sender == oracleAddress, "either oracle or admin");
_;
}
/// @notice Add ERC20 tokens to the list of whitelisted tokens.
/// @param _tokens ERC20 token contract addresses.
/// @param _symbols ERC20 token names.
/// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token.
/// @param _loadable is a bool that states whether or not a token is loadable to the TokenCard.
/// @param _redeemable is a bool that states whether or not a token is redeemable in the TKN Holder Contract.
/// @param _lastUpdate is a unit representing an ISO datetime e.g. 20180913153211.
function addTokens(address[] calldata _tokens, bytes32[] calldata _symbols, uint[] calldata _magnitude, bool[] calldata _loadable, bool[] calldata _redeemable, uint _lastUpdate) external onlyAdmin {
// Require that all parameters have the same length.
require(_tokens.length == _symbols.length && _tokens.length == _magnitude.length && _tokens.length == _loadable.length && _tokens.length == _loadable.length, "parameter lengths do not match");
// Add each token to the list of supported tokens.
for (uint i = 0; i < _tokens.length; i++) {
// Require that the token isn't already available.
require(!_tokenInfoMap[_tokens[i]].available, "token already available");
// Store the intermediate values.
string memory symbol = _symbols[i].toSliceB32().toString();
// Add the token to the token list.
_tokenInfoMap[_tokens[i]] = Token({
symbol : symbol,
magnitude : _magnitude[i],
rate : 0,
available : true,
loadable : _loadable[i],
redeemable: _redeemable[i],
lastUpdate : _lastUpdate
});
// Add the token address to the address list.
_tokenAddressArray.push(_tokens[i]);
//if the token is redeemable increase the redeemableCounter
if (_redeemable[i]){
_redeemableCounter = _redeemableCounter.add(1);
}
// Emit token addition event.
emit AddedToken(msg.sender, _tokens[i], symbol, _magnitude[i], _loadable[i], _redeemable[i]);
}
}
/// @notice Remove ERC20 tokens from the whitelist of tokens.
/// @param _tokens ERC20 token contract addresses.
function removeTokens(address[] calldata _tokens) external onlyAdmin {
// Delete each token object from the list of supported tokens based on the addresses provided.
for (uint i = 0; i < _tokens.length; i++) {
// Store the token address.
address token = _tokens[i];
//token must be available, reverts on duplicates as well
require(_tokenInfoMap[token].available, "token is not available");
//if the token is redeemable decrease the redeemableCounter
if (_tokenInfoMap[token].redeemable){
_redeemableCounter = _redeemableCounter.sub(1);
}
// Delete the token object.
delete _tokenInfoMap[token];
// Remove the token address from the address list.
for (uint j = 0; j < _tokenAddressArray.length.sub(1); j++) {
if (_tokenAddressArray[j] == token) {
_tokenAddressArray[j] = _tokenAddressArray[_tokenAddressArray.length.sub(1)];
break;
}
}
_tokenAddressArray.length--;
// Emit token removal event.
emit RemovedToken(msg.sender, token);
}
}
/// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.
/// @param _data is the transaction payload.
function getERC20RecipientAndAmount(address _token, bytes calldata _data) external view returns (address, uint) {
// Require that there exist enough bytes for encoding at least a method signature + data in the transaction payload:
// 4 (signature) + 32(address or uint256)
require(_data.length >= 4 + 32, "not enough method-encoding bytes");
// Get the method signature
bytes4 signature = _data._bytesToBytes4(0);
// Check if method Id is supported
require(isERC20MethodSupported(_token, signature), "unsupported method");
// returns the recipient's address and amount is the value to be transferred
if (signature == _BURN) {
// 4 (signature) + 32(uint256)
return (_token, _data._bytesToUint256(4));
} else if (signature == _TRANSFER_FROM) {
// 4 (signature) + 32(address) + 32(address) + 32(uint256)
require(_data.length >= 4 + 32 + 32 + 32, "not enough data for transferFrom");
return ( _data._bytesToAddress(4 + 32 + 12), _data._bytesToUint256(4 + 32 + 32));
} else { //transfer or approve
// 4 (signature) + 32(address) + 32(uint)
require(_data.length >= 4 + 32 + 32, "not enough data for transfer/appprove");
return (_data._bytesToAddress(4 + 12), _data._bytesToUint256(4 + 32));
}
}
/// @notice Toggles whether or not a token is loadable or not.
function setTokenLoadable(address _token, bool _loadable) external onlyAdmin {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// this sets the loadable flag to the value passed in
_tokenInfoMap[_token].loadable = _loadable;
emit UpdatedTokenLoadable(msg.sender, _token, _loadable);
}
/// @notice Toggles whether or not a token is redeemable or not.
function setTokenRedeemable(address _token, bool _redeemable) external onlyAdmin {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// this sets the redeemable flag to the value passed in
_tokenInfoMap[_token].redeemable = _redeemable;
emit UpdatedTokenRedeemable(msg.sender, _token, _redeemable);
}
/// @notice Update ERC20 token exchange rate.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle {
// Require that the token exists.
require(_tokenInfoMap[_token].available, "token is not available");
// Update the token's rate.
_tokenInfoMap[_token].rate = _rate;
// Update the token's last update timestamp.
_tokenInfoMap[_token].lastUpdate = _updateDate;
// Emit the rate update event.
emit UpdatedTokenRate(msg.sender, _token, _rate);
}
//// @notice Withdraw tokens from the smart contract to the specified account.
function claim(address payable _to, address _asset, uint _amount) external onlyAdmin {
_safeTransfer(_to, _asset, _amount);
emit Claimed(_to, _asset, _amount);
}
/// @notice This returns all of the fields for a given token.
/// @param _a is the address of a given token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function getTokenInfo(address _a) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
Token storage tokenInfo = _tokenInfoMap[_a];
return (tokenInfo.symbol, tokenInfo.magnitude, tokenInfo.rate, tokenInfo.available, tokenInfo.loadable, tokenInfo.redeemable, tokenInfo.lastUpdate);
}
/// @notice This returns all of the fields for our StableCoin.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
Token storage stablecoinInfo = _tokenInfoMap[_stablecoin];
return (stablecoinInfo.symbol, stablecoinInfo.magnitude, stablecoinInfo.rate, stablecoinInfo.available, stablecoinInfo.loadable, stablecoinInfo.redeemable, stablecoinInfo.lastUpdate);
}
/// @notice This returns an array of all whitelisted token addresses.
/// @return address[] of whitelisted tokens.
function tokenAddressArray() external view returns (address[] memory) {
return _tokenAddressArray;
}
/// @notice This returns an array of all redeemable token addresses.
/// @return address[] of redeemable tokens.
function redeemableTokens() external view returns (address[] memory) {
address[] memory redeemableAddresses = new address[](_redeemableCounter);
uint redeemableIndex = 0;
for (uint i = 0; i < _tokenAddressArray.length; i++) {
address token = _tokenAddressArray[i];
if (_tokenInfoMap[token].redeemable){
redeemableAddresses[redeemableIndex] = token;
redeemableIndex += 1;
}
}
return redeemableAddresses;
}
/// @notice This returns true if a method Id is supported for the specific token.
/// @return true if _methodId is supported in general or just for the specific token.
function isERC20MethodSupported(address _token, bytes4 _methodId) public view returns (bool) {
require(_tokenInfoMap[_token].available, "non-existing token");
return (_methodIdWhitelist[_methodId]);
}
/// @notice This returns true if the method is supported for all protected tokens.
/// @return true if _methodId is in the method whitelist.
function isERC20MethodWhitelisted(bytes4 _methodId) external view returns (bool) {
return (_methodIdWhitelist[_methodId]);
}
/// @notice This returns the number of redeemable tokens.
/// @return current # of redeemables.
function redeemableCounter() external view returns (uint) {
return _redeemableCounter;
}
/// @notice This returns the address of our stablecoin of choice.
/// @return the address of the stablecoin contract.
function stablecoin() external view returns (address) {
return _stablecoin;
}
/// @notice this returns the node hash of our Oracle.
/// @return the oracle node registered in ENS.
function oracleNode() external view returns (bytes32) {
return _oracleNode;
}
}
// File: tokenWhitelistable.sol
/**
* TokenWhitelistable - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title TokenWhitelistable implements access to the TokenWhitelist located behind ENS.
contract TokenWhitelistable is ENSResolvable {
/// @notice Is the registered ENS node identifying the tokenWhitelist contract
bytes32 private _tokenWhitelistNode;
/// @notice Constructor initializes the TokenWhitelistable object.
/// @param _tokenWhitelistNode_ is the ENS node of the TokenWhitelist.
constructor(bytes32 _tokenWhitelistNode_) internal {
_tokenWhitelistNode = _tokenWhitelistNode_;
}
/// @notice This shows what TokenWhitelist is being used
/// @return TokenWhitelist's node registered in ENS.
function tokenWhitelistNode() external view returns (bytes32) {
return _tokenWhitelistNode;
}
/// @notice This returns all of the fields for a given token.
/// @param _a is the address of a given token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function _getTokenInfo(address _a) internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getTokenInfo(_a);
}
/// @notice This returns all of the fields for our stablecoin token.
/// @return string of the token's symbol.
/// @return uint of the token's magnitude.
/// @return uint of the token's exchange rate to ETH.
/// @return bool whether the token is available.
/// @return bool whether the token is loadable to the TokenCard.
/// @return bool whether the token is redeemable to the TKN Holder Contract.
/// @return uint of the lastUpdated time of the token's exchange rate.
function _getStablecoinInfo() internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getStablecoinInfo();
}
/// @notice This returns an array of our whitelisted addresses.
/// @return address[] of our whitelisted tokens.
function _tokenAddressArray() internal view returns (address[] memory) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).tokenAddressArray();
}
/// @notice This returns an array of all redeemable token addresses.
/// @return address[] of redeemable tokens.
function _redeemableTokens() internal view returns (address[] memory) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).redeemableTokens();
}
/// @notice Update ERC20 token exchange rate.
/// @param _token ERC20 token contract address.
/// @param _rate ERC20 token exchange rate in wei.
/// @param _updateDate date for the token updates. This will be compared to when oracle updates are received.
function _updateTokenRate(address _token, uint _rate, uint _updateDate) internal {
ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).updateTokenRate(_token, _rate, _updateDate);
}
/// @notice based on the method it returns the recipient address and amount/value, ERC20 specific.
/// @param _data is the transaction payload.
function _getERC20RecipientAndAmount(address _destination, bytes memory _data) internal view returns (address, uint) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getERC20RecipientAndAmount(_destination, _data);
}
/// @notice Checks whether a token is available.
/// @return bool available or not.
function _isTokenAvailable(address _a) internal view returns (bool) {
( , , , bool available, , , ) = _getTokenInfo(_a);
return available;
}
/// @notice Checks whether a token is redeemable.
/// @return bool redeemable or not.
function _isTokenRedeemable(address _a) internal view returns (bool) {
( , , , , , bool redeemable, ) = _getTokenInfo(_a);
return redeemable;
}
/// @notice Checks whether a token is loadable.
/// @return bool loadable or not.
function _isTokenLoadable(address _a) internal view returns (bool) {
( , , , , bool loadable, , ) = _getTokenInfo(_a);
return loadable;
}
/// @notice This gets the address of the stablecoin.
/// @return the address of the stablecoin contract.
function _stablecoin() internal view returns (address) {
return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).stablecoin();
}
}
// File: holder.sol
/**
* Holder (aka Asset Contract) - The Consumer Contract Wallet
* Copyright (C) 2019 The Contract Wallet Company Limited
*
* 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 <https://www.gnu.org/licenses/>.
*/
pragma solidity ^0.5.10;
/// @title Holder - The TKN Asset Contract
/// @notice When the TKN contract calls the burn method, a share of the tokens held by this contract are disbursed to the burner.
contract Holder is Balanceable, ENSResolvable, Controllable, Transferrable, TokenWhitelistable {
using SafeMath for uint256;
event Received(address _from, uint _amount);
event CashAndBurned(address _to, address _asset, uint _amount);
event Claimed(address _to, address _asset, uint _amount);
/// @dev Check if the sender is the burner contract
modifier onlyBurner() {
require (msg.sender == _burner, "burner contract is not the sender");
_;
}
// Burner token which can be burned to redeem shares.
address private _burner;
/// @notice Constructor initializes the holder contract.
/// @param _burnerContract_ is the address of the token contract TKN with burning functionality.
/// @param _ens_ is the address of the ENS registry.
/// @param _tokenWhitelistNode_ is the ENS node of the Token whitelist.
/// @param _controllerNode_ is the ENS node of the Controller
constructor (address _burnerContract_, address _ens_, bytes32 _tokenWhitelistNode_, bytes32 _controllerNode_) ENSResolvable(_ens_) Controllable(_controllerNode_) TokenWhitelistable(_tokenWhitelistNode_) public {
_burner = _burnerContract_;
}
/// @notice Ether may be sent from anywhere.
function() external payable {
emit Received(msg.sender, msg.value);
}
/// @notice Burn handles disbursing a share of tokens in this contract to a given address.
/// @param _to The address to disburse to
/// @param _amount The amount of TKN that will be burned if this succeeds
function burn(address payable _to, uint _amount) external onlyBurner returns (bool) {
if (_amount == 0) {
return true;
}
// The burner token deducts from the supply before calling.
uint supply = IBurner(_burner).currentSupply().add(_amount);
address[] memory redeemableAddresses = _redeemableTokens();
for (uint i = 0; i < redeemableAddresses.length; i++) {
uint redeemableBalance = _balance(address(this), redeemableAddresses[i]);
if (redeemableBalance > 0) {
uint redeemableAmount = redeemableBalance.mul(_amount).div(supply);
_safeTransfer(_to, redeemableAddresses[i], redeemableAmount);
emit CashAndBurned(_to, redeemableAddresses[i], redeemableAmount);
}
}
return true;
}
/// @notice This allows for the admin to reclaim the non-redeemableTokens
/// @param _to this is the address which the reclaimed tokens will be sent to
/// @param _nonRedeemableAddresses this is the array of tokens to be claimed
function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) {
for (uint i = 0; i < _nonRedeemableAddresses.length; i++) {
//revert if token is redeemable
require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), "redeemables cannot be claimed");
uint claimBalance = _balance(address(this), _nonRedeemableAddresses[i]);
if (claimBalance > 0) {
_safeTransfer(_to, _nonRedeemableAddresses[i], claimBalance);
emit Claimed(_to, _nonRedeemableAddresses[i], claimBalance);
}
}
return true;
}
/// @notice Returned the address of the burner contract
/// @return the TKN address
function burner() external view returns (address) {
return _burner;
}
}
|
Emit the ownership transfer event.
|
emit TransferredOwnership(_owner, _account);
| 913,559 |
[
1,
17982,
326,
23178,
7412,
871,
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,
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,
3639,
3626,
2604,
4193,
5460,
12565,
24899,
8443,
16,
389,
4631,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/Address.sol";
contract TokenFetcher is AccessControl {
using Address for address;
// Listed Tokens
MajorRoute[] majorCoins;
MinorRoute[] minorCoins;
struct MajorRoute {
string fromSymbol;
address fromToken;
address[] toTokens;
string[] toSymbols;
string[] routesName;
uint128[] routesId;
}
struct MinorRoute {
string fromSymbol;
address fromToken;
address[] toTokens;
string[] toSymbols;
string[] routesName;
uint128[] routesId;
}
constructor(address gnosis, bool isTesting) {
require(gnosis.isContract(), "Exchange: not contract");
_grantRole(DEFAULT_ADMIN_ROLE, gnosis);
if (isTesting) _grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// @notice Retrieve all major listed tokens with associated routes.
/// @return Array of Major tokens
function getAllMajorCoins() external view returns (MajorRoute[] memory) {
return majorCoins;
}
/// @notice Retrieve all minor listed tokens with associated routes.
/// @return Array of Minor tokens
function getAllMinorCoins() external view returns (MinorRoute[] memory) {
return minorCoins;
}
/// @notice Bulk Add Listed Major Coins
/// @dev New Token pushed at last index
/// @param _newTokenToPush Tuple of matching struct
/// @return Array of new listed major tokens
function addMajorCoins(MajorRoute[] memory _newTokenToPush)
external
onlyRole(DEFAULT_ADMIN_ROLE)
returns (MajorRoute[] memory)
{
for (uint i = 0; i < _newTokenToPush.length; i++) {
majorCoins.push(_newTokenToPush[i]);
}
return majorCoins;
}
/// @notice Bulk Add Listed Minor Coins
/// @dev New Token pushed at last index
/// @param _newTokenToPush Tuple of matching struct
/// @return Array of new listed minor tokens
function addMinorCoins(MinorRoute[] memory _newTokenToPush)
external
onlyRole(DEFAULT_ADMIN_ROLE)
returns (MinorRoute[] memory)
{
for (uint i = 0; i < _newTokenToPush.length; i++) {
minorCoins.push(_newTokenToPush[i]);
}
return minorCoins;
}
/// @notice Replace Listed Major Tokens Datas
/// @dev All information must be rewritten
/// @param _indexOfToken Index of Token To Replace
/// @param _newData New Struct
/// @return Array of modified major tokens
function changeMajorCoinData(
uint256 _indexOfToken,
MajorRoute memory _newData
) external onlyRole(DEFAULT_ADMIN_ROLE) returns (MajorRoute[] memory) {
majorCoins[_indexOfToken] = _newData;
return majorCoins;
}
/// @notice Replace Listed Minor Tokens Datas
/// @dev All information must be rewritten
/// @param _indexOfToken Index of Token To Replace
/// @param _newData New Struct
/// @return Array of modified major tokens
function changeMinorCoinData(
uint256 _indexOfToken,
MinorRoute memory _newData
) external onlyRole(DEFAULT_ADMIN_ROLE) returns (MinorRoute[] memory) {
minorCoins[_indexOfToken] = _newData;
return minorCoins;
}
/// @notice Delete Listed Major Token by Index.
/// @dev Switch actual token's index to last one and delete it
/// @param _tokenIndex Index of token to delete.
/// @return Array of latest listed major tokens
function deleteMajorCoin(uint256 _tokenIndex)
external
onlyRole(DEFAULT_ADMIN_ROLE)
returns (MajorRoute[] memory)
{
majorCoins[_tokenIndex] = majorCoins[majorCoins.length - 1];
majorCoins.pop();
return majorCoins;
}
/// @notice Delete Listed Minor Token by Index.
/// @dev Switch actual token's index to last one and delete it
/// @param _tokenIndex Index of token to delete.
/// @return Array of latest listed minor tokens
function deleteMinorCoin(uint256 _tokenIndex)
external
onlyRole(DEFAULT_ADMIN_ROLE)
returns (MinorRoute[] memory)
{
minorCoins[_tokenIndex] = minorCoins[minorCoins.length - 1];
minorCoins.pop();
return minorCoins;
}
}
|
@notice Delete Listed Major Token by Index. @dev Switch actual token's index to last one and delete it @param _tokenIndex Index of token to delete. @return Array of latest listed major tokens
|
function deleteMajorCoin(uint256 _tokenIndex)
external
onlyRole(DEFAULT_ADMIN_ROLE)
returns (MajorRoute[] memory)
{
majorCoins[_tokenIndex] = majorCoins[majorCoins.length - 1];
majorCoins.pop();
return majorCoins;
}
| 5,365,720 |
[
1,
2613,
987,
329,
25977,
3155,
635,
3340,
18,
225,
13967,
3214,
1147,
1807,
770,
358,
1142,
1245,
471,
1430,
518,
225,
389,
2316,
1016,
3340,
434,
1147,
358,
1430,
18,
327,
1510,
434,
4891,
12889,
7888,
2430,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
1430,
17581,
27055,
12,
11890,
5034,
389,
2316,
1016,
13,
203,
3639,
3903,
203,
3639,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
203,
3639,
1135,
261,
17581,
3255,
8526,
3778,
13,
203,
565,
288,
203,
3639,
7888,
39,
9896,
63,
67,
2316,
1016,
65,
273,
7888,
39,
9896,
63,
14019,
39,
9896,
18,
2469,
300,
404,
15533,
203,
3639,
7888,
39,
9896,
18,
5120,
5621,
203,
3639,
327,
7888,
39,
9896,
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
] |
./partial_match/100/0xB05a6D89465fe397F0350f4421b271cD2AF2dEc6/sources/Chievs.sol
|
If the array is new, skip over the first index.
|
constructor () public {
if(chievs.length == 0) {
Chiev memory _dummyChiev = Chiev({priceFinney: 0,numClonesAllowed: 0, numClonesInWild: 0,
clonedFromId: 0, cloner: address(0), permTokenId: 0
});
chievs.push(_dummyChiev);
}
}
| 16,681,255 |
[
1,
2047,
326,
526,
353,
394,
16,
2488,
1879,
326,
1122,
770,
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
] |
[
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,
3885,
1832,
1071,
288,
203,
3639,
309,
12,
17384,
6904,
18,
2469,
422,
374,
13,
288,
203,
5411,
1680,
1385,
90,
3778,
389,
21050,
782,
1385,
90,
273,
1680,
1385,
90,
12590,
8694,
6187,
82,
402,
30,
374,
16,
2107,
2009,
5322,
5042,
30,
374,
16,
818,
2009,
5322,
382,
59,
545,
30,
374,
16,
203,
4766,
6647,
13027,
1265,
548,
30,
374,
16,
927,
31430,
30,
1758,
12,
20,
3631,
4641,
1345,
548,
30,
374,
203,
4766,
6647,
15549,
203,
5411,
462,
1385,
6904,
18,
6206,
24899,
21050,
782,
1385,
90,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Fundraiser donations
/// @author kwight
/// @notice This contract allows register charities to receive donations for campaigns.
contract Fundraisers is Ownable {
mapping(address => Charity) private charityRegistry;
address[] private charities;
Program[] private programs;
Donation[] private donations;
enum ProgramStatus {
Active,
Cancelled,
Complete
}
struct Charity {
string name;
uint256 index;
}
struct Program {
string title;
ProgramStatus status;
address charity;
}
struct Donation {
address doner;
uint256 programId;
uint256 amount;
}
/// @notice Emit an event when a charity is registered.
/// @param charityAddress Address of the registered charity.
/// @param name Name of the charity.
event CharityRegistered(address charityAddress, string name);
/// @notice Emit an event when a charity is removed by the owner.
/// @param charityAddress Address of the removed charity.
event CharityRemoved(address charityAddress);
/// @notice Emit an event when a charity registers a program.
/// @param programId Index in the programs array.
/// @param charityAddress Address of the charity doing the registering.
event ProgramRegistered(uint256 programId, address charityAddress);
/// @notice Emit an event when a charity cancels a program.
/// @param programId Index in the programs array.
/// @param charityAddress Address of the charity doing the cancelling.
event ProgramCancelled(uint256 programId, address charityAddress);
/// @notice Emit an event when a charity marks a program as completed.
/// @param programId Index in the programs array.
/// @param charityAddress Address of the charity marking the completion.
event ProgramCompleted(uint256 programId, address charityAddress);
/// @notice Emit an event when a donation is received.
/// @param amount Amount of the donation (in wei).
/// @param charityAddress Address of the charity receiving the funds.
/// @param programId Index in the programs array.
/// @param doner Address of the doner.
event DonationReceived(
uint256 amount,
address charityAddress,
uint256 programId,
address doner
);
modifier isOwnerOrCharity(address charityAddress) {
require(
msg.sender == owner() || msg.sender == charityAddress,
"unauthorized"
);
_;
}
modifier onlyCharity() {
require(isRegisteredCharity(msg.sender) == true, "unauthorized");
_;
}
/// @notice Verify a given address is a registered charity.
/// @param charityAddress Address being verified.
/// @return True if registered, false otherwise.
function isRegisteredCharity(address charityAddress)
public
view
returns (bool)
{
if (charities.length == 0) return false;
return (charities[charityRegistry[charityAddress].index] ==
charityAddress);
}
/// @notice Register a charity.
/// @param charityAddress Address of the charity to be registered.
/// @param name Name of the charity.
function registerCharity(address charityAddress, string memory name)
public
onlyOwner
{
require(
isRegisteredCharity(charityAddress) == false,
"charity already exists"
);
charities.push(charityAddress);
charityRegistry[charityAddress].name = name;
charityRegistry[charityAddress].index = charities.length - 1;
emit CharityRegistered(charityAddress, name);
}
/// @notice Remove a charity.
/// @param charityAddress Address of the charity to be removed.
function removeCharity(address charityAddress)
public
isOwnerOrCharity(charityAddress)
{
require(
isRegisteredCharity(charityAddress) == true,
"charity does not exist"
);
uint256 toRemove = charityRegistry[charityAddress].index;
address toMove = charities[charities.length - 1];
charityRegistry[toMove].index = toRemove;
charities[toRemove] = toMove;
charities.pop();
emit CharityRemoved(charityAddress);
}
/// @notice Get stored data for the given charity.
/// @param charityAddress Address of the charity requested.
/// @return Charity struct instance.
function getCharity(address charityAddress)
public
view
returns (Charity memory)
{
require(
isRegisteredCharity(charityAddress) == true,
"charity does not exist"
);
return charityRegistry[charityAddress];
}
/// @notice Get data for all registered charities.
/// @return Array of Charity struct instances.
function getCharities() public view returns (address[] memory) {
return charities;
}
/// @notice Get data for all registered programs.
/// @return Array of Program struct instances.
function getPrograms() public view returns (Program[] memory) {
return programs;
}
/// @notice Register a program.
/// @param title The name of the program.
function registerProgram(string memory title) public onlyCharity {
programs.push(
Program({
title: title,
status: ProgramStatus.Active,
charity: msg.sender
})
);
emit ProgramRegistered(programs.length - 1, msg.sender);
}
/// @notice Cancel an active program.
/// @param programId Index of the program to be cancelled.
function cancelProgram(uint256 programId) public onlyCharity {
require(programs.length > programId, "program does not exist");
require(programs[programId].charity == msg.sender, "unauthorized");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
programs[programId].status = ProgramStatus.Cancelled;
emit ProgramCancelled(programId, msg.sender);
}
/// @notice Mark an active program as complete.
/// @param programId Index of the program to be marked complete.
function completeProgram(uint256 programId) public onlyCharity {
require(programs.length > programId, "program does not exist");
require(programs[programId].charity == msg.sender, "unauthorized");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
programs[programId].status = ProgramStatus.Complete;
emit ProgramCompleted(programId, msg.sender);
}
/// @notice Donate ether to a charity's program.
/// @param programId Index of the program "receiving" the donation.
function donate(uint256 programId) public payable {
require(programs.length > programId, "program does not exist");
require(
programs[programId].status == ProgramStatus.Active,
"program is not active"
);
Program memory receivingProgram = programs[programId];
donations.push(
Donation({
doner: msg.sender,
programId: programId,
amount: msg.value
})
);
(bool sent, ) = receivingProgram.charity.call{value: msg.value}("");
require(sent, "ether not sent to charity");
emit DonationReceived(
msg.value,
receivingProgram.charity,
programId,
msg.sender
);
}
/// @notice Get data for all donations.
/// @return Array of Donation struct instances.
function getDonations() public view returns (Donation[] memory) {
return donations;
}
}
|
@notice Get stored data for the given charity. @param charityAddress Address of the charity requested. @return Charity struct instance.
|
function getCharity(address charityAddress)
public
view
returns (Charity memory)
{
require(
isRegisteredCharity(charityAddress) == true,
"charity does not exist"
);
return charityRegistry[charityAddress];
}
| 7,269,339 |
[
1,
967,
4041,
501,
364,
326,
864,
1149,
560,
18,
225,
1149,
560,
1887,
5267,
434,
326,
1149,
560,
3764,
18,
327,
3703,
560,
1958,
791,
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
] |
[
1,
1,
1,
1,
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,
23577,
560,
12,
2867,
1149,
560,
1887,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
2156,
560,
3778,
13,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
353,
10868,
2156,
560,
12,
3001,
560,
1887,
13,
422,
638,
16,
203,
5411,
315,
3001,
560,
1552,
486,
1005,
6,
203,
3639,
11272,
203,
3639,
327,
1149,
560,
4243,
63,
3001,
560,
1887,
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,
-100,
-100
] |
pragma solidity ^0.4.24;
contract F3Devents {
event Winner(address winner, uint256 pool, address revealer);
event Buy(address buyer, uint256 keys, uint256 cost);
event Sell(address from, uint256 price, uint256 count);
event Bought(address buyer, address from, uint256 amount, uint256 price);
}
contract F3d is F3Devents {
using SafeMath for *;
uint256 public a; // key price parameter 15825000
uint256 public b; // key price parameter 749999139625000
uint256 public ta; // percentage goes to pool 37.5
uint256 public tb; // percentage goes to split 38.5
uint256 public tc; // percentage goes to ref1 15
uint256 public td; // percentage goes to ref2 5
uint256 public te; // percentage goes to owner 4
uint256 public wa; // percentage of pool goes to winner 50
uint256 public wb; // percentage of pool goes to next pool 16.6
uint256 public wc; // percentage of pool goes to finalizer 0.5
uint256 public wd; // percentage of pool goes to owner 2.6
uint256 public we; // percentage of pool goes to split 30.3
uint256 public maxTimeRemain; // 4 * 60 * 60
uint256 public timeGap; // 5 * 60
uint256 public soldKeys; // 0
uint256 public decimals = 1000000;
bool public pause;
address public owner;
address public admin;
PlayerStatus[] public players;
mapping(address => uint256) public playerIds;
mapping(uint256 => Round) public rounds;
mapping(uint256 => mapping (uint256 => PlayerRound)) public playerRoundData;
uint256 public currentRound;
struct PlayerStatus {
address addr; //player addr
uint256 wallet; //get from spread
uint256 affiliate; //get from reference
uint256 win; //get from winning
uint256 lrnd; //last round played
uint256 referer; //who introduced this player
}
struct PlayerRound {
uint256 eth; //eth player added to this round
uint256 keys; //keys player bought in this round
uint256 mask; //player mask in this round
}
struct Round {
uint256 eth; //eth to this round
uint256 keys; //keys sold in this round
uint256 mask; //mask of this round
address winner; //winner of this round
uint256 pool; //the amount of pool when ends
uint256 endTime; //the end time
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier whenNotPaused() {
require(!pause);
_;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
function setPause(bool _pause) onlyAdmin public {
pause = _pause;
}
constructor(uint256 _a, uint256 _b,
uint256 _ta, uint256 _tb, uint256 _tc, uint256 _td, uint256 _te,
uint256 _wa, uint256 _wb, uint256 _wc, uint256 _wd, uint256 _we,
uint256 _maxTimeRemain, uint256 _gap, address _owner) public {
a = _a;
b = _b;
ta = _ta;
tb = _tb;
tc = _tc;
td = _td;
te = _te;
wa = _wa;
wb = _wb;
wc = _wc;
wd = _wd;
we = _we;
// split less than 100%
require(ta.add(tb).add(tc).add(td).add(te) == 1000);
require(wa.add(wb).add(wc).add(wd).add(we) == 1000);
owner = _owner;
// start from first round
currentRound = 1;
rounds[currentRound] = Round(0, 0, 0, owner, 0, block.timestamp.add(_maxTimeRemain));
maxTimeRemain = _maxTimeRemain;
timeGap = _gap;
admin = msg.sender;
// the first player is the owner
players.push(PlayerStatus(
owner,
0,
0,
0,
0,
0));
}
// return the price for nth key n = keys / decimals
function Price(uint256 n) public view returns (uint256) {
return n.mul(a).add(b);
}
function updatePlayer(uint256 _pID) private {
if(players[_pID].lrnd != 0) {
updateWallet(_pID, players[_pID].lrnd);
}
players[_pID].lrnd = currentRound;
}
function updateWallet(uint256 _pID, uint256 _round) private {
uint256 earnings = calculateMasked(_pID, _round);
if (earnings > 0) {
players[_pID].wallet = earnings.add(players[_pID].wallet);
playerRoundData[_pID][_round].mask = earnings.add(playerRoundData[_pID][_round].mask);
}
}
function profit() public view returns (uint256) {
uint256 id = playerIds[msg.sender];
if (id == 0 && msg.sender != owner) {
return 0;
}
PlayerStatus memory player = players[id];
return player.wallet.add(player.affiliate).add(player.win).add(calculateMasked(id, player.lrnd));
}
function calculateMasked(uint256 _pID, uint256 _round) private view returns (uint256) {
PlayerRound memory roundData = playerRoundData[_pID][_round];
return rounds[_round].mask.mul(roundData.keys).sub(roundData.mask);
}
function registerUserIfNeeded(uint256 ref) public {
if (msg.sender != owner) {
if (playerIds[msg.sender] == 0) {
playerIds[msg.sender] = players.length;
if (ref >= players.length) {
ref = 0;
}
players.push(PlayerStatus(
msg.sender,
0,
0,
0,
0,
ref));
}
}
}
// anyone can finalize a round
function finalize(uint256 ref) public {
Round storage lastOne = rounds[currentRound];
// round must be finished
require(block.timestamp > lastOne.endTime);
// register the user if necessary
registerUserIfNeeded(ref);
// new round has started
currentRound = currentRound.add(1);
Round storage _round = rounds[currentRound];
_round.endTime = block.timestamp.add(maxTimeRemain);
_round.winner = owner;
// save the round data
uint256 money = lastOne.pool;
if (money == 0) {
// nothing happend in last round
return;
}
// to pool
_round.pool = money.mul(wb) / 1000;
// to winner
uint256 toWinner = money.mul(wa) / 1000;
players[playerIds[lastOne.winner]].win = toWinner.add(players[playerIds[lastOne.winner]].win);
// to revealer
uint256 toRevealer = money.mul(wc) / 1000;
uint256 revealId = playerIds[msg.sender];
// self reveal, no awards
if (msg.sender == lastOne.winner) {
revealId = 0;
}
players[revealId].win = players[revealId].win.add(toRevealer);
uint256 toOwner = money.mul(wd) / 1000;
players[0].win = players[0].win.add(toOwner);
uint256 split = money.sub(_round.pool).sub(toWinner).sub(toRevealer).sub(toOwner);
if (lastOne.keys != 0) {
lastOne.mask = lastOne.mask.add(split / lastOne.keys);
// gather the dust
players[0].wallet = players[0].wallet.add(split.sub((split/lastOne.keys) * lastOne.keys));
} else {
// last round no one bought any keys, sad
// put the split into next round
_round.pool = split.add(_round.pool);
}
}
function price(uint256 key) public view returns (uint256) {
return a.mul(key).add(b);
}
function ethForKey(uint256 _keys) public view returns (uint256) {
Round memory current = rounds[currentRound];
uint256 c_key = (current.keys / decimals);
// in (a, a + 1], we use price(a + 1)
if (c_key.mul(decimals) != current.keys) {
c_key = c_key.add(1);
}
uint256 _price = price(c_key);
uint256 remainKeys = c_key.mul(decimals).sub(current.keys);
if (remainKeys >= _keys) {
return _price.mul(_keys) / decimals;
}
uint256 costEth = _price.mul(_keys) / decimals;
_keys = _keys.sub(remainKeys);
while(_keys >= decimals) {
c_key = c_key.add(1);
_price = price(c_key);
costEth = costEth.add(_price);
_keys = _keys.sub(decimals);
}
c_key = c_key.add(1);
_price = price(c_key);
costEth = costEth.add(_price.mul(_keys) / decimals);
return costEth;
}
// the keys that one could buy at a stage using _eth
function keys(uint256 _eth) public view returns (uint256) {
Round memory current = rounds[currentRound];
uint256 c_key = (current.keys / decimals).add(1);
uint256 _price = price(c_key);
uint256 remainKeys = c_key.mul(decimals).sub(current.keys);
uint256 remain =remainKeys.mul(_price) / decimals;
if (remain >= _eth) {
return _eth.mul(decimals) / _price;
}
uint256 boughtKeys = remainKeys;
_eth = _eth.sub(remain);
while(true) {
c_key = c_key.add(1);
_price = price(c_key);
if (_price <= _eth) {
// buy a whole unit
boughtKeys = boughtKeys.add(decimals);
_eth = _eth.sub(_price);
} else {
boughtKeys = boughtKeys.add(_eth.mul(decimals) / _price);
break;
}
}
return boughtKeys;
}
// _pID spent _eth to buy keys in _round
function core(uint256 _round, uint256 _pID, uint256 _eth) internal {
Round memory current = rounds[currentRound];
// new to this round
if (playerRoundData[_pID][_round].keys == 0) {
updatePlayer(_pID);
}
if (block.timestamp > current.endTime) {
//we need to do finalzing
finalize(players[_pID].referer);
//new round generated, we need to update the user status to the new round
updatePlayer(_pID);
}
// retrive the current round obj again, in case it changed
Round storage current_now = rounds[currentRound];
// calculate the keys that he could buy
uint256 _keys = keys(_eth);
if (_keys <= 0) {
// put the eth to the sender
// sorry, you're bumped
players[_pID].wallet = _eth.add(players[_pID].wallet);
return;
}
if (_keys >= decimals) {
// buy at least one key to be the winner
current_now.winner = players[_pID].addr;
current_now.endTime = current_now.endTime.add(timeGap);
if (current_now.endTime.sub(block.timestamp) > maxTimeRemain) {
current_now.endTime = block.timestamp.add(maxTimeRemain);
}
}
//now we do the money distribute
uint256 toOwner = _eth.sub(_eth.mul(ta) / 1000);
toOwner = toOwner.sub(_eth.mul(tb) / 1000);
toOwner = toOwner.sub(_eth.mul(tc) / 1000);
toOwner = toOwner.sub(_eth.mul(td) / 1000);
// to pool
current_now.pool = (_eth.mul(ta) / 1000).add(current_now.pool);
if (current_now.keys == 0) {
// current no keys to split, send to owner
toOwner = toOwner.add((_eth.mul(tb) / 1000));
players[0].wallet = toOwner.add(players[0].wallet);
} else {
current_now.mask = current_now.mask.add((_eth.mul(tb) / 1000) / current_now.keys);
// dust to owner;
// since the _eth will > 0, so the division is ok
uint256 dust = (_eth.mul(tb) / 1000).sub( _eth.mul(tb) / 1000 / current_now.keys * current_now.keys );
players[0].wallet = toOwner.add(dust).add(players[0].wallet);
}
// the split doesnt include keys that the user just bought
playerRoundData[_pID][currentRound].keys = _keys.add(playerRoundData[_pID][currentRound].keys);
current_now.keys = _keys.add(current_now.keys);
current_now.eth = _eth.add(current_now.eth);
// for the new keys, remove the user's free earnings
playerRoundData[_pID][currentRound].mask = current_now.mask.mul(_keys).add(playerRoundData[_pID][currentRound].mask);
// to ref 1, 2
uint256 referer1 = players[_pID].referer;
uint256 referer2 = players[referer1].referer;
players[referer1].affiliate = (_eth.mul(tc) / 1000).add(players[referer1].affiliate);
players[referer2].affiliate = (_eth.mul(td) / 1000).add(players[referer2].affiliate);
}
// calculate the keys that the user can buy with specified amount of eth
// return the eth left
function BuyKeys(uint256 ref) payable whenNotPaused public {
registerUserIfNeeded(ref);
core(currentRound, playerIds[msg.sender], msg.value);
}
function ReloadKeys(uint256 value, uint256 ref) whenNotPaused public {
registerUserIfNeeded(ref);
players[playerIds[msg.sender]].wallet = retrieveEarnings().sub(value);
core(currentRound, playerIds[msg.sender], value);
}
function retrieveEarnings() internal returns (uint256) {
uint256 id = playerIds[msg.sender];
updatePlayer(id);
PlayerStatus storage player = players[id];
uint256 earnings = player.wallet.add(player.affiliate).add(player.win);
if (earnings == 0) {
return;
}
player.wallet = 0;
player.affiliate = 0;
player.win = 0;
return earnings;
}
// withdrawal all the earning of the game
function withdrawal(uint256 ref) whenNotPaused public {
registerUserIfNeeded(ref);
uint256 earnings = retrieveEarnings();
if (earnings == 0) {
return;
}
msg.sender.transfer(earnings);
}
function playerCount() public view returns (uint256) {
return players.length;
}
function register(uint256 ref) public whenNotPaused {
registerUserIfNeeded(ref);
}
function remainTime() public view returns (uint256) {
if (rounds[currentRound].endTime <= block.timestamp) {
return 0;
} else {
return rounds[currentRound].endTime - block.timestamp;
}
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
}
|
percentage of pool goes to owner 2.6
|
uint256 public wd;
| 5,380,389 |
[
1,
18687,
434,
2845,
13998,
358,
3410,
4202,
576,
18,
26,
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,
225,
2254,
5034,
1071,
14452,
31,
565,
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
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_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 "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/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/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _value - the sale price of the NFT asset specified by _tokenId
/// @return _receiver - address of who should be sent the royalty payment
/// @return _royaltyAmount - the royalty payment amount for value sale price
function royaltyInfo(uint256 _tokenId, uint256 _value)
external
view
returns (address _receiver, uint256 _royaltyAmount);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import './OpenSea/BaseOpenSea.sol';
/// @title ERC721Ownable
/// @author Simon Fremaux (@dievardump)
contract ERC721Ownable is Ownable, ERC721Enumerable, BaseOpenSea {
/// @notice constructor
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address owner_
) ERC721(name_, symbol_) {
// set contract uri if present
if (bytes(contractURI_).length > 0) {
_setContractURI(contractURI_);
}
// set OpenSea proxyRegistry for gas-less trading if present
if (address(0) != openseaProxyRegistry_) {
_setOpenSeaRegistry(openseaProxyRegistry_);
}
// transferOwnership if needed
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
/// @notice Allows to burn a tokenId
/// @dev Burns `tokenId`. See {ERC721-_burn}. The caller must own `tokenId` or be an approved operator.
/// @param tokenId the tokenId to burn
function burn(uint256 tokenId) public virtual {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721Burnable: caller is not owner nor approved'
);
_burn(tokenId);
}
/// @notice Allows gas-less trading on OpenSea by safelisting the Proxy of the user
/// @dev Override isApprovedForAll to check first if current operator is owner's OpenSea proxy
/// @inheritdoc ERC721
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
// allows gas less trading on OpenSea
if (isOwnersOpenSeaProxy(owner, operator)) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/// @notice Helper for the owner of the contract to set the new contract URI
/// @dev needs to be owner
/// @param contractURI_ new contract URI
function setContractURI(string memory contractURI_) external onlyOwner {
_setContractURI(contractURI_);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/// @title INiftyForge721
/// @author Simon Fremaux (@dievardump)
interface INiftyForge721 {
struct ModuleInit {
address module;
bool enabled;
bool minter;
}
/// @notice totalSupply access
function totalSupply() external view returns (uint256);
/// @notice helper to know if everyone can mint or only minters
function isMintingOpenToAll() external view returns (bool);
/// @notice Toggle minting open to all state
/// @param isOpen if the new state is open or not
function setMintingOpenToAll(bool isOpen) external;
/// @notice Mint token to `to` with `uri`
/// @param to address of recipient
/// @param uri token metadata uri
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uri[i]`
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory tokenIds);
/// @notice Mint `tokenId` to to` with `uri`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it is doing.
/// this also means, this function does not verify _maxTokenId
/// @param to address of recipient
/// @param uri token metadata uri
/// @param tokenId token id wanted
/// @param feeRecipient the recipient of royalties
/// @param feeAmount the royalties amount. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @param transferTo the address to transfer the NFT to after mint
/// this is used when we want to mint the NFT to the creator address
/// before transferring it to a recipient
/// @return tokenId the tokenId
function mint(
address to,
string memory uri,
uint256 tokenId_,
address feeRecipient,
uint256 feeAmount,
address transferTo
) external returns (uint256 tokenId);
/// @notice Mint batch tokens to `to[i]` with `uris[i]`
/// Because not all tokenIds have incremental ids
/// be careful with this function, it does not increment lastTokenId
/// and expects the minter to actually know what it's doing.
/// this also means, this function does not verify _maxTokenId
/// @param to array of address of recipients
/// @param uris array of token metadata uris
/// @param tokenIds array of token ids wanted
/// @param feeRecipients the recipients of royalties for each id
/// @param feeAmounts the royalties amounts for each id. From 0 to 10000
/// where 10000 == 100.00%; 1000 == 10.00%; 250 == 2.50%
/// @return tokenIds the tokenIds
function mintBatch(
address[] memory to,
string[] memory uris,
uint256[] memory tokenIds,
address[] memory feeRecipients,
uint256[] memory feeAmounts
) external returns (uint256[] memory);
/// @notice Attach a module
/// @param module a module to attach
/// @param enabled if the module is enabled by default
/// @param canModuleMint if the module has to be given the minter role
function attachModule(
address module,
bool enabled,
bool canModuleMint
) external;
/// @dev Allows owner to enable a module
/// @param module to enable
/// @param canModuleMint if the module has to be given the minter role
function enableModule(address module, bool canModuleMint) external;
/// @dev Allows owner to disable a module
/// @param module to disable
function disableModule(address module, bool keepListeners) external;
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/introspection/IERC165.sol';
interface INFModule is IERC165 {
/// @notice Called by a Token Registry whenever the module is Attached
/// @return if the attach worked
function onAttach() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Enabled
/// @return if the enabling worked
function onEnable() external returns (bool);
/// @notice Called by a Token Registry whenever the module is Disabled
function onDisable() external;
/// @notice returns an URI with information about the module
/// @return the URI where to find information about the module
function contractURI() external view returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleRenderTokenURI is INFModule {
function renderTokenURI(uint256 tokenId)
external
view
returns (string memory);
function renderTokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleTokenURI is INFModule {
function tokenURI(uint256 tokenId) external view returns (string memory);
function tokenURI(address registry, uint256 tokenId)
external
view
returns (string memory);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './INFModule.sol';
interface INFModuleWithRoyalties is INFModule {
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
/// @notice Return royalties (recipient, basisPoint) for tokenId
/// @dev Contrary to EIP2981, modules are expected to return basisPoint for second parameters
/// This in order to allow right royalties on marketplaces not supporting 2981 (like Rarible)
/// @param registry registry to check id of
/// @param tokenId token to check
/// @return recipient and basisPoint for this tokenId
function royaltyInfo(address registry, uint256 tokenId)
external
view
returns (address recipient, uint256 basisPoint);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
import './INFModule.sol';
/// @title NFBaseModule
/// @author Simon Fremaux (@dievardump)
contract NFBaseModule is INFModule, ERC165 {
using EnumerableSet for EnumerableSet.AddressSet;
EnumerableSet.AddressSet internal _attached;
event NewContractURI(string contractURI);
string private _contractURI;
modifier onlyAttached(address registry) {
require(_attached.contains(registry), '!NOT_ATTACHED!');
_;
}
constructor(string memory contractURI_) {
_setContractURI(contractURI_);
}
/// @inheritdoc INFModule
function contractURI()
external
view
virtual
override
returns (string memory)
{
return _contractURI;
}
/// @inheritdoc INFModule
function onAttach() external virtual override returns (bool) {
if (_attached.add(msg.sender)) {
return true;
}
revert('!ALREADY_ATTACHED!');
}
/// @notice this contract doesn't really care if it's enabled or not
/// since trying to mint on a contract where it's not enabled will fail
/// @inheritdoc INFModule
function onEnable() external pure virtual override returns (bool) {
return true;
}
/// @inheritdoc INFModule
function onDisable() external virtual override {}
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
emit NewContractURI(contractURI_);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title OpenSea contract helper that defines a few things
/// @author Simon Fremaux (@dievardump)
/// @dev This is a contract used to add OpenSea's support
contract BaseOpenSea {
string private _contractURI;
ProxyRegistry private _proxyRegistry;
/// @notice Returns the contract URI function. Used on OpenSea to get details
// about a contract (owner, royalties etc...)
function contractURI() public view returns (string memory) {
return _contractURI;
}
/// @notice Helper for OpenSea gas-less trading
/// @dev Allows to check if `operator` is owner's OpenSea proxy
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function isOwnersOpenSeaProxy(address owner, address operator)
public
view
returns (bool)
{
ProxyRegistry proxyRegistry = _proxyRegistry;
return
// we have a proxy registry address
address(proxyRegistry) != address(0) &&
// current operator is owner's proxy address
address(proxyRegistry.proxies(owner)) == operator;
}
/// @dev Internal function to set the _contractURI
/// @param contractURI_ the new contract uri
function _setContractURI(string memory contractURI_) internal {
_contractURI = contractURI_;
}
/// @dev Internal function to set the _proxyRegistry
/// @param proxyRegistryAddress the new proxy registry address
function _setOpenSeaRegistry(address proxyRegistryAddress) internal {
_proxyRegistry = ProxyRegistry(proxyRegistryAddress);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '../NiftyForge/INiftyForge721.sol';
import '../NiftyForge/Modules/NFBaseModule.sol';
import '../NiftyForge/Modules/INFModuleTokenURI.sol';
import '../NiftyForge/Modules/INFModuleRenderTokenURI.sol';
import '../NiftyForge/Modules/INFModuleWithRoyalties.sol';
import '../v2/AstragladeUpgrade.sol';
import '../ERC2981/IERC2981Royalties.sol';
import '../libraries/Randomize.sol';
import '../libraries/Base64.sol';
/// @title PlanetsModule
/// @author Simon Fremaux (@dievardump)
contract PlanetsModule is
Ownable,
NFBaseModule,
INFModuleTokenURI,
INFModuleRenderTokenURI,
INFModuleWithRoyalties
{
// using ECDSA for bytes32;
using Strings for uint256;
using Randomize for Randomize.Random;
uint256 constant SEED_BOUND = 1000000000;
// emitted when planets are claimed
event PlanetsClaimed(uint256[] tokenIds);
// contract actually holding the planets
address public planetsContract;
// astraglade contract to claim ids from
address public astragladeContract;
// contract operator next to the owner
address public contractOperator =
address(0xD1edDfcc4596CC8bD0bd7495beaB9B979fc50336);
// project base render URI
string private _baseRenderURI;
// whenever all images are uploaded on arweave/ipfs and
// this flag allows to stop all update of images, scripts etc...
bool public frozenMeta;
// base image rendering URI
// before all Planets are minted, images will be stored on our servers since
// they need to be generated after minting
// after all planets are minted, they will all be stored in a decentralized way
// and the _baseImagesURI will be updated
string private _baseImagesURI;
// project description
string internal _description;
address[3] public feeRecipients = [
0xe4657aF058E3f844919c3ee713DF09c3F2949447,
0xb275E5aa8011eA32506a91449B190213224aEc1e,
0xdAC81C3642b520584eD0E743729F238D1c350E62
];
mapping(uint256 => bytes32) public planetSeed;
// saving already taken seeds to ensure not reusing a seed
mapping(uint256 => bool) public seedTaken;
modifier onlyOperator() {
require(isOperator(msg.sender), 'Not operator.');
_;
}
function isOperator(address operator) public view returns (bool) {
return owner() == operator || contractOperator == operator;
}
/// @dev Receive, for royalties
receive() external payable {}
/// @notice constructor
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
/// @param astragladeContract_ the contract holding the astraglades
constructor(
string memory contractURI_,
address owner_,
address planetsContract_,
address astragladeContract_
) NFBaseModule(contractURI_) {
planetsContract = planetsContract_;
astragladeContract = astragladeContract_;
if (address(0) != owner_) {
transferOwnership(owner_);
}
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
interfaceId == type(INFModuleTokenURI).interfaceId ||
interfaceId == type(INFModuleRenderTokenURI).interfaceId ||
interfaceId == type(INFModuleWithRoyalties).interfaceId ||
super.supportsInterface(interfaceId);
}
/// @inheritdoc INFModuleWithRoyalties
function royaltyInfo(uint256 tokenId)
public
view
override
returns (address, uint256)
{
return royaltyInfo(msg.sender, tokenId);
}
/// @inheritdoc INFModuleWithRoyalties
function royaltyInfo(address, uint256)
public
view
override
returns (address receiver, uint256 basisPoint)
{
receiver = address(this);
basisPoint = 1000;
}
/// @inheritdoc INFModuleTokenURI
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
return tokenURI(msg.sender, tokenId);
}
/// @inheritdoc INFModuleTokenURI
function tokenURI(address, uint256 tokenId)
public
view
override
returns (string memory)
{
(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) = getPlanetData(tokenId);
return
string(
abi.encodePacked(
'data:application/json;base64,',
Base64.encode(
abi.encodePacked(
'{"name":"Planet - ',
tokenId.toString(),
'","license":"CC BY-SA 4.0","description":"',
getDescription(),
'","created_by":"Fabin Rasheed","twitter":"@astraglade","image":"',
abi.encodePacked(
getBaseImageURI(),
tokenId.toString()
),
'","seed":"',
seed.toString(),
abi.encodePacked(
'","astragladeSeed":"',
astragladeSeed.toString(),
'","attributes":[',
_generateJSONAttributes(attributes),
'],"animation_url":"',
_renderTokenURI(
seed,
astragladeSeed,
attributes
),
'"}'
)
)
)
)
);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
return renderTokenURI(msg.sender, tokenId);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(address, uint256 tokenId)
public
view
override
returns (string memory)
{
(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) = getPlanetData(tokenId);
return _renderTokenURI(seed, astragladeSeed, attributes);
}
/// @notice Helper returning all data for a Planet
/// @param tokenId the planet id
/// @return the planet seed, the astraglade seed and the planet attributes (the integer form)
function getPlanetData(uint256 tokenId)
public
view
returns (
uint256,
uint256,
uint256[] memory
)
{
require(planetSeed[tokenId] != 0, '!UNKNOWN_TOKEN!');
uint256 seed = uint256(planetSeed[tokenId]) % SEED_BOUND;
uint256[] memory attributes = _getAttributes(seed);
AstragladeUpgrade.AstragladeMeta memory astraglade = AstragladeUpgrade(
payable(astragladeContract)
).getAstraglade(tokenId);
return (seed, astraglade.seed, attributes);
}
/// @notice Returns Metadata for Astraglade id
/// @param tokenId the tokenId we want metadata for
function getAstraglade(uint256 tokenId)
public
view
returns (AstragladeUpgrade.AstragladeMeta memory astraglade)
{
return
AstragladeUpgrade(payable(astragladeContract)).getAstraglade(
tokenId
);
}
/// @notice helper to get the description
function getDescription() public view returns (string memory) {
if (bytes(_description).length == 0) {
return
"Astraglade Planets is an extension of project Astraglade (https://nurecas.com/astraglade). Planets are an interactive and generative 3D art that can be minted for free by anyone who owns an astraglade at [https://astraglade.beyondnft.io/planets/](https://astraglade.beyondnft.io/planets/). When a Planet is minted, the owner's astraglade will orbit forever around the planet that they mint.";
}
return _description;
}
/// @notice helper to get the baseRenderURI
function getBaseRenderURI() public view returns (string memory) {
if (bytes(_baseRenderURI).length == 0) {
return 'ar://JYtFvtxlpyur2Cdpaodmo46XzuTpmp0OwJl13rFUrrg/';
}
return _baseRenderURI;
}
/// @notice helper to get the baseImageURI
function getBaseImageURI() public view returns (string memory) {
if (bytes(_baseImagesURI).length == 0) {
return 'https://astraglade-api.beyondnft.io/planets/images/';
}
return _baseImagesURI;
}
/// @inheritdoc INFModule
function onAttach()
external
virtual
override(INFModule, NFBaseModule)
returns (bool)
{
// only the first attach is accepted, saves a "setPlanetsContract" call
if (planetsContract == address(0)) {
planetsContract = msg.sender;
return true;
}
return false;
}
/// @notice Claim tokenIds[] from the astraglade contract
/// @param tokenIds the tokenIds to claim
function claim(uint256[] calldata tokenIds) external {
address operator = msg.sender;
// saves some reads
address astragladeContract_ = astragladeContract;
address planetsContract_ = planetsContract;
for (uint256 i; i < tokenIds.length; i++) {
_claim(
operator,
tokenIds[i],
astragladeContract_,
planetsContract_
);
}
}
/// @notice Allows to freeze any metadata update
function freezeMeta() external onlyOperator {
frozenMeta = true;
}
/// @notice sets contract uri
/// @param newURI the new uri
function setContractURI(string memory newURI) external onlyOperator {
_setContractURI(newURI);
}
/// @notice sets planets contract
/// @param planetsContract_ the contract containing planets
function setPlanetsContract(address planetsContract_)
external
onlyOperator
{
planetsContract = planetsContract_;
}
/// @notice helper to set the description
/// @param newDescription the new description
function setDescription(string memory newDescription)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_description = newDescription;
}
/// @notice helper to set the baseRenderURI
/// @param newRenderURI the new renderURI
function setBaseRenderURI(string memory newRenderURI)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_baseRenderURI = newRenderURI;
}
/// @notice helper to set the baseImageURI
/// @param newBaseImagesURI the new base image URI
function setBaseImagesURI(string memory newBaseImagesURI)
external
onlyOperator
{
require(frozenMeta == false, '!META_FROZEN!');
_baseImagesURI = newBaseImagesURI;
}
/// @dev Owner withdraw balance function
function withdraw() external onlyOperator {
address[3] memory feeRecipients_ = feeRecipients;
uint256 balance_ = address(this).balance;
payable(address(feeRecipients_[0])).transfer((balance_ * 30) / 100);
payable(address(feeRecipients_[1])).transfer((balance_ * 35) / 100);
payable(address(feeRecipients_[2])).transfer(address(this).balance);
}
/// @notice helper to set the fee recipient at `index`
/// @param newFeeRecipient the new address
/// @param index the index to edit
function setFeeRecipient(address newFeeRecipient, uint8 index)
external
onlyOperator
{
require(index < feeRecipients.length, '!INDEX_OVERFLOW!');
require(newFeeRecipient != address(0), '!INVALID_ADDRESS!');
feeRecipients[index] = newFeeRecipient;
}
/// @notice Helper for an operator to change the current operator address
/// @param newOperator the new operator
function setContractOperator(address newOperator) external onlyOperator {
contractOperator = newOperator;
}
/// @dev Allows to claim a tokenId; the Planet will always be minted to the owner of the Astraglade
/// @param operator the one launching the claim (needs to be owner or approved on the Astraglade)
/// @param tokenId the Astraglade tokenId to claim
/// @param astragladeContract_ the Astraglade contract to check ownership
/// @param planetsContract_ the Planet contract (where to mint the tokens)
function _claim(
address operator,
uint256 tokenId,
address astragladeContract_,
address planetsContract_
) internal {
AstragladeUpgrade astraglade = AstragladeUpgrade(
payable(astragladeContract_)
);
address owner_ = astraglade.ownerOf(tokenId);
// verify that the operator has the right to claim
require(
owner_ == operator ||
astraglade.isApprovedForAll(owner_, operator) ||
astraglade.getApproved(tokenId) == operator,
'!NOT_AUTHORIZED!'
);
// mint
INiftyForge721 planets = INiftyForge721(planetsContract_);
// always mint to owner_, not to operator
planets.mint(owner_, '', tokenId, address(0), 0, address(0));
// creates a seed
bytes32 seed;
do {
seed = _generateSeed(
tokenId,
block.timestamp,
owner_,
blockhash(block.number - 1)
);
} while (seedTaken[uint256(seed) % SEED_BOUND]);
planetSeed[tokenId] = seed;
// ensure we won't have two seeds rendering the same planet
seedTaken[uint256(seed) % SEED_BOUND] = true;
}
/// @dev Calculate next seed using a few on chain data
/// @param tokenId tokenId
/// @param timestamp current block timestamp
/// @param operator current operator
/// @param blockHash last block hash
/// @return a new bytes32 seed
function _generateSeed(
uint256 tokenId,
uint256 timestamp,
address operator,
bytes32 blockHash
) internal view returns (bytes32) {
return
keccak256(
abi.encodePacked(
tokenId,
timestamp,
operator,
blockHash,
block.coinbase,
block.difficulty,
tx.gasprice
)
);
}
/// @notice generates the attributes values according to seed
/// @param seed the seed to generate the values
/// @return attributes an array of attributes (integers)
function _getAttributes(uint256 seed)
internal
pure
returns (uint256[] memory attributes)
{
Randomize.Random memory random = Randomize.Random({seed: seed});
// remember, all numbers returned by randomBetween are
// multiplicated by 1000, because solidity has no decimals
// so we will divide all those numbers later
attributes = new uint256[](6);
// density
attributes[0] = random.randomBetween(10, 200);
// radius
attributes[1] = random.randomBetween(5, 15);
// cube planet
attributes[2] = random.randomBetween(0, 5000);
if (attributes[2] < 20000) {
// set radius = 10 if cube
attributes[1] = 10000;
}
// shade - remember to actually change 1 into -1 in the HTML
attributes[3] = random.randomBetween(0, 2) < 1000 ? 0 : 1;
// rings
// if cube, 2 or 3 rings
if (attributes[2] < 20000) {
attributes[4] = random.randomBetween(2, 4) / 1000;
} else {
// else 30% chances to have rings (1, 2 and 3)
attributes[4] = random.randomBetween(0, 10) / 1000;
// if more than 3, then none.
if (attributes[4] > 3) {
attributes[4] = 0;
}
}
// moons, 0, 1, 2 or 3
attributes[5] = random.randomBetween(0, 4) / 1000;
}
/// @notice Generates the JSON string from the attributes values
/// @param attributes the attributes values
/// @return jsonAttributes, the string for attributes
function _generateJSONAttributes(uint256[] memory attributes)
internal
pure
returns (string memory)
{
bytes memory coma = bytes(',');
// Terrain
bytes memory jsonAttributes = abi.encodePacked(
_makeAttributes(
'Terrain',
attributes[0] < 50000 ? 'Dense' : 'Sparse'
),
coma
);
// Size
if (attributes[1] < 8000) {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Tiny'),
coma
);
} else if (attributes[1] < 12000) {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Medium'),
coma
);
} else {
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes('Size', 'Giant'),
coma
);
}
// Form
jsonAttributes = abi.encodePacked(
jsonAttributes,
_makeAttributes(
'Form',
attributes[2] < 20000 ? 'Tesseract' : 'Geo'
),
coma,
_makeAttributes('Shade', attributes[3] == 0 ? 'Vibrant' : 'Simple'),
coma,
_makeAttributes('Rings', attributes[4].toString()),
coma,
_makeAttributes('Moons', attributes[5].toString())
);
return string(jsonAttributes);
}
function _makeAttributes(string memory name_, string memory value)
internal
pure
returns (bytes memory)
{
return
abi.encodePacked(
'{"trait_type":"',
name_,
'","value":"',
value,
'"}'
);
}
/// @notice returns the URL to render the Planet
/// @param seed the planet seed
/// @param astragladeSeed the astraglade seed
/// @param attributes all attributes needed for the planets
/// @return the URI to render the planet
function _renderTokenURI(
uint256 seed,
uint256 astragladeSeed,
uint256[] memory attributes
) internal view returns (string memory) {
bytes memory coma = bytes(',');
bytes memory attrs = abi.encodePacked(
attributes[0].toString(),
coma,
attributes[1].toString(),
coma,
attributes[2].toString(),
coma
);
return
string(
abi.encodePacked(
getBaseRenderURI(),
'?seed=',
seed.toString(),
'&astragladeSeed=',
astragladeSeed.toString(),
'&attributes=',
abi.encodePacked(
attrs,
attributes[3].toString(),
coma,
attributes[4].toString(),
coma,
attributes[5].toString()
)
)
);
}
}
pragma solidity ^0.8.0;
// SPDX-License-Identifier: MIT
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// small library to randomize using (min, max, seed)
// all number returned are considered with 3 decimals
library Randomize {
struct Random {
uint256 seed;
}
/// @notice This function uses seed to return a pseudo random interger between 0 and 1000
/// Because solidity has no decimal points, the number is considered to be [0, 0.999]
/// @param random the random seed
/// @return the pseudo random number (with 3 decimal basis)
function randomDec(Random memory random) internal pure returns (uint256) {
random.seed ^= random.seed << 13;
random.seed ^= random.seed >> 17;
random.seed ^= random.seed << 5;
return ((random.seed < 0 ? ~random.seed + 1 : random.seed) % 1000);
}
/// @notice return a number between [min, max[, multiplicated by 1000 (for 3 decimal basis)
/// @param random the random seed
/// @return the pseudo random number (with 3 decimal basis)
function randomBetween(
Random memory random,
uint256 min,
uint256 max
) internal pure returns (uint256) {
return min * 1000 + (max - min) * Randomize.randomDec(random);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol';
import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '../ERC721Ownable.sol';
import '../ERC2981/IERC2981Royalties.sol';
import './IOldMetaHolder.sol';
/// @title AstragladeUpgrade
/// @author Simon Fremaux (@dievardump)
contract AstragladeUpgrade is
IERC2981Royalties,
ERC721Ownable,
IERC721Receiver
{
using ECDSA for bytes32;
using Strings for uint256;
// emitted when an Astraglade has been upgrade
event AstragladeUpgraded(address indexed operator, uint256 indexed tokenId);
// emitted when a token owner asks for a metadata update (image or signature)
// because of rendering error
event RequestUpdate(address indexed operator, uint256 indexed tokenId);
struct MintingOrder {
address to;
uint256 expiration;
uint256 seed;
string signature;
string imageHash;
}
struct AstragladeMeta {
uint256 seed;
string signature;
string imageHash;
}
// start at the old contract last token Id minted
uint256 public lastTokenId = 84;
// signer that signs minting orders
address public mintSigner;
// how long before an order expires
uint256 public expiration;
// old astraglade contract to allow upgrade to new token
address public oldAstragladeContract;
// contract that holds metadata of previous contract Astraglades
address public oldMetaHolder;
// contract operator next to the owner
address public contractOperator =
address(0xD1edDfcc4596CC8bD0bd7495beaB9B979fc50336);
// max supply
uint256 constant MAX_SUPPLY = 5555;
// price
uint256 constant PRICE = 0.0888 ether;
// project base render URI
string private _baseRenderURI;
// project description
string internal _description;
// list of Astraglades
mapping(uint256 => AstragladeMeta) internal _astraglades;
// saves if a minting order was already used or not
mapping(bytes32 => uint256) public messageToTokenId;
// request updates
mapping(uint256 => bool) public requestUpdates;
// remaining giveaways
uint256 public remainingGiveaways = 100;
// user giveaways
mapping(address => uint8) public giveaways;
// Petri already redeemed
mapping(uint256 => bool) public petriRedeemed;
address public artBlocks;
address[3] public feeRecipients = [
0xe4657aF058E3f844919c3ee713DF09c3F2949447,
0xb275E5aa8011eA32506a91449B190213224aEc1e,
0xdAC81C3642b520584eD0E743729F238D1c350E62
];
modifier onlyOperator() {
require(isOperator(msg.sender), 'Not operator.');
_;
}
function isOperator(address operator) public view returns (bool) {
return owner() == operator || contractOperator == operator;
}
/// @notice constructor
/// @param name_ name of the contract (see ERC721)
/// @param symbol_ symbol of the contract (see ERC721)
/// @param contractURI_ The contract URI (containing its metadata) - can be empty ""
/// @param openseaProxyRegistry_ OpenSea's proxy registry to allow gas-less listings - can be address(0)
/// @param mintSigner_ Address of the wallet used to sign minting orders
/// @param owner_ Address to whom transfer ownership (can be address(0), then owner is deployer)
constructor(
string memory name_,
string memory symbol_,
string memory contractURI_,
address openseaProxyRegistry_,
address mintSigner_,
address owner_,
address oldAstragladeContract_,
address oldMetaHolder_,
address artBlocks_
)
ERC721Ownable(
name_,
symbol_,
contractURI_,
openseaProxyRegistry_,
owner_
)
{
mintSigner = mintSigner_;
oldAstragladeContract = oldAstragladeContract_;
oldMetaHolder = oldMetaHolder_;
artBlocks = artBlocks_;
}
/// @notice Mint one token using a minting order
/// @dev mintingSignature must be a signature that matches `mintSigner` for `mintingOrder`
/// @param mintingOrder the minting order
/// @param mintingSignature signature for the mintingOrder
/// @param petriId petri id to redeem if owner and not already redeemed the free AG
function mint(
MintingOrder memory mintingOrder,
bytes memory mintingSignature,
uint256 petriId
) external payable {
bytes32 message = hashMintingOrder(mintingOrder)
.toEthSignedMessageHash();
address sender = msg.sender;
require(
message.recover(mintingSignature) == mintSigner,
'Wrong minting order signature.'
);
require(
mintingOrder.expiration >= block.timestamp,
'Minting order expired.'
);
require(
mintingOrder.to == sender,
'Minting order for another address.'
);
require(mintingOrder.seed != 0, 'Seed can not be 0');
require(messageToTokenId[message] == 0, 'Token already minted.');
uint256 tokenId = lastTokenId + 1;
require(tokenId <= MAX_SUPPLY, 'Max supply already reached.');
uint256 mintingCost = PRICE;
// For Each Petri (https://artblocks.io/project/67/) created by Fabin on artblocks.io
// the owner can claim a free Astraglade
// After a Petri was used, it CAN NOT be used again to claim another Astraglade
if (petriId >= 67000000 && petriId < 67000200) {
require(
// petri was not redeemed already
petriRedeemed[petriId] == false &&
// msg.sender is Petri owner
ERC721(artBlocks).ownerOf(petriId) == sender,
'Petri already redeemed or not owner'
);
petriRedeemed[petriId] = true;
mintingCost = 0;
} else if (giveaways[sender] > 0) {
// if the user has some free mints
giveaways[sender]--;
mintingCost = 0;
}
require(
msg.value == mintingCost || isOperator(sender),
'Incorrect value.'
);
lastTokenId = tokenId;
messageToTokenId[message] = tokenId;
_astraglades[tokenId] = AstragladeMeta({
seed: mintingOrder.seed,
signature: mintingOrder.signature,
imageHash: mintingOrder.imageHash
});
_safeMint(mintingOrder.to, tokenId, '');
}
/// @inheritdoc ERC165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return
ERC721Enumerable.supportsInterface(interfaceId) ||
interfaceId == type(IERC2981Royalties).interfaceId;
}
/// @notice Helper to get the price
/// @return the price to mint
function getPrice() external pure returns (uint256) {
return PRICE;
}
/// @notice tokenURI override that returns a data:json application
/// @inheritdoc ERC721
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
AstragladeMeta memory astraglade = getAstraglade(tokenId);
string memory astraType;
if (tokenId <= 10) {
astraType = 'Universa';
} else if (tokenId <= 100) {
astraType = 'Galactica';
} else if (tokenId <= 1000) {
astraType = 'Nebula';
} else if (tokenId <= 2500) {
astraType = 'Meteora';
} else if (tokenId <= 5554) {
astraType = 'Solaris';
} else {
astraType = 'Quanta';
}
return
string(
abi.encodePacked(
'data:application/json;utf8,{"name":"Astraglade - ',
tokenId.toString(),
' - ',
astraType,
'","license":"CC BY-SA 4.0","description":"',
getDescription(),
'","created_by":"Fabin Rasheed","twitter":"@astraglade","image":"ipfs://ipfs/',
astraglade.imageHash,
'","seed":"',
astraglade.seed.toString(),
'","signature":"',
astraglade.signature,
'","animation_url":"',
renderTokenURI(tokenId),
'"}'
)
);
}
/// @notice function that returns a string that can be used to render the current token
/// @param tokenId tokenId
/// @return the URI to render token
function renderTokenURI(uint256 tokenId)
public
view
returns (string memory)
{
AstragladeMeta memory astraglade = getAstraglade(tokenId);
return
string(
abi.encodePacked(
getBaseRenderURI(),
'?seed=',
astraglade.seed.toString(),
'&signature=',
astraglade.signature
)
);
}
/// @notice Returns Metadata for Astraglade id
/// @param tokenId the tokenId we want metadata for
function getAstraglade(uint256 tokenId)
public
view
returns (AstragladeMeta memory astraglade)
{
require(_exists(tokenId), 'Astraglade: nonexistent token');
// if the metadata are in this contract
if (_astraglades[tokenId].seed != 0) {
astraglade = _astraglades[tokenId];
} else {
// or in the old one
(
uint256 seed,
string memory signature,
string memory imageHash
) = IOldMetaHolder(oldMetaHolder).get(tokenId);
astraglade.seed = seed;
astraglade.signature = signature;
astraglade.imageHash = imageHash;
}
}
/// @notice helper to get the description
function getDescription() public view returns (string memory) {
if (bytes(_description).length == 0) {
return
'Astraglade is an interactive, generative, 3D collectible project. Astraglades are collected through a unique social collection mechanism. Each version of Astraglade can be signed with a signature which will remain in the artwork forever.';
}
return _description;
}
/// @notice helper to set the description
/// @param newDescription the new description
function setDescription(string memory newDescription)
external
onlyOperator
{
_description = newDescription;
}
/// @notice helper to get the base expiration time
function getExpiration() public view returns (uint256) {
if (expiration == 0) {
return 15 * 60;
}
return expiration;
}
/// @notice helper to set the expiration
/// @param newExpiration the new expiration
function setExpiration(uint256 newExpiration) external onlyOperator {
expiration = newExpiration;
}
/// @notice helper to get the baseRenderURI
function getBaseRenderURI() public view returns (string memory) {
if (bytes(_baseRenderURI).length == 0) {
return 'ipfs://ipfs/QmP85DSrtLAxSBnct9iUr7qNca43F3E4vuG6Jv5aoTh9w7';
}
return _baseRenderURI;
}
/// @notice helper to set the baseRenderURI
/// @param newRenderURI the new renderURI
function setBaseRenderURI(string memory newRenderURI)
external
onlyOperator
{
_baseRenderURI = newRenderURI;
}
/// @notice Helper to do giveaways - there can only be `remainingGiveaways` giveaways given all together
/// @param winner the giveaway winner
/// @param count how many we giveaway to recipient
function giveaway(address winner, uint8 count) external onlyOperator {
require(remainingGiveaways >= count, 'Giveaway limit reached');
remainingGiveaways -= count;
giveaways[winner] += count;
}
/// @dev Receive, for royalties
receive() external payable {}
/// @dev Owner withdraw balance function
function withdraw() external onlyOperator {
address[3] memory feeRecipients_ = feeRecipients;
uint256 balance_ = address(this).balance;
payable(address(feeRecipients_[0])).transfer((balance_ * 30) / 100);
payable(address(feeRecipients_[1])).transfer((balance_ * 35) / 100);
payable(address(feeRecipients_[2])).transfer(address(this).balance);
}
/// @notice helper to set the fee recipient at `index`
/// @param newFeeRecipient the new address
/// @param index the index to edit
function setFeeRecipient(address newFeeRecipient, uint8 index)
external
onlyOperator
{
require(index < feeRecipients.length, 'Index too high.');
require(newFeeRecipient != address(0), 'Invalid address.');
feeRecipients[index] = newFeeRecipient;
}
/// @notice 10% royalties going to this contract
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = address(this);
royaltyAmount = (value * 1000) / 10000;
}
/// @notice Hash the Minting Order so it can be signed by the signer
/// @param mintingOrder the minting order
/// @return the hash to sign
function hashMintingOrder(MintingOrder memory mintingOrder)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(mintingOrder));
}
/// @notice Helper for the owner to change current minting signer
/// @dev needs to be owner
/// @param mintSigner_ new signer
function setMintingSigner(address mintSigner_) external onlyOperator {
require(mintSigner_ != address(0), 'Invalid Signer address.');
mintSigner = mintSigner_;
}
/// @notice Helper for an operator to change the current operator address
/// @param newOperator the new operator
function setContractOperator(address newOperator) external onlyOperator {
contractOperator = newOperator;
}
/// @notice Helper for the owner to change the oldMetaHolder
/// @dev needs to be owner
/// @param oldMetaHolder_ new oldMetaHolder address
function setOldMetaHolder(address oldMetaHolder_) external onlyOperator {
require(oldMetaHolder_ != address(0), 'Invalid Contract address.');
oldMetaHolder = oldMetaHolder_;
}
/// @notice Helpers that returns the MintingOrder plus the message to sign
/// @param to the address of the creator
/// @param seed the seed
/// @param signature the signature
/// @param imageHash image hash
/// @return mintingOrder and message to hash
function createMintingOrder(
address to,
uint256 seed,
string memory signature,
string memory imageHash
)
external
view
returns (MintingOrder memory mintingOrder, bytes32 message)
{
mintingOrder = MintingOrder({
to: to,
expiration: block.timestamp + getExpiration(),
seed: seed,
signature: signature,
imageHash: imageHash
});
message = hashMintingOrder(mintingOrder);
}
/// @notice returns a tokenId from an mintingOrder, used to know if already minted
/// @param mintingOrder the minting order to check
/// @return an integer. 0 if not minted, else the tokenId
function tokenIdFromOrder(MintingOrder memory mintingOrder)
external
view
returns (uint256)
{
bytes32 message = hashMintingOrder(mintingOrder)
.toEthSignedMessageHash();
return messageToTokenId[message];
}
/// @notice Allows an owner to request a metadata update.
/// Because Astraglade are generated from a backend it can happen that a bug
/// blocks the generation of the image OR that a signature with special characters stops the
/// token from working.
/// This method allows a user to ask for regeneration of the image / signature update
/// A contract operator can then update imageHash and / or signature
/// @param tokenId the tokenId to update
function requestMetaUpdate(uint256 tokenId) external {
require(ownerOf(tokenId) == msg.sender, 'Not token owner.');
requestUpdates[tokenId] = true;
emit RequestUpdate(msg.sender, tokenId);
}
/// @notice Allows an operator of this contract to update a tokenId metadata (signature or image hash)
/// after it was requested by its owner.
/// This is only used in the case the generation of the Preview image did fail
/// in some way or if the signature has special characters that stops the token from working
/// @param tokenId the tokenId to update
/// @param newImageHash the new imageHash (can be empty)
/// @param newSignature the new signature (can be empty)
function updateMeta(
uint256 tokenId,
string memory newImageHash,
string memory newSignature
) external onlyOperator {
require(
requestUpdates[tokenId] == true,
'No update request for token.'
);
requestUpdates[tokenId] = false;
// get the current Astraglade data
// for ids 1-82 it can come from oldMetaHolder
AstragladeMeta memory astraglade = getAstraglade(tokenId);
if (bytes(newImageHash).length > 0) {
astraglade.imageHash = newImageHash;
}
if (bytes(newSignature).length > 0) {
astraglade.signature = newSignature;
}
// save the new state
_astraglades[tokenId] = astraglade;
}
/// @notice function used to allow upgrade of old contract Astraglade to this one.
/// @inheritdoc IERC721Receiver
function onERC721Received(
address,
address from,
uint256 tokenId,
bytes calldata
) external override returns (bytes4) {
require(msg.sender == oldAstragladeContract, 'Only old Astraglades.');
// mint tokenId to from
_mint(from, tokenId);
// burn old tokenId
ERC721Burnable(msg.sender).burn(tokenId);
emit AstragladeUpgraded(from, tokenId);
return 0x150b7a02;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IOldMetaHolder
/// @author Simon Fremaux (@dievardump)
interface IOldMetaHolder {
function get(uint256 tokenId)
external
pure
returns (
uint256,
string memory,
string memory
);
}
|
@dev Allows to claim a tokenId; the Planet will always be minted to the owner of the Astraglade @param operator the one launching the claim (needs to be owner or approved on the Astraglade) @param tokenId the Astraglade tokenId to claim @param astragladeContract_ the Astraglade contract to check ownership @param planetsContract_ the Planet contract (where to mint the tokens) verify that the operator has the right to claim mint always mint to owner_, not to operator creates a seed
|
function _claim(
address operator,
uint256 tokenId,
address astragladeContract_,
address planetsContract_
) internal {
AstragladeUpgrade astraglade = AstragladeUpgrade(
payable(astragladeContract_)
);
address owner_ = astraglade.ownerOf(tokenId);
require(
owner_ == operator ||
astraglade.isApprovedForAll(owner_, operator) ||
astraglade.getApproved(tokenId) == operator,
'!NOT_AUTHORIZED!'
);
INiftyForge721 planets = INiftyForge721(planetsContract_);
planets.mint(owner_, '', tokenId, address(0), 0, address(0));
bytes32 seed;
do {
seed = _generateSeed(
tokenId,
block.timestamp,
owner_,
blockhash(block.number - 1)
);
} while (seedTaken[uint256(seed) % SEED_BOUND]);
planetSeed[tokenId] = seed;
}
| 164,152 |
[
1,
19132,
358,
7516,
279,
1147,
548,
31,
326,
12540,
278,
903,
3712,
506,
312,
474,
329,
358,
326,
3410,
434,
326,
432,
701,
346,
80,
2486,
225,
3726,
326,
1245,
8037,
310,
326,
7516,
261,
20600,
358,
506,
3410,
578,
20412,
603,
326,
432,
701,
346,
80,
2486,
13,
225,
1147,
548,
326,
432,
701,
346,
80,
2486,
1147,
548,
358,
7516,
225,
487,
313,
346,
80,
2486,
8924,
67,
326,
432,
701,
346,
80,
2486,
6835,
358,
866,
23178,
225,
4995,
2413,
8924,
67,
326,
12540,
278,
6835,
261,
6051,
358,
312,
474,
326,
2430,
13,
3929,
716,
326,
3726,
711,
326,
2145,
358,
7516,
312,
474,
3712,
312,
474,
358,
3410,
67,
16,
486,
358,
3726,
3414,
279,
5009,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
389,
14784,
12,
203,
3639,
1758,
3726,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1758,
487,
313,
346,
80,
2486,
8924,
67,
16,
203,
3639,
1758,
4995,
2413,
8924,
67,
203,
565,
262,
2713,
288,
203,
3639,
432,
701,
346,
80,
2486,
10784,
487,
313,
346,
80,
2486,
273,
432,
701,
346,
80,
2486,
10784,
12,
203,
5411,
8843,
429,
12,
345,
313,
346,
80,
2486,
8924,
67,
13,
203,
3639,
11272,
203,
3639,
1758,
3410,
67,
273,
487,
313,
346,
80,
2486,
18,
8443,
951,
12,
2316,
548,
1769,
203,
203,
3639,
2583,
12,
203,
5411,
3410,
67,
422,
3726,
747,
203,
7734,
487,
313,
346,
80,
2486,
18,
291,
31639,
1290,
1595,
12,
8443,
67,
16,
3726,
13,
747,
203,
7734,
487,
313,
346,
80,
2486,
18,
588,
31639,
12,
2316,
548,
13,
422,
3726,
16,
203,
5411,
11817,
4400,
67,
28383,
5124,
203,
3639,
11272,
203,
203,
3639,
2120,
2136,
93,
1290,
908,
27,
5340,
4995,
2413,
273,
2120,
2136,
93,
1290,
908,
27,
5340,
12,
7088,
2413,
8924,
67,
1769,
203,
203,
3639,
4995,
2413,
18,
81,
474,
12,
8443,
67,
16,
10226,
1147,
548,
16,
1758,
12,
20,
3631,
374,
16,
1758,
12,
20,
10019,
203,
203,
3639,
1731,
1578,
5009,
31,
203,
3639,
741,
288,
203,
5411,
5009,
273,
389,
7163,
12702,
12,
203,
7734,
1147,
548,
16,
203,
7734,
1203,
18,
5508,
16,
203,
7734,
3410,
67,
16,
203,
7734,
1203,
2816,
12,
2629,
18,
2696,
300,
404,
13,
203,
5411,
11272,
2
] |
./full_match/10/0x3c0FFAca566fCcfD9Cc95139FEF6CBA143795963/sources/contracts/saddle/Swap.sol
|
* @notice Remove liquidity from the pool, weighted differently than the pool's current balances. Withdraw fee that decays linearly over period of 4 weeks since last deposit will apply. @param amounts how much of each token to withdraw @param maxBurnAmount the max LP token provider is willing to pay to remove liquidity. Useful as a front-running mitigation. @param deadline latest timestamp to accept this transaction @return amount of LP tokens burned/ whenNotPaused
|
function removeLiquidityImbalance(
uint256[] calldata amounts,
uint256 maxBurnAmount,
uint256 deadline
)
external
nonReentrant
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount);
}
| 3,780,250 |
[
1,
3288,
4501,
372,
24237,
628,
326,
2845,
16,
13747,
23621,
2353,
326,
2845,
1807,
783,
324,
26488,
18,
3423,
9446,
14036,
716,
2109,
8271,
9103,
715,
1879,
3879,
434,
1059,
17314,
3241,
1142,
443,
1724,
903,
2230,
18,
225,
30980,
3661,
9816,
434,
1517,
1147,
358,
598,
9446,
225,
943,
38,
321,
6275,
326,
943,
511,
52,
1147,
2893,
353,
903,
310,
358,
8843,
358,
1206,
4501,
372,
24237,
18,
19256,
487,
279,
6641,
17,
8704,
20310,
360,
367,
18,
225,
14096,
4891,
2858,
358,
2791,
333,
2492,
327,
3844,
434,
511,
52,
2430,
18305,
329,
19,
1347,
1248,
28590,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
1206,
48,
18988,
24237,
1170,
12296,
12,
203,
3639,
2254,
5034,
8526,
745,
892,
30980,
16,
203,
3639,
2254,
5034,
943,
38,
321,
6275,
16,
203,
3639,
2254,
5034,
14096,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1661,
426,
8230,
970,
203,
3639,
14096,
1564,
12,
22097,
1369,
13,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
7720,
3245,
18,
4479,
48,
18988,
24237,
1170,
12296,
12,
8949,
87,
16,
943,
38,
321,
6275,
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
] |
pragma solidity ^0.4.24;
contract Cat {
struct AdoptionCat {
string name;
uint8 age;
string gender;
string town;
string descr;
string imageHash;
string organization;
address catOwner;
bool isAdopted;
}
address private owner;
string[] private organizations; // All registered organizations
mapping (string => AdoptionCat[]) adoptionCats; // Organization - Cats :))
mapping(string => uint) indexes; // Organization name - index
mapping (address => uint) donations;
uint public allDonations;
// Set Owner of Contract to be current Sender
constructor() public {
owner == msg.sender;
}
/**
* Modifiers and Events
**/
modifier isOwner() {
require(owner == msg.sender);
_;
}
modifier catExists(string _organization, uint _index) {
require(adoptionCats[_organization].length > 0);
require(_index <= indexes[_organization]);
_;
}
modifier canAdopt(string _organization, uint _index) {
require(adoptionCats[_organization][_index].isAdopted == false);
// require(_cat.catOwner != msg.sender);
_;
}
// Event for Donation made
event Donation(address _from, uint _amount);
event Adopt(address _owner);
/**
* Donation
**/
function donate(uint _amount) public payable {
donations[msg.sender] += _amount;
allDonations += _amount;
emit Donation(msg.sender, _amount);
}
// TODO - Transfer donations?
/**
* Get information about cats
**/
function info(string _organization, uint _index)
view public catExists(_organization, _index)
returns(string, uint, string, string, string, string) {
return (adoptionCats[_organization][_index].name,
adoptionCats[_organization][_index].age,
adoptionCats[_organization][_index].gender,
adoptionCats[_organization][_index].town,
adoptionCats[_organization][_index].descr,
adoptionCats[_organization][_index].organization);
}
function isAdopted(string _organization, uint _index)
view public catExists(_organization, _index)
returns (bool) {
return adoptionCats[_organization][_index].isAdopted;
}
function imageHash(string _organization, uint _index)
view public catExists(_organization, _index)
returns (string) {
return adoptionCats[_organization][_index].imageHash;
}
function catOwner(string _organization, uint _index)
view public catExists(_organization, _index)
returns (address) {
return adoptionCats[_organization][_index].catOwner;
}
/**
* Adoption
**/
// Add Cat available for Adoption
function add(string _name, uint8 _age, string _gender, string _town,
string _descr, string _imageHash, string _organization) public {
AdoptionCat memory cat;
cat.name = _name;
cat.age = _age;
cat.gender = _gender;
cat.town = _town;
cat.descr = _descr;
cat.imageHash = _imageHash;
cat.organization = _organization;
cat.catOwner = msg.sender;
cat.isAdopted = false;
// Check if we have already registered organization. If not, add it.
if (adoptionCats[_organization].length == 0) {
organizations.push(_organization);
}
// Add current cat to adoptionCats
if (adoptionCats[_organization].length == indexes[_organization]) {
adoptionCats[_organization].push(cat);
indexes[_organization] += 1; // Index and keep the organization
} else {
adoptionCats[_organization][indexes[_organization]] = cat;
indexes[_organization] += 1;
}
}
function adopt(string _organization, uint _index)
public catExists(_organization, _index) canAdopt(_organization, _index) {
adoptionCats[_organization][_index].isAdopted = true;
adoptionCats[_organization][_index].catOwner = msg.sender;
emit Adopt(msg.sender);
}
}
|
Organization - Cats :))
|
mapping (string => AdoptionCat[]) adoptionCats;
| 5,452,627 |
[
1,
8113,
300,
385,
2323,
294,
3719,
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,
2874,
261,
1080,
516,
432,
2896,
375,
11554,
63,
5717,
1261,
3482,
39,
2323,
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
] |
./partial_match/1/0x336A24FC03c93101D4e31160c27EeaEdc34BE01d/sources/XLand.sol
|
* @title Standard ERC20 token @dev Implementation of the basic standard token./
|
contract ERC20Token is IERC20Token {
using SafeMath for uint256;
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowed;
uint256 _totalSupply;
string private _name;
string private _symbol;
uint256 private _decimals;
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
constructor(string memory name, string memory symbol,uint256 total, uint256 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply = total.mul(10**decimals);
_balances[msg.sender] = _totalSupply;
}
function name() public view returns(string memory) {
return _name;
}
function symbol() public view returns(string memory) {
return _symbol;
}
function decimals() public view returns(uint) {
return _decimals;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
function transfer(address to, uint256 value) public returns (bool) {
require(value <= _balances[msg.sender],"not enough balance!!");
require(to != address(0),"params can't be empty(0)");
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0),"approve address can't be empty(0)!!!");
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
)
public
returns (bool)
{
require(value <= _balances[from],"balance not enough!!");
require(value <= _allowed[from][msg.sender],"allow not enough");
require(to != address(0),"target address can't be empty(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;
}
}
| 4,295,592 |
[
1,
8336,
4232,
39,
3462,
1147,
225,
25379,
434,
326,
5337,
4529,
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,
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,
16351,
4232,
39,
3462,
1345,
353,
467,
654,
39,
3462,
1345,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
2874,
261,
2867,
516,
2254,
5034,
13,
389,
70,
26488,
31,
203,
203,
225,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
389,
8151,
31,
203,
203,
225,
2254,
5034,
389,
4963,
3088,
1283,
31,
203,
225,
533,
3238,
389,
529,
31,
203,
225,
533,
3238,
389,
7175,
31,
203,
225,
2254,
5034,
3238,
389,
31734,
31,
203,
203,
282,
871,
12279,
12,
203,
565,
1758,
8808,
628,
16,
203,
565,
1758,
8808,
358,
16,
203,
565,
2254,
5034,
460,
203,
225,
11272,
203,
203,
225,
871,
1716,
685,
1125,
12,
203,
565,
1758,
8808,
3410,
16,
203,
565,
1758,
8808,
17571,
264,
16,
203,
565,
2254,
5034,
460,
203,
225,
11272,
203,
203,
225,
3885,
12,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
11890,
5034,
2078,
16,
2254,
5034,
15105,
13,
1071,
288,
203,
565,
389,
529,
273,
508,
31,
203,
565,
389,
7175,
273,
3273,
31,
203,
565,
389,
31734,
273,
15105,
31,
203,
565,
389,
4963,
3088,
1283,
273,
2078,
18,
16411,
12,
2163,
636,
31734,
1769,
203,
565,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
225,
289,
203,
203,
225,
445,
508,
1435,
1071,
1476,
1135,
12,
1080,
3778,
13,
288,
203,
565,
327,
389,
529,
31,
203,
225,
289,
203,
203,
225,
445,
3273,
1435,
1071,
1476,
1135,
12,
1080,
3778,
13,
288,
2
] |
./full_match/1/0x26a70759222b1842A7c72215F64C7FdE8Db24856/sources/vesperVault.sol
|
@dev Recalls an amount of funds from a vault to this contract. @param _vaultId the identifier of the recall funds from. @param _amount the amount of funds to recall from the vault. @return the amount of funds that were recalled from the vault to this contract and the decreased vault value.
|
function _recallFunds(uint256 _vaultId, uint256 _amount) internal returns (uint256, uint256) {
require(emergencyExit || msg.sender == governance || _vaultId != _vaults.lastIndex(), "YumVesperVaultD8: not an emergency, not governance, and user does not have permission to recall funds from active vault");
VaultV2.Data storage _vault = _vaults.get(_vaultId);
(uint256 _withdrawnAmount, uint256 _decreasedValue) = _vault.withdraw(address(this), _amount, false);
emit FundsRecalled(_vaultId, _withdrawnAmount, _decreasedValue);
return (_withdrawnAmount, _decreasedValue);
}
| 2,926,593 |
[
1,
426,
12550,
392,
3844,
434,
284,
19156,
628,
279,
9229,
358,
333,
6835,
18,
225,
389,
26983,
548,
326,
2756,
434,
326,
20895,
284,
19156,
628,
18,
225,
389,
8949,
225,
326,
3844,
434,
284,
19156,
358,
20895,
628,
326,
9229,
18,
327,
326,
3844,
434,
284,
19156,
716,
4591,
283,
11777,
628,
326,
9229,
358,
333,
6835,
471,
326,
23850,
8905,
9229,
460,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
225,
445,
389,
266,
1991,
42,
19156,
12,
11890,
5034,
389,
26983,
548,
16,
2254,
5034,
389,
8949,
13,
2713,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
565,
2583,
12,
351,
24530,
6767,
747,
1234,
18,
15330,
422,
314,
1643,
82,
1359,
747,
389,
26983,
548,
480,
389,
26983,
87,
18,
2722,
1016,
9334,
315,
61,
379,
58,
281,
457,
12003,
40,
28,
30,
486,
392,
801,
24530,
16,
486,
314,
1643,
82,
1359,
16,
471,
729,
1552,
486,
1240,
4132,
358,
20895,
284,
19156,
628,
2695,
9229,
8863,
203,
203,
565,
17329,
58,
22,
18,
751,
2502,
389,
26983,
273,
389,
26983,
87,
18,
588,
24899,
26983,
548,
1769,
203,
565,
261,
11890,
5034,
389,
1918,
9446,
82,
6275,
16,
2254,
5034,
389,
323,
1793,
8905,
620,
13,
273,
389,
26983,
18,
1918,
9446,
12,
2867,
12,
2211,
3631,
389,
8949,
16,
629,
1769,
203,
203,
565,
3626,
478,
19156,
426,
11777,
24899,
26983,
548,
16,
389,
1918,
9446,
82,
6275,
16,
389,
323,
1793,
8905,
620,
1769,
203,
203,
565,
327,
261,
67,
1918,
9446,
82,
6275,
16,
389,
323,
1793,
8905,
620,
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
] |
pragma solidity ^0.4.2;
import 'common/Object.sol';
import 'lib/SecurityRings.sol';
contract Proxy is Object {
SecurityRings.Data rings;
using SecurityRings for SecurityRings.Data;
/**
* @dev Authorization node info
* @param _ring Ring index
* @param _gate Gate index
* @return (Auth node address, Auth node ident (user identificator))
*/
function authAt(uint _ring, uint _gate) constant returns (address, bytes32)
{ return rings.authAt(_ring, _gate); }
/**
* @dev Get user identificator for sender node
*/
function getIdent() constant returns (bytes32)
{ return rings.identOf[msg.sender]; }
/**
* @dev Return true when ready to run
*/
function isAuthorized(uint _index) constant returns (bool)
{ return rings.isAuthorized(_index); }
/**
* @dev Initial setup for a new ring
* @param _gates List of auth node addresses
* @param _idents List of user identifiers
*/
function initRing(address[] _gates, bytes32[] _idents) onlyOwner {
var ring = rings.auth.length;
rings.addRing(_gates[0], _idents[0]);
for (uint i = 1; i < _gates.length; ++i)
rings.addGate(ring, _gates[i], _idents[i]);
}
/**
* @dev Proxy constructor
* @param _auth Default auth node
* @param _ident Default user identifier
* @param _safe Ring0 safety address
*/
function Proxy(address _auth, bytes32 _ident, address _safe) {
rings.addRing(_auth, _ident);
rings.addGate(0, _safe, bytes32("safe"));
}
struct Call {
address target;
uint value;
bytes transaction;
uint execBlock;
}
Call[] queue;
/**
* @dev Get call info by index
* @param _index Action call index
*/
function callAt(uint _index) constant returns (address, uint, bytes, uint) {
var c = queue[_index];
return (c.target, c.value, c.transaction, c.execBlock);
}
/**
* @dev Get call queue length
*/
function queueLen() constant returns (uint)
{ return queue.length; }
/**
* @dev Transaction request
* @param _target Transaction destination
* @param _value Transaction value in wei
* @param _transaction Transaction data
*/
function request(address _target, uint _value, bytes _transaction) {
var rid = rings.newAction();
rings.authorized[rid][msg.sender] = true;
queue.push(Call(_target, _value, _transaction, 0));
CallRequest(rid);
}
/**
* @dev Call request log
* @param index Position in call queue
*/
event CallRequest(uint indexed index);
/**
* @dev Authorization of transaction
* @param _index Call in queue position
*/
function authorize(uint _index) {
if (_index >= rings.authorized.length) throw;
rings.authorized[_index][msg.sender] = true;
CallAuthorized(_index, msg.sender);
}
/**
* @dev Authorized call event
* @param index Position in call queue
* @param node Authorization node
*/
event CallAuthorized(uint indexed index, address indexed node);
/**
* @dev Run action when authorized
* @param _index Call in queue position
* @notice This can take a lot of gas
*/
function run(uint _index) {
if (!rings.isAuthorized(_index)
|| queue[_index].execBlock != 0) throw;
// Store exec block
queue[_index].execBlock = block.number;
// Run transaction
var c = queue[_index];
if (!c.target.call.value(c.value)(c.transaction)) throw;
CallExecuted(_index, block.number);
}
/**
* @dev Executed call event
* @param index Position in call queue
* @param block_number Number of call execution block
*/
event CallExecuted(uint indexed index, uint indexed block_number);
/**
* @dev Payable fallback method
*/
function() payable
{ PaymentReceived(msg.sender, msg.value); }
/**
* @dev Incoming payment event
* @param from Payment sender
* @param value Amount of received wei
*/
event PaymentReceived(address indexed from, uint indexed value);
}
|
* @dev Proxy constructor @param _auth Default auth node @param _ident Default user identifier @param _safe Ring0 safety address/
|
function Proxy(address _auth, bytes32 _ident, address _safe) {
rings.addRing(_auth, _ident);
rings.addGate(0, _safe, bytes32("safe"));
}
| 957,598 |
[
1,
3886,
3885,
225,
389,
1944,
2989,
1357,
756,
225,
389,
6392,
2989,
729,
2756,
225,
389,
4626,
25463,
20,
24179,
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,
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,
7659,
12,
2867,
389,
1944,
16,
1731,
1578,
389,
6392,
16,
1758,
389,
4626,
13,
288,
203,
3639,
26537,
18,
1289,
10369,
24899,
1944,
16,
389,
6392,
1769,
203,
3639,
26537,
18,
1289,
13215,
12,
20,
16,
389,
4626,
16,
1731,
1578,
2932,
4626,
7923,
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
] |
./full_match/56/0x6E93d247198cD9116183A09b35e257D24E9D0039/sources/project_/contracts/JordanBSC.sol
|
Create a uniswap pair for this new token set the rest of the contract variablesset wallet provided to true
|
) {
_name = "JordanBSC";
_symbol = "JORDAN";
_decimals = 18;
_tTotal = 1000000000 * 10 ** _decimals;
_tOwned[tokenOwner] = _tTotal;
_devFee = 4;
_devWalletAddress = devWalletAddress_;
_maxTxAmount = _maxHeldAmount;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_router);
uniswapV2Pair = IUniswapV2Pair(
IUniswapV2Factory(_uniswapV2Router.factory()).createPair(
address(this),
_basePair
)
);
uniswapV2Router = _uniswapV2Router;
_isExcludedFromDevFee[owner()] = true;
_isExcludedFromDevFee[address(this)] = true;
_isExcludedFromDevFee[_devWalletAddress] = true;
_isExcludedFromMaxAmount[owner()] = true;
_isExcludedFromMaxAmount[address(this)] = true;
_isExcludedFromMaxAmount[_devWalletAddress] = true;
_isDevWallet[_devWalletAddress] = true;
emit Transfer(address(0), tokenOwner, _tTotal);
}
| 3,248,180 |
[
1,
1684,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
1394,
378,
2656,
278,
9230,
2112,
358,
638,
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,
225,
262,
288,
203,
565,
389,
529,
273,
315,
46,
517,
304,
38,
2312,
14432,
203,
565,
389,
7175,
273,
315,
46,
916,
40,
1258,
14432,
203,
565,
389,
31734,
273,
6549,
31,
203,
565,
389,
88,
5269,
273,
15088,
3784,
380,
1728,
2826,
389,
31734,
31,
203,
565,
389,
88,
5460,
329,
63,
2316,
5541,
65,
273,
389,
88,
5269,
31,
203,
203,
565,
389,
5206,
14667,
273,
1059,
31,
203,
565,
389,
5206,
16936,
1887,
273,
4461,
16936,
1887,
67,
31,
203,
203,
565,
389,
1896,
4188,
6275,
273,
389,
1896,
44,
488,
6275,
31,
203,
203,
565,
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,
24899,
10717,
1769,
203,
565,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
203,
1377,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
203,
3639,
1758,
12,
2211,
3631,
203,
3639,
389,
1969,
4154,
203,
1377,
262,
203,
565,
11272,
203,
203,
565,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
389,
291,
16461,
1265,
8870,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
565,
389,
291,
16461,
1265,
8870,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
565,
389,
291,
16461,
1265,
8870,
14667,
63,
67,
5206,
16936,
2
] |
/*
* This file was generated by MyWish Platform (https://mywish.io/)
* The complete code could be found at https://github.com/MyWishPlatform/
* Copyright (C) 2020 MyWish
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title 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 Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;
// Amount of wei raised
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
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @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;
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @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]);
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];
}
}
/**
* @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;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-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);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
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;
}
}
contract FreezableToken is StandardToken {
// freezing chains
mapping (bytes32 => uint64) internal chains;
// freezing amounts for each chain
mapping (bytes32 => uint) internal freezings;
// total freezing balance per address
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
/**
* @dev Gets the balance of the specified address include freezing tokens.
* @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 super.balanceOf(_owner) + freezingBalance[_owner];
}
/**
* @dev Gets the balance of the specified address without freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
/**
* @dev gets freezing count
* @param _addr Address of freeze tokens owner.
*/
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
/**
* @dev gets freezing end date and freezing balance for the freezing portion specified by index.
* @param _addr Address of freeze tokens owner.
* @param _index Freezing portion index. It ordered by release date descending.
*/
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
/**
* @dev freeze your tokens to the specified address.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to freeze.
* @param _until Release date, must be in future.
*/
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
/**
* @dev release first available freezing tokens.
*/
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
/**
* @dev release all available for release freezing tokens. Gas usage is not deterministic!
* @return how many tokens was released
*/
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
// WISH masc to increase entropy
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @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();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
/**
* @dev Mint the specified amount of token to the specified address and freeze it until the specified date.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to mint and freeze.
* @param _until Release date, must be in future.
* @return A boolean that indicates if the operation was successful.
*/
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "GOE";
string public constant TOKEN_SYMBOL = "GOE";
bool public constant PAUSED = true;
address public constant TARGET_USER = 0x7edfb498a99CC2475db7A426Dff640Fa605daaBA;
uint public constant START_TIME = 1600616760;
bool public constant CONTINUE_MINTING = true;
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, 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(hasClosed());
finalization();
emit 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 CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
}
contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale {
function hasStarted() public view returns (bool) {
return now >= openingTime;
}
function startTime() public view returns (uint256) {
return openingTime;
}
function endTime() public view returns (uint256) {
return closingTime;
}
function hasClosed() public view returns (bool) {
return super.hasClosed() || capReached();
}
function hasEnded() public view returns (bool) {
return hasClosed();
}
function finalization() internal {
super.finalization();
if (PAUSED) {
MainToken(token).unpause();
}
if (!CONTINUE_MINTING) {
require(MintableToken(token).finishMinting());
}
Ownable(token).transferOwnership(TARGET_USER);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate).div(1 ether);
}
}
contract TemplateCrowdsale is Consts, MainCrowdsale
{
event Initialized();
event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime);
bool public initialized = false;
constructor(MintableToken _token) public
Crowdsale(10 * TOKEN_DECIMAL_MULTIPLIER, 0x7edfb498a99CC2475db7A426Dff640Fa605daaBA, _token)
TimedCrowdsale(START_TIME > now ? START_TIME : now, 1609515960)
CappedCrowdsale(100000000000000000000000000000)
{
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
transferOwnership(TARGET_USER);
emit Initialized();
}
/**
* @dev override hasClosed to add minimal value logic
* @return true if remained to achieve less than minimal
*/
function hasClosed() public view returns (bool) {
bool remainValue = cap.sub(weiRaised) < 50000000000000000;
return super.hasClosed() || remainValue;
}
function setStartTime(uint _startTime) public onlyOwner {
// only if CS was not started
require(now < openingTime);
// only move time to future
require(_startTime > openingTime);
require(_startTime < closingTime);
emit TimesChanged(_startTime, closingTime, openingTime, closingTime);
openingTime = _startTime;
}
function setEndTime(uint _endTime) public onlyOwner {
// only if CS was not ended
require(now < closingTime);
// only if new end time in future
require(now < _endTime);
require(_endTime > openingTime);
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
closingTime = _endTime;
}
function setTimes(uint _startTime, uint _endTime) public onlyOwner {
require(_endTime > _startTime);
uint oldStartTime = openingTime;
uint oldEndTime = closingTime;
bool changed = false;
if (_startTime != oldStartTime) {
require(_startTime > now);
// only if CS was not started
require(now < oldStartTime);
// only move time to future
require(_startTime > oldStartTime);
openingTime = _startTime;
changed = true;
}
if (_endTime != oldEndTime) {
// only if CS was not ended
require(now < oldEndTime);
// end time in future
require(now < _endTime);
closingTime = _endTime;
changed = true;
}
if (changed) {
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
}
}
/**
* @dev override purchase validation to add extra value logic.
* @return true if sended more than minimal value
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(msg.value >= 50000000000000000);
require(msg.value <= 100000000000000000000000000000);
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
|
* @dev override hasClosed to add minimal value logic @return true if remained to achieve less than minimal/
|
function hasClosed() public view returns (bool) {
bool remainValue = cap.sub(weiRaised) < 50000000000000000;
return super.hasClosed() || remainValue;
}
| 5,921,226 |
[
1,
10601,
711,
7395,
358,
527,
16745,
460,
4058,
327,
638,
309,
7232,
329,
358,
20186,
537,
5242,
2353,
16745,
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
] |
[
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,
711,
7395,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
1426,
7232,
620,
273,
3523,
18,
1717,
12,
1814,
77,
12649,
5918,
13,
411,
1381,
12648,
12648,
31,
203,
3639,
327,
2240,
18,
5332,
7395,
1435,
747,
7232,
620,
31,
203,
565,
289,
203,
377,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Sources flattened with hardhat v2.8.4 https://hardhat.org
// File @rari-capital/solmate/src/auth/[email protected]
// SPDX-License-Identifier: GNU AGPLv3
pragma solidity >=0.8.0;
/// @notice Provides a flexible and updatable auth pattern which is completely separate from application logic.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
abstract contract Auth {
event OwnerUpdated(address indexed user, address indexed newOwner);
event AuthorityUpdated(address indexed user, Authority indexed newAuthority);
address public owner;
Authority public authority;
constructor(address _owner, Authority _authority) {
owner = _owner;
authority = _authority;
emit OwnerUpdated(msg.sender, _owner);
emit AuthorityUpdated(msg.sender, _authority);
}
modifier requiresAuth() {
require(isAuthorized(msg.sender, msg.sig), "UNAUTHORIZED");
_;
}
function isAuthorized(address user, bytes4 functionSig) internal view virtual returns (bool) {
Authority auth = authority; // Memoizing authority saves us a warm SLOAD, around 100 gas.
// Checking if the caller is the owner only after calling the authority saves gas in most cases, but be
// aware that this makes protected functions uncallable even to the owner if the authority is out of order.
return (address(auth) != address(0) && auth.canCall(user, address(this), functionSig)) || user == owner;
}
function setAuthority(Authority newAuthority) public virtual {
// We check if the caller is the owner first because we want to ensure they can
// always swap out the authority even if it's reverting or using up a lot of gas.
require(msg.sender == owner || authority.canCall(msg.sender, address(this), msg.sig));
authority = newAuthority;
emit AuthorityUpdated(msg.sender, newAuthority);
}
function setOwner(address newOwner) public virtual requiresAuth {
owner = newOwner;
emit OwnerUpdated(msg.sender, newOwner);
}
}
/// @notice A generic interface for a contract which provides authorization data to an Auth instance.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/auth/Auth.sol)
/// @author Modified from Dappsys (https://github.com/dapphub/ds-auth/blob/master/src/auth.sol)
interface Authority {
function canCall(
address user,
address target,
bytes4 functionSig
) external view returns (bool);
}
// File @rari-capital/solmate/src/tokens/[email protected]
pragma solidity >=0.8.0;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*///////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*///////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
// File @rari-capital/solmate/src/utils/[email protected]
pragma solidity >=0.8.0;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol)
/// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer.
library SafeTransferLib {
/*///////////////////////////////////////////////////////////////
ETH OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferETH(address to, uint256 amount) internal {
bool callStatus;
assembly {
// Transfer the ETH and store if it succeeded or not.
callStatus := call(gas(), to, amount, 0, 0, 0, 0)
}
require(callStatus, "ETH_TRANSFER_FAILED");
}
/*///////////////////////////////////////////////////////////////
ERC20 OPERATIONS
//////////////////////////////////////////////////////////////*/
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "from" argument.
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 100 because the calldata length is 4 + 32 * 3.
callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED");
}
function safeTransfer(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED");
}
function safeApprove(
ERC20 token,
address to,
uint256 amount
) internal {
bool callStatus;
assembly {
// Get a pointer to some free memory.
let freeMemoryPointer := mload(0x40)
// Write the abi-encoded calldata to memory piece by piece:
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) // Begin with the function selector.
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Mask and append the "to" argument.
mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value.
// Call the token and store if it succeeded or not.
// We use 68 because the calldata length is 4 + 32 * 2.
callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0)
}
require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED");
}
/*///////////////////////////////////////////////////////////////
INTERNAL HELPER LOGIC
//////////////////////////////////////////////////////////////*/
function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) {
assembly {
// Get how many bytes the call returned.
let returnDataSize := returndatasize()
// If the call reverted:
if iszero(callStatus) {
// Copy the revert message into memory.
returndatacopy(0, 0, returnDataSize)
// Revert with the same message.
revert(0, returnDataSize)
}
switch returnDataSize
case 32 {
// Copy the return data into memory.
returndatacopy(0, 0, returnDataSize)
// Set success to whether it returned true.
success := iszero(iszero(mload(0)))
}
case 0 {
// There was no return data.
success := 1
}
default {
// It returned some malformed input.
success := 0
}
}
}
}
// File @rari-capital/solmate/src/tokens/[email protected]
pragma solidity >=0.8.0;
/// @notice Minimalist and modern Wrapped Ether implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/WETH.sol)
/// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol)
contract WETH is ERC20("Wrapped Ether", "WETH", 18) {
using SafeTransferLib for address;
event Deposit(address indexed from, uint256 amount);
event Withdrawal(address indexed to, uint256 amount);
function deposit() public payable virtual {
_mint(msg.sender, msg.value);
emit Deposit(msg.sender, msg.value);
}
function withdraw(uint256 amount) public virtual {
_burn(msg.sender, amount);
emit Withdrawal(msg.sender, amount);
msg.sender.safeTransferETH(amount);
}
receive() external payable virtual {
deposit();
}
}
// File @rari-capital/solmate/src/utils/[email protected]
pragma solidity >=0.8.0;
/// @notice Safe unsigned integer casting library that reverts on overflow.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeCastLib.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol)
library SafeCastLib {
function safeCastTo248(uint256 x) internal pure returns (uint248 y) {
require(x <= type(uint248).max);
y = uint248(x);
}
function safeCastTo128(uint256 x) internal pure returns (uint128 y) {
require(x <= type(uint128).max);
y = uint128(x);
}
function safeCastTo96(uint256 x) internal pure returns (uint96 y) {
require(x <= type(uint96).max);
y = uint96(x);
}
function safeCastTo64(uint256 x) internal pure returns (uint64 y) {
require(x <= type(uint64).max);
y = uint64(x);
}
function safeCastTo32(uint256 x) internal pure returns (uint32 y) {
require(x <= type(uint32).max);
y = uint32(x);
}
}
// File srcBuild/FixedPointMathLib.sol
pragma solidity >=0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/* ///////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
////////////////////////////////////////////////////////////// */
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD);
// Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD);
// Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y);
// Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y);
// Equivalent to (x * WAD) / y rounded up.
}
/* ///////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function fmul(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(x == 0 || (x * y) / x == y)
if iszero(or(iszero(x), eq(div(z, x), y))) {
revert(0, 0)
}
// If baseUnit is zero this will return zero instead of reverting.
z := div(z, baseUnit)
}
}
function fdiv(
uint256 x,
uint256 y,
uint256 baseUnit
) internal pure returns (uint256 z) {
assembly {
// Store x * baseUnit in z for now.
z := mul(x, baseUnit)
// Equivalent to require(y != 0 && (x == 0 || (x * baseUnit) / x == baseUnit))
if iszero(and(iszero(iszero(y)), or(iszero(x), eq(div(z, x), baseUnit)))) {
revert(0, 0)
}
// We ensure y is not zero above, so there is never division by zero here.
z := div(z, y)
}
}
function mulDivDown(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// Divide z by the denominator.
z := div(z, denominator)
}
}
function mulDivUp(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
// Store x * y in z for now.
z := mul(x, y)
// Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y))
if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {
revert(0, 0)
}
// First, divide z - 1 by the denominator and add 1.
// Then multiply it by 0 if z is zero, or 1 otherwise.
z := mul(iszero(iszero(z)), add(div(sub(z, 1), denominator), 1))
}
}
function rpow(
uint256 x,
uint256 n,
uint256 denominator
) internal pure returns (uint256 z) {
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := denominator
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store denominator in z for now.
z := denominator
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, denominator)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, denominator)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, denominator)
}
}
}
}
}
/* ///////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
assembly {
// Start off with z at 1.
z := 1
// Used below to help find a nearby power of 2.
let y := x
// Find the lowest power of 2 that is at least sqrt(x).
if iszero(lt(y, 0x100000000000000000000000000000000)) {
y := shr(128, y) // Like dividing by 2 ** 128.
z := shl(64, z)
}
if iszero(lt(y, 0x10000000000000000)) {
y := shr(64, y) // Like dividing by 2 ** 64.
z := shl(32, z)
}
if iszero(lt(y, 0x100000000)) {
y := shr(32, y) // Like dividing by 2 ** 32.
z := shl(16, z)
}
if iszero(lt(y, 0x10000)) {
y := shr(16, y) // Like dividing by 2 ** 16.
z := shl(8, z)
}
if iszero(lt(y, 0x100)) {
y := shr(8, y) // Like dividing by 2 ** 8.
z := shl(4, z)
}
if iszero(lt(y, 0x10)) {
y := shr(4, y) // Like dividing by 2 ** 4.
z := shl(2, z)
}
if iszero(lt(y, 0x8)) {
// Equivalent to 2 ** z.
z := shl(1, z)
}
// Shifting right by 1 is like dividing by 2.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// Compute a rounded down version of z.
let zRoundDown := div(x, z)
// If zRoundDown is smaller, use it.
if lt(zRoundDown, z) {
z := zRoundDown
}
}
}
}
// File srcBuild/interfaces/Strategy.sol
pragma solidity ^0.8.11;
/// @notice Minimal interface for Vault compatible strategies.
/// @dev Designed for out of the box compatibility with Fuse cTokens.
/// @dev Like cTokens, strategies must be transferrable ERC20s.
abstract contract Strategy is ERC20 {
/// @notice Returns whether the strategy accepts ETH or an ERC20.
/// @return True if the strategy accepts ETH, false otherwise.
/// @dev Only present in Fuse cTokens, not Compound cTokens.
function isCEther() external view virtual returns (bool);
/// @notice Withdraws a specific amount of underlying tokens from the strategy.
/// @param amount The amount of underlying tokens to withdraw.
/// @return An error code, or 0 if the withdrawal was successful.
function redeemUnderlying(uint256 amount) external virtual returns (uint256);
/// @notice Returns a user's strategy balance in underlying tokens.
/// @param user The user to get the underlying balance of.
/// @return The user's strategy balance in underlying tokens.
/// @dev May mutate the state of the strategy by accruing interest.
function balanceOfUnderlying(address user) external virtual returns (uint256);
}
/// @notice Minimal interface for Vault strategies that accept ERC20s.
/// @dev Designed for out of the box compatibility with Fuse cERC20s.
abstract contract ERC20Strategy is Strategy {
/// @notice Returns the underlying ERC20 token the strategy accepts.
/// @return The underlying ERC20 token the strategy accepts.
function underlying() external view virtual returns (ERC20);
/// @notice Deposit a specific amount of underlying tokens into the strategy.
/// @param amount The amount of underlying tokens to deposit.
/// @return An error code, or 0 if the deposit was successful.
function mint(uint256 amount) external virtual returns (uint256);
}
/// @notice Minimal interface for Vault strategies that accept ETH.
/// @dev Designed for out of the box compatibility with Fuse cEther.
abstract contract ETHStrategy is Strategy {
/// @notice Deposit a specific amount of ETH into the strategy.
/// @dev The amount of ETH is specified via msg.value. Reverts on error.
function mint() external payable virtual;
}
// File srcBuild/Vault.sol
pragma solidity ^0.8.11;
/// @title Aphra Vault (avToken)
/// @author Transmissions11 and JetJadeja
/// @notice Flexible, minimalist, and gas-optimized yield
/// aggregator for earning interest on any ERC20 token.
/// @notice changes from original are to rename Rari -> Aphra tokens and any usage of rvToken => avToken
contract Vault is ERC20, Auth {
using SafeCastLib for uint256;
using SafeTransferLib for ERC20;
using FixedPointMathLib for uint256;
/* //////////////////////////////////////////////////////////////
CONSTANTS
///////////////////////////////////////////////////////////// */
/// @notice The maximum number of elements allowed on the withdrawal stack.
/// @dev Needed to prevent denial of service attacks by queue operators.
uint256 internal constant MAX_WITHDRAWAL_STACK_SIZE = 32;
/* //////////////////////////////////////////////////////////////
IMMUTABLES
///////////////////////////////////////////////////////////// */
/// @notice The underlying token the Vault accepts.
ERC20 public immutable UNDERLYING;
/// @notice The base unit of the underlying token and hence avToken.
/// @dev Equal to 10 ** decimals. Used for fixed point arithmetic.
uint256 internal immutable BASE_UNIT;
/// @notice Creates a new Vault that accepts a specific underlying token.
/// @param _UNDERLYING The ERC20 compliant token the Vault should accept.
constructor(ERC20 _UNDERLYING)
ERC20(
// ex:Aphra Vader Vault
string(abi.encodePacked("Aphra ", _UNDERLYING.name(), " Vault")),
// ex: avVader
string(abi.encodePacked("av", _UNDERLYING.symbol())),
// ex: 18
_UNDERLYING.decimals()
)
Auth(Auth(msg.sender).owner(), Auth(msg.sender).authority())
{
UNDERLYING = _UNDERLYING;
BASE_UNIT = 10**decimals;
// Prevent minting of avTokens until
// the initialize function is called.
totalSupply = type(uint256).max;
}
/* //////////////////////////////////////////////////////////////
FEE CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice The percentage of profit recognized each harvest to reserve as fees.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public feePercent;
/// @notice Emitted when the fee percentage is updated.
/// @param user The authorized user who triggered the update.
/// @param newFeePercent The new fee percentage.
event FeePercentUpdated(address indexed user, uint256 newFeePercent);
/// @notice Sets a new fee percentage.
/// @param newFeePercent The new fee percentage.
function setFeePercent(uint256 newFeePercent) external requiresAuth {
// A fee percentage over 100% doesn't make sense.
require(newFeePercent <= 1e18, "FEE_TOO_HIGH");
// Update the fee percentage.
feePercent = newFeePercent;
emit FeePercentUpdated(msg.sender, newFeePercent);
}
/* //////////////////////////////////////////////////////////////
HARVEST CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Emitted when the harvest window is updated.
/// @param user The authorized user who triggered the update.
/// @param newHarvestWindow The new harvest window.
event HarvestWindowUpdated(address indexed user, uint128 newHarvestWindow);
/// @notice Emitted when the harvest delay is updated.
/// @param user The authorized user who triggered the update.
/// @param newHarvestDelay The new harvest delay.
event HarvestDelayUpdated(address indexed user, uint64 newHarvestDelay);
/// @notice Emitted when the harvest delay is scheduled to be updated next harvest.
/// @param user The authorized user who triggered the update.
/// @param newHarvestDelay The scheduled updated harvest delay.
event HarvestDelayUpdateScheduled(address indexed user, uint64 newHarvestDelay);
/// @notice The period in seconds during which multiple harvests can occur
/// regardless if they are taking place before the harvest delay has elapsed.
/// @dev Long harvest windows open the Vault up to profit distribution slowdown attacks.
uint128 public harvestWindow;
/// @notice The period in seconds over which locked profit is unlocked.
/// @dev Cannot be 0 as it opens harvests up to sandwich attacks.
uint64 public harvestDelay;
/// @notice The value that will replace harvestDelay next harvest.
/// @dev In the case that the next delay is 0, no update will be applied.
uint64 public nextHarvestDelay;
/// @notice Sets a new harvest window.
/// @param newHarvestWindow The new harvest window.
/// @dev The Vault's harvestDelay must already be set before calling.
function setHarvestWindow(uint128 newHarvestWindow) external requiresAuth {
// A harvest window longer than the harvest delay doesn't make sense.
require(newHarvestWindow <= harvestDelay, "WINDOW_TOO_LONG");
// Update the harvest window.
harvestWindow = newHarvestWindow;
emit HarvestWindowUpdated(msg.sender, newHarvestWindow);
}
/// @notice Sets a new harvest delay.
/// @param newHarvestDelay The new harvest delay to set.
/// @dev If the current harvest delay is 0, meaning it has not
/// been set before, it will be updated immediately, otherwise
/// it will be scheduled to take effect after the next harvest.
function setHarvestDelay(uint64 newHarvestDelay) external requiresAuth {
// A harvest delay of 0 makes harvests vulnerable to sandwich attacks.
require(newHarvestDelay != 0, "DELAY_CANNOT_BE_ZERO");
// A harvest delay longer than 1 year doesn't make sense.
require(newHarvestDelay <= 365 days, "DELAY_TOO_LONG");
// If the harvest delay is 0, meaning it has not been set before:
if (harvestDelay == 0) {
// We'll apply the update immediately.
harvestDelay = newHarvestDelay;
emit HarvestDelayUpdated(msg.sender, newHarvestDelay);
} else {
// We'll apply the update next harvest.
nextHarvestDelay = newHarvestDelay;
emit HarvestDelayUpdateScheduled(msg.sender, newHarvestDelay);
}
}
/* //////////////////////////////////////////////////////////////
TARGET FLOAT CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice The desired percentage of the Vault's holdings to keep as float.
/// @dev A fixed point number where 1e18 represents 100% and 0 represents 0%.
uint256 public targetFloatPercent;
/// @notice Emitted when the target float percentage is updated.
/// @param user The authorized user who triggered the update.
/// @param newTargetFloatPercent The new target float percentage.
event TargetFloatPercentUpdated(address indexed user, uint256 newTargetFloatPercent);
/// @notice Set a new target float percentage.
/// @param newTargetFloatPercent The new target float percentage.
function setTargetFloatPercent(uint256 newTargetFloatPercent) external requiresAuth {
// A target float percentage over 100% doesn't make sense.
require(newTargetFloatPercent <= 1e18, "TARGET_TOO_HIGH");
// Update the target float percentage.
targetFloatPercent = newTargetFloatPercent;
emit TargetFloatPercentUpdated(msg.sender, newTargetFloatPercent);
}
/* //////////////////////////////////////////////////////////////
UNDERLYING IS WETH CONFIGURATION
///////////////////////////////////////////////////////////// */
/// @notice Whether the Vault should treat the underlying token as WETH compatible.
/// @dev If enabled the Vault will allow trusting strategies that accept Ether.
bool public underlyingIsWETH;
/// @notice Emitted when whether the Vault should treat the underlying as WETH is updated.
/// @param user The authorized user who triggered the update.
/// @param newUnderlyingIsWETH Whether the Vault nows treats the underlying as WETH.
event UnderlyingIsWETHUpdated(address indexed user, bool newUnderlyingIsWETH);
/// @notice Sets whether the Vault treats the underlying as WETH.
/// @param newUnderlyingIsWETH Whether the Vault should treat the underlying as WETH.
/// @dev The underlying token must have 18 decimals, to match Ether's decimal scheme.
function setUnderlyingIsWETH(bool newUnderlyingIsWETH) external requiresAuth {
// Ensure the underlying token's decimals match ETH if is WETH being set to true.
require(!newUnderlyingIsWETH || UNDERLYING.decimals() == 18, "WRONG_DECIMALS");
// Update whether the Vault treats the underlying as WETH.
underlyingIsWETH = newUnderlyingIsWETH;
emit UnderlyingIsWETHUpdated(msg.sender, newUnderlyingIsWETH);
}
/* //////////////////////////////////////////////////////////////
STRATEGY STORAGE
///////////////////////////////////////////////////////////// */
/// @notice The total amount of underlying tokens held in strategies at the time of the last harvest.
/// @dev Includes maxLockedProfit, must be correctly subtracted to compute available/free holdings.
uint256 public totalStrategyHoldings;
/// @dev Packed struct of strategy data.
/// @param trusted Whether the strategy is trusted.
/// @param balance The amount of underlying tokens held in the strategy.
struct StrategyData {
// Used to determine if the Vault will operate on a strategy.
bool trusted;
// Used to determine profit and loss during harvests of the strategy.
uint248 balance;
}
/// @notice Maps strategies to data the Vault holds on them.
mapping(Strategy => StrategyData) public getStrategyData;
/* //////////////////////////////////////////////////////////////
HARVEST STORAGE
///////////////////////////////////////////////////////////// */
/// @notice A timestamp representing when the first harvest in the most recent harvest window occurred.
/// @dev May be equal to lastHarvest if there was/has only been one harvest in the most last/current window.
uint64 public lastHarvestWindowStart;
/// @notice A timestamp representing when the most recent harvest occurred.
uint64 public lastHarvest;
/// @notice The amount of locked profit at the end of the last harvest.
uint128 public maxLockedProfit;
/* //////////////////////////////////////////////////////////////
WITHDRAWAL STACK STORAGE
///////////////////////////////////////////////////////////// */
/// @notice An ordered array of strategies representing the withdrawal stack.
/// @dev The stack is processed in descending order, meaning the last index will be withdrawn from first.
/// @dev Strategies that are untrusted, duplicated, or have no balance are filtered out when encountered at
/// withdrawal time, not validated upfront, meaning the stack may not reflect the "true" set used for withdrawals.
Strategy[] public withdrawalStack;
/// @notice Gets the full withdrawal stack.
/// @return An ordered array of strategies representing the withdrawal stack.
/// @dev This is provided because Solidity converts public arrays into index getters,
/// but we need a way to allow external contracts and users to access the whole array.
function getWithdrawalStack() external view returns (Strategy[] memory) {
return withdrawalStack;
}
/* //////////////////////////////////////////////////////////////
DEPOSIT/WITHDRAWAL LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a successful deposit.
/// @param user The address that deposited into the Vault.
/// @param underlyingAmount The amount of underlying tokens that were deposited.
event Deposit(address indexed user, uint256 underlyingAmount);
/// @notice Emitted after a successful withdrawal.
/// @param user The address that withdrew from the Vault.
/// @param underlyingAmount The amount of underlying tokens that were withdrawn.
event Withdraw(address indexed user, uint256 underlyingAmount);
/// @notice Deposit a specific amount of underlying tokens.
/// @param underlyingAmount The amount of the underlying token to deposit.
function deposit(uint256 underlyingAmount) external {
// Determine the equivalent amount of avTokens and mint them.
_mint(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT));
emit Deposit(msg.sender, underlyingAmount);
// Transfer in underlying tokens from the user.
// This will revert if the user does not have the amount specified.
UNDERLYING.safeTransferFrom(msg.sender, address(this), underlyingAmount);
}
/// @notice Withdraw a specific amount of underlying tokens.
/// @param underlyingAmount The amount of underlying tokens to withdraw.
function withdraw(uint256 underlyingAmount) external {
// Determine the equivalent amount of avTokens and burn them.
// This will revert if the user does not have enough avTokens.
_burn(msg.sender, underlyingAmount.fdiv(exchangeRate(), BASE_UNIT));
emit Withdraw(msg.sender, underlyingAmount);
// Withdraw from strategies if needed and transfer.
transferUnderlyingTo(msg.sender, underlyingAmount);
}
/// @notice Redeem a specific amount of avTokens for underlying tokens.
/// @param avTokenAmount The amount of avTokens to redeem for underlying tokens.
function redeem(uint256 avTokenAmount) external {
// Determine the equivalent amount of underlying tokens.
uint256 underlyingAmount = avTokenAmount.fmul(exchangeRate(), BASE_UNIT);
// Burn the provided amount of avTokens.
// This will revert if the user does not have enough avTokens.
_burn(msg.sender, avTokenAmount);
emit Withdraw(msg.sender, underlyingAmount);
// Withdraw from strategies if needed and transfer.
transferUnderlyingTo(msg.sender, underlyingAmount);
}
/// @dev Transfers a specific amount of underlying tokens held in strategies and/or float to a recipient.
/// @dev Only withdraws from strategies if needed and maintains the target float percentage if possible.
/// @param recipient The user to transfer the underlying tokens to.
/// @param underlyingAmount The amount of underlying tokens to transfer.
function transferUnderlyingTo(address recipient, uint256 underlyingAmount) internal {
// Get the Vault's floating balance.
uint256 float = totalFloat();
// If the amount is greater than the float, withdraw from strategies.
if (underlyingAmount > float) {
// Compute the amount needed to reach our target float percentage.
uint256 floatMissingForTarget = (totalHoldings() - underlyingAmount).fmul(targetFloatPercent, 1e18);
// Compute the bare minimum amount we need for this withdrawal.
uint256 floatMissingForWithdrawal = underlyingAmount - float;
// Pull enough to cover the withdrawal and reach our target float percentage.
pullFromWithdrawalStack(floatMissingForWithdrawal + floatMissingForTarget);
}
// Transfer the provided amount of underlying tokens.
UNDERLYING.safeTransfer(recipient, underlyingAmount);
}
/* //////////////////////////////////////////////////////////////
VAULT ACCOUNTING LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Returns a user's Vault balance in underlying tokens.
/// @param user The user to get the underlying balance of.
/// @return The user's Vault balance in underlying tokens.
function balanceOfUnderlying(address user) external view returns (uint256) {
return balanceOf[user].fmul(exchangeRate(), BASE_UNIT);
}
/// @notice Returns the amount of underlying tokens an avToken can be redeemed for.
/// @return The amount of underlying tokens an avToken can be redeemed for.
function exchangeRate() public view returns (uint256) {
// Get the total supply of avTokens.
uint256 avTokenSupply = totalSupply;
// If there are no avTokens in circulation, return an exchange rate of 1:1.
if (avTokenSupply == 0) return BASE_UNIT;
// Calculate the exchange rate by dividing the total holdings by the avToken supply.
return totalHoldings().fdiv(avTokenSupply, BASE_UNIT);
}
/// @notice Calculates the total amount of underlying tokens the Vault holds.
/// @return totalUnderlyingHeld The total amount of underlying tokens the Vault holds.
function totalHoldings() public view returns (uint256 totalUnderlyingHeld) {
unchecked {
// Cannot underflow as locked profit can't exceed total strategy holdings.
totalUnderlyingHeld = totalStrategyHoldings - lockedProfit();
}
// Include our floating balance in the total.
totalUnderlyingHeld += totalFloat();
}
/// @notice Calculates the current amount of locked profit.
/// @return The current amount of locked profit.
function lockedProfit() public view returns (uint256) {
// Get the last harvest and harvest delay.
uint256 previousHarvest = lastHarvest;
uint256 harvestInterval = harvestDelay;
unchecked {
// If the harvest delay has passed, there is no locked profit.
// Cannot overflow on human timescales since harvestInterval is capped.
if (block.timestamp >= previousHarvest + harvestInterval) return 0;
// Get the maximum amount we could return.
uint256 maximumLockedProfit = maxLockedProfit;
// Compute how much profit remains locked based on the last harvest and harvest delay.
// It's impossible for the previous harvest to be in the future, so this will never underflow.
return maximumLockedProfit - (maximumLockedProfit * (block.timestamp - previousHarvest)) / harvestInterval;
}
}
/// @notice Returns the amount of underlying tokens that idly sit in the Vault.
/// @return The amount of underlying tokens that sit idly in the Vault.
function totalFloat() public view returns (uint256) {
return UNDERLYING.balanceOf(address(this));
}
/* //////////////////////////////////////////////////////////////
HARVEST LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a successful harvest.
/// @param user The authorized user who triggered the harvest.
/// @param strategies The trusted strategies that were harvested.
event Harvest(address indexed user, Strategy[] strategies);
/// @notice Harvest a set of trusted strategies.
/// @param strategies The trusted strategies to harvest.
/// @dev Will always revert if called outside of an active
/// harvest window or before the harvest delay has passed.
function harvest(Strategy[] calldata strategies) external requiresAuth {
// If this is the first harvest after the last window:
if (block.timestamp >= lastHarvest + harvestDelay) {
// Set the harvest window's start timestamp.
// Cannot overflow 64 bits on human timescales.
lastHarvestWindowStart = uint64(block.timestamp);
} else {
// We know this harvest is not the first in the window so we need to ensure it's within it.
require(block.timestamp <= lastHarvestWindowStart + harvestWindow, "BAD_HARVEST_TIME");
}
// Get the Vault's current total strategy holdings.
uint256 oldTotalStrategyHoldings = totalStrategyHoldings;
// Used to store the total profit accrued by the strategies.
uint256 totalProfitAccrued;
// Used to store the new total strategy holdings after harvesting.
uint256 newTotalStrategyHoldings = oldTotalStrategyHoldings;
// Will revert if any of the specified strategies are untrusted.
for (uint256 i = 0; i < strategies.length; i++) {
// Get the strategy at the current index.
Strategy strategy = strategies[i];
// If an untrusted strategy could be harvested a malicious user could use
// a fake strategy that over-reports holdings to manipulate the exchange rate.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Get the strategy's previous and current balance.
uint256 balanceLastHarvest = getStrategyData[strategy].balance;
uint256 balanceThisHarvest = strategy.balanceOfUnderlying(address(this));
// Update the strategy's stored balance. Cast overflow is unrealistic.
getStrategyData[strategy].balance = balanceThisHarvest.safeCastTo248();
// Increase/decrease newTotalStrategyHoldings based on the profit/loss registered.
// We cannot wrap the subtraction in parenthesis as it would underflow if the strategy had a loss.
newTotalStrategyHoldings = newTotalStrategyHoldings + balanceThisHarvest - balanceLastHarvest;
unchecked {
// Update the total profit accrued while counting losses as zero profit.
// Cannot overflow as we already increased total holdings without reverting.
totalProfitAccrued += balanceThisHarvest > balanceLastHarvest
? balanceThisHarvest - balanceLastHarvest // Profits since last harvest.
: 0; // If the strategy registered a net loss we don't have any new profit.
}
}
// Compute fees as the fee percent multiplied by the profit.
uint256 feesAccrued = totalProfitAccrued.fmul(feePercent, 1e18);
// If we accrued any fees, mint an equivalent amount of avTokens.
// Authorized users can claim the newly minted avTokens via claimFees.
_mint(address(this), feesAccrued.fdiv(exchangeRate(), BASE_UNIT));
// Update max unlocked profit based on any remaining locked profit plus new profit.
maxLockedProfit = (lockedProfit() + totalProfitAccrued - feesAccrued).safeCastTo128();
// Set strategy holdings to our new total.
totalStrategyHoldings = newTotalStrategyHoldings;
// Update the last harvest timestamp.
// Cannot overflow on human timescales.
lastHarvest = uint64(block.timestamp);
emit Harvest(msg.sender, strategies);
// Get the next harvest delay.
uint64 newHarvestDelay = nextHarvestDelay;
// If the next harvest delay is not 0:
if (newHarvestDelay != 0) {
// Update the harvest delay.
harvestDelay = newHarvestDelay;
// Reset the next harvest delay.
nextHarvestDelay = 0;
emit HarvestDelayUpdated(msg.sender, newHarvestDelay);
}
}
/* //////////////////////////////////////////////////////////////
STRATEGY DEPOSIT/WITHDRAWAL LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after the Vault deposits into a strategy contract.
/// @param user The authorized user who triggered the deposit.
/// @param strategy The strategy that was deposited into.
/// @param underlyingAmount The amount of underlying tokens that were deposited.
event StrategyDeposit(address indexed user, Strategy indexed strategy, uint256 underlyingAmount);
/// @notice Emitted after the Vault withdraws funds from a strategy contract.
/// @param user The authorized user who triggered the withdrawal.
/// @param strategy The strategy that was withdrawn from.
/// @param underlyingAmount The amount of underlying tokens that were withdrawn.
event StrategyWithdrawal(address indexed user, Strategy indexed strategy, uint256 underlyingAmount);
/// @notice Deposit a specific amount of float into a trusted strategy.
/// @param strategy The trusted strategy to deposit into.
/// @param underlyingAmount The amount of underlying tokens in float to deposit.
function depositIntoStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth {
// A strategy must be trusted before it can be deposited into.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Increase totalStrategyHoldings to account for the deposit.
totalStrategyHoldings += underlyingAmount;
unchecked {
// Without this the next harvest would count the deposit as profit.
// Cannot overflow as the balance of one strategy can't exceed the sum of all.
getStrategyData[strategy].balance += underlyingAmount.safeCastTo248();
}
emit StrategyDeposit(msg.sender, strategy, underlyingAmount);
// We need to deposit differently if the strategy takes ETH.
if (strategy.isCEther()) {
// Unwrap the right amount of WETH.
WETH(payable(address(UNDERLYING))).withdraw(underlyingAmount);
// Deposit into the strategy and assume it will revert on error.
ETHStrategy(address(strategy)).mint{value: underlyingAmount}();
} else {
// Approve underlyingAmount to the strategy so we can deposit.
UNDERLYING.safeApprove(address(strategy), underlyingAmount);
// Deposit into the strategy and revert if it returns an error code.
require(ERC20Strategy(address(strategy)).mint(underlyingAmount) == 0, "MINT_FAILED");
}
}
/// @notice Withdraw a specific amount of underlying tokens from a strategy.
/// @param strategy The strategy to withdraw from.
/// @param underlyingAmount The amount of underlying tokens to withdraw.
/// @dev Withdrawing from a strategy will not remove it from the withdrawal stack.
function withdrawFromStrategy(Strategy strategy, uint256 underlyingAmount) external requiresAuth {
// A strategy must be trusted before it can be withdrawn from.
require(getStrategyData[strategy].trusted, "UNTRUSTED_STRATEGY");
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance -= underlyingAmount.safeCastTo248();
unchecked {
// Decrease totalStrategyHoldings to account for the withdrawal.
// Cannot underflow as the balance of one strategy will never exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
emit StrategyWithdrawal(msg.sender, strategy, underlyingAmount);
// Withdraw from the strategy and revert if it returns an error code.
require(strategy.redeemUnderlying(underlyingAmount) == 0, "REDEEM_FAILED");
// Wrap the withdrawn Ether into WETH if necessary.
if (strategy.isCEther()) WETH(payable(address(UNDERLYING))).deposit{value: underlyingAmount}();
}
/* //////////////////////////////////////////////////////////////
STRATEGY TRUST/DISTRUST LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a strategy is set to trusted.
/// @param user The authorized user who trusted the strategy.
/// @param strategy The strategy that became trusted.
event StrategyTrusted(address indexed user, Strategy indexed strategy);
/// @notice Emitted when a strategy is set to untrusted.
/// @param user The authorized user who untrusted the strategy.
/// @param strategy The strategy that became untrusted.
event StrategyDistrusted(address indexed user, Strategy indexed strategy);
/// @notice Stores a strategy as trusted, enabling it to be harvested.
/// @param strategy The strategy to make trusted.
function trustStrategy(Strategy strategy) external requiresAuth {
// Ensure the strategy accepts the correct underlying token.
// If the strategy accepts ETH the Vault should accept WETH, it'll handle wrapping when necessary.
require(
strategy.isCEther() ? underlyingIsWETH : ERC20Strategy(address(strategy)).underlying() == UNDERLYING,
"WRONG_UNDERLYING"
);
// Store the strategy as trusted.
getStrategyData[strategy].trusted = true;
emit StrategyTrusted(msg.sender, strategy);
}
/// @notice Stores a strategy as untrusted, disabling it from being harvested.
/// @param strategy The strategy to make untrusted.
function distrustStrategy(Strategy strategy) external requiresAuth {
// Store the strategy as untrusted.
getStrategyData[strategy].trusted = false;
emit StrategyDistrusted(msg.sender, strategy);
}
/* //////////////////////////////////////////////////////////////
WITHDRAWAL STACK LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when a strategy is pushed to the withdrawal stack.
/// @param user The authorized user who triggered the push.
/// @param pushedStrategy The strategy pushed to the withdrawal stack.
event WithdrawalStackPushed(address indexed user, Strategy indexed pushedStrategy);
/// @notice Emitted when a strategy is popped from the withdrawal stack.
/// @param user The authorized user who triggered the pop.
/// @param poppedStrategy The strategy popped from the withdrawal stack.
event WithdrawalStackPopped(address indexed user, Strategy indexed poppedStrategy);
/// @notice Emitted when the withdrawal stack is updated.
/// @param user The authorized user who triggered the set.
/// @param replacedWithdrawalStack The new withdrawal stack.
event WithdrawalStackSet(address indexed user, Strategy[] replacedWithdrawalStack);
/// @notice Emitted when an index in the withdrawal stack is replaced.
/// @param user The authorized user who triggered the replacement.
/// @param index The index of the replaced strategy in the withdrawal stack.
/// @param replacedStrategy The strategy in the withdrawal stack that was replaced.
/// @param replacementStrategy The strategy that overrode the replaced strategy at the index.
event WithdrawalStackIndexReplaced(
address indexed user,
uint256 index,
Strategy indexed replacedStrategy,
Strategy indexed replacementStrategy
);
/// @notice Emitted when an index in the withdrawal stack is replaced with the tip.
/// @param user The authorized user who triggered the replacement.
/// @param index The index of the replaced strategy in the withdrawal stack.
/// @param replacedStrategy The strategy in the withdrawal stack replaced by the tip.
/// @param previousTipStrategy The previous tip of the stack that replaced the strategy.
event WithdrawalStackIndexReplacedWithTip(
address indexed user,
uint256 index,
Strategy indexed replacedStrategy,
Strategy indexed previousTipStrategy
);
/// @notice Emitted when the strategies at two indexes are swapped.
/// @param user The authorized user who triggered the swap.
/// @param index1 One index involved in the swap
/// @param index2 The other index involved in the swap.
/// @param newStrategy1 The strategy (previously at index2) that replaced index1.
/// @param newStrategy2 The strategy (previously at index1) that replaced index2.
event WithdrawalStackIndexesSwapped(
address indexed user,
uint256 index1,
uint256 index2,
Strategy indexed newStrategy1,
Strategy indexed newStrategy2
);
/// @dev Withdraw a specific amount of underlying tokens from strategies in the withdrawal stack.
/// @param underlyingAmount The amount of underlying tokens to pull into float.
/// @dev Automatically removes depleted strategies from the withdrawal stack.
function pullFromWithdrawalStack(uint256 underlyingAmount) internal {
// We will update this variable as we pull from strategies.
uint256 amountLeftToPull = underlyingAmount;
// We'll start at the tip of the stack and traverse backwards.
uint256 currentIndex = withdrawalStack.length - 1;
// Iterate in reverse so we pull from the stack in a "last in, first out" manner.
// Will revert due to underflow if we empty the stack before pulling the desired amount.
for (; ; currentIndex--) {
// Get the strategy at the current stack index.
Strategy strategy = withdrawalStack[currentIndex];
// Get the balance of the strategy before we withdraw from it.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy is currently untrusted or was already depleted:
if (!getStrategyData[strategy].trusted || strategyBalance == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
// Move onto the next strategy.
continue;
}
// We want to pull as much as we can from the strategy, but no more than we need.
uint256 amountToPull = strategyBalance > amountLeftToPull ? amountLeftToPull : strategyBalance;
unchecked {
// Compute the balance of the strategy that will remain after we withdraw.
// Cannot underflow as we cap the amount to pull at the strategy's balance.
uint256 strategyBalanceAfterWithdrawal = strategyBalance - amountToPull;
// Without this the next harvest would count the withdrawal as a loss.
getStrategyData[strategy].balance = strategyBalanceAfterWithdrawal.safeCastTo248();
// Adjust our goal based on how much we can pull from the strategy.
// Cannot underflow as we cap the amount to pull at the amount left to pull.
amountLeftToPull -= amountToPull;
emit StrategyWithdrawal(msg.sender, strategy, amountToPull);
// Withdraw from the strategy and revert if returns an error code.
require(strategy.redeemUnderlying(amountToPull) == 0, "REDEEM_FAILED");
// If we fully depleted the strategy:
if (strategyBalanceAfterWithdrawal == 0) {
// Remove it from the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, strategy);
}
}
// If we've pulled all we need, exit the loop.
if (amountLeftToPull == 0) break;
}
unchecked {
// Account for the withdrawals done in the loop above.
// Cannot underflow as the balances of some strategies cannot exceed the sum of all.
totalStrategyHoldings -= underlyingAmount;
}
// Cache the Vault's balance of ETH.
uint256 ethBalance = address(this).balance;
// If the Vault's underlying token is WETH compatible and we have some ETH, wrap it into WETH.
if (ethBalance != 0 && underlyingIsWETH) WETH(payable(address(UNDERLYING))).deposit{value: ethBalance}();
}
/// @notice Pushes a single strategy to front of the withdrawal stack.
/// @param strategy The strategy to be inserted at the front of the withdrawal stack.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function pushToWithdrawalStack(Strategy strategy) external requiresAuth {
// Ensure pushing the strategy will not cause the stack exceed its limit.
require(withdrawalStack.length < MAX_WITHDRAWAL_STACK_SIZE, "STACK_FULL");
// Push the strategy to the front of the stack.
withdrawalStack.push(strategy);
emit WithdrawalStackPushed(msg.sender, strategy);
}
/// @notice Removes the strategy at the tip of the withdrawal stack.
/// @dev Be careful, another authorized user could push a different strategy
/// than expected to the stack while a popFromWithdrawalStack transaction is pending.
function popFromWithdrawalStack() external requiresAuth {
// Get the (soon to be) popped strategy.
Strategy poppedStrategy = withdrawalStack[withdrawalStack.length - 1];
// Pop the first strategy in the stack.
withdrawalStack.pop();
emit WithdrawalStackPopped(msg.sender, poppedStrategy);
}
/// @notice Sets a new withdrawal stack.
/// @param newStack The new withdrawal stack.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function setWithdrawalStack(Strategy[] calldata newStack) external requiresAuth {
// Ensure the new stack is not larger than the maximum stack size.
require(newStack.length <= MAX_WITHDRAWAL_STACK_SIZE, "STACK_TOO_BIG");
// Replace the withdrawal stack.
withdrawalStack = newStack;
emit WithdrawalStackSet(msg.sender, newStack);
}
/// @notice Replaces an index in the withdrawal stack with another strategy.
/// @param index The index in the stack to replace.
/// @param replacementStrategy The strategy to override the index with.
/// @dev Strategies that are untrusted, duplicated, or have no balance are
/// filtered out when encountered at withdrawal time, not validated upfront.
function replaceWithdrawalStackIndex(uint256 index, Strategy replacementStrategy) external requiresAuth {
// Get the (soon to be) replaced strategy.
Strategy replacedStrategy = withdrawalStack[index];
// Update the index with the replacement strategy.
withdrawalStack[index] = replacementStrategy;
emit WithdrawalStackIndexReplaced(msg.sender, index, replacedStrategy, replacementStrategy);
}
/// @notice Moves the strategy at the tip of the stack to the specified index and pop the tip off the stack.
/// @param index The index of the strategy in the withdrawal stack to replace with the tip.
function replaceWithdrawalStackIndexWithTip(uint256 index) external requiresAuth {
// Get the (soon to be) previous tip and strategy we will replace at the index.
Strategy previousTipStrategy = withdrawalStack[withdrawalStack.length - 1];
Strategy replacedStrategy = withdrawalStack[index];
// Replace the index specified with the tip of the stack.
withdrawalStack[index] = previousTipStrategy;
// Remove the now duplicated tip from the array.
withdrawalStack.pop();
emit WithdrawalStackIndexReplacedWithTip(msg.sender, index, replacedStrategy, previousTipStrategy);
}
/// @notice Swaps two indexes in the withdrawal stack.
/// @param index1 One index involved in the swap
/// @param index2 The other index involved in the swap.
function swapWithdrawalStackIndexes(uint256 index1, uint256 index2) external requiresAuth {
// Get the (soon to be) new strategies at each index.
Strategy newStrategy2 = withdrawalStack[index1];
Strategy newStrategy1 = withdrawalStack[index2];
// Swap the strategies at both indexes.
withdrawalStack[index1] = newStrategy1;
withdrawalStack[index2] = newStrategy2;
emit WithdrawalStackIndexesSwapped(msg.sender, index1, index2, newStrategy1, newStrategy2);
}
/* //////////////////////////////////////////////////////////////
SEIZE STRATEGY LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after a strategy is seized.
/// @param user The authorized user who triggered the seize.
/// @param strategy The strategy that was seized.
event StrategySeized(address indexed user, Strategy indexed strategy);
/// @notice Seizes a strategy.
/// @param strategy The strategy to seize.
/// @dev Intended for use in emergencies or other extraneous situations where the
/// strategy requires interaction outside of the Vault's standard operating procedures.
function seizeStrategy(Strategy strategy) external requiresAuth {
// Get the strategy's last reported balance of underlying tokens.
uint256 strategyBalance = getStrategyData[strategy].balance;
// If the strategy's balance exceeds the Vault's current
// holdings, instantly unlock any remaining locked profit.
if (strategyBalance > totalHoldings()) maxLockedProfit = 0;
// Set the strategy's balance to 0.
getStrategyData[strategy].balance = 0;
unchecked {
// Decrease totalStrategyHoldings to account for the seize.
// Cannot underflow as the balance of one strategy will never exceed the sum of all.
totalStrategyHoldings -= strategyBalance;
}
emit StrategySeized(msg.sender, strategy);
// Transfer all of the strategy's tokens to the caller.
ERC20(strategy).safeTransfer(msg.sender, strategy.balanceOf(address(this)));
}
/* //////////////////////////////////////////////////////////////
FEE CLAIM LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted after fees are claimed.
/// @param user The authorized user who claimed the fees.
/// @param avTokenAmount The amount of avTokens that were claimed.
event FeesClaimed(address indexed user, uint256 avTokenAmount);
/// @notice Claims fees accrued from harvests.
/// @param avTokenAmount The amount of avTokens to claim.
/// @dev Accrued fees are measured as avTokens held by the Vault.
function claimFees(uint256 avTokenAmount) external requiresAuth {
emit FeesClaimed(msg.sender, avTokenAmount);
// Transfer the provided amount of avTokens to the caller.
ERC20(this).safeTransfer(msg.sender, avTokenAmount);
}
/* //////////////////////////////////////////////////////////////
INITIALIZATION AND DESTRUCTION LOGIC
///////////////////////////////////////////////////////////// */
/// @notice Emitted when the Vault is initialized.
/// @param user The authorized user who triggered the initialization.
event Initialized(address indexed user);
/// @notice Whether the Vault has been initialized yet.
/// @dev Can go from false to true, never from true to false.
bool public isInitialized;
/// @notice Initializes the Vault, enabling it to receive deposits.
/// @dev All critical parameters must already be set before calling.
function initialize() external requiresAuth {
// Ensure the Vault has not already been initialized.
require(!isInitialized, "ALREADY_INITIALIZED");
// Mark the Vault as initialized.
isInitialized = true;
// Open for deposits.
totalSupply = 0;
emit Initialized(msg.sender);
}
/// @notice Self destructs a Vault, enabling it to be redeployed.
/// @dev Caller will receive any ETH held as float in the Vault.
function destroy() external requiresAuth {
selfdestruct(payable(msg.sender));
}
/* //////////////////////////////////////////////////////////////
RECIEVE ETHER LOGIC
///////////////////////////////////////////////////////////// */
/// @dev Required for the Vault to receive unwrapped ETH.
receive() external payable {}
}
|
If the strategy registered a net loss we don't have any new profit.
|
: 0;
| 314,847 |
[
1,
2047,
326,
6252,
4104,
279,
2901,
8324,
732,
2727,
1404,
1240,
1281,
394,
450,
7216,
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
] |
[
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,
10792,
294,
374,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x44C696287E1FC316CAc9C34FbD9e0F64de41A02d/sources/contracts/Farming.sol
|
* @notice withdraw If amount is zero, it will claim pending rewards If amount is not zero, it will withdraw and reset unlock time @param _pid {uint256} Pool Id @param _amount {uint256} Amount of token to withdraw/
|
function withdraw(
uint256 _pid,
uint256 _amount
) external nonReentrant whenNotPaused validatePoolByPid(_pid) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
uint256 feeAmount;
if (block.timestamp < user.lastClaim + pool.lockupDuration) {
feeAmount = (_amount * earlyWithdrawFee) / FEE_MULTIPLIER;
}
updatePool(_pid);
uint256 pending = (user.amount * pool.accTokenPerShare) /
SHARE_MULTIPLIER -
user.rewardDebt;
if (pending > 0) {
user.pendingRewards += pending;
uint256 claimedAmount = safeTokenTransfer(msg.sender, user.pendingRewards);
emit Claim(msg.sender, _pid, claimedAmount);
user.pendingRewards -= claimedAmount;
}
if (_amount > 0) {
user.amount -= _amount;
user.lastClaim = block.timestamp;
pool.lpToken.safeTransfer(address(msg.sender), _amount - feeAmount);
if (feeAmount > 0) {
pool.lpToken.safeTransfer(treasury, feeAmount);
}
pool.amount -= _amount;
}
user.rewardDebt = (user.amount * pool.accTokenPerShare) / SHARE_MULTIPLIER;
emit Withdraw(msg.sender, _pid, _amount);
}
| 8,305,560 |
[
1,
1918,
9446,
971,
3844,
353,
3634,
16,
518,
903,
7516,
4634,
283,
6397,
971,
3844,
353,
486,
3634,
16,
518,
903,
598,
9446,
471,
2715,
7186,
813,
225,
389,
6610,
1377,
288,
11890,
5034,
97,
282,
8828,
3124,
225,
389,
8949,
282,
288,
11890,
5034,
97,
282,
16811,
434,
1147,
358,
598,
9446,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
598,
9446,
12,
203,
3639,
2254,
5034,
389,
6610,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
3903,
1661,
426,
8230,
970,
1347,
1248,
28590,
1954,
2864,
858,
12478,
24899,
6610,
13,
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,
203,
3639,
2583,
12,
1355,
18,
8949,
1545,
389,
8949,
16,
315,
1918,
9446,
30,
486,
7494,
8863,
203,
203,
3639,
2254,
5034,
14036,
6275,
31,
203,
3639,
309,
261,
2629,
18,
5508,
411,
729,
18,
2722,
9762,
397,
2845,
18,
739,
416,
5326,
13,
288,
203,
5411,
14036,
6275,
273,
261,
67,
8949,
380,
11646,
1190,
9446,
14667,
13,
342,
478,
9383,
67,
24683,
2053,
654,
31,
203,
3639,
289,
203,
203,
3639,
1089,
2864,
24899,
6610,
1769,
203,
203,
3639,
2254,
5034,
4634,
273,
261,
1355,
18,
8949,
380,
2845,
18,
8981,
1345,
2173,
9535,
13,
342,
203,
5411,
6122,
9332,
67,
24683,
2053,
654,
300,
203,
5411,
729,
18,
266,
2913,
758,
23602,
31,
203,
3639,
309,
261,
9561,
405,
374,
13,
288,
203,
5411,
729,
18,
9561,
17631,
14727,
1011,
4634,
31,
203,
5411,
2254,
5034,
7516,
329,
6275,
273,
4183,
1345,
5912,
12,
3576,
18,
15330,
16,
729,
18,
9561,
17631,
14727,
1769,
203,
5411,
3626,
18381,
12,
3576,
18,
15330,
16,
389,
6610,
16,
7516,
329,
6275,
1769,
203,
5411,
729,
18,
9561,
17631,
14727,
3947,
7516,
329,
6275,
31,
203,
3639,
2
] |
./full_match/80001/0x8E4087D188338E9516cd050e4d606C24c89e7dEb/sources/contracts/Contract.sol
|
* @dev List of abilities: 16 - Ability to execute transfer./* @dev Error constants./* @dev Calls into ERC20 Token contract, invoking transferFrom. @param _target Address of token to transfer. @param _a Address to transfer token from. @param _b Address to transfer token to. @param _c Amount of token to transfer./
|
{
require(
ERC20(_target).transferFrom(_a, _b, _c),
TRANSFER_FAILED
);
}
| 9,491,195 |
[
1,
682,
434,
1223,
5076,
30,
2872,
300,
9771,
1889,
358,
1836,
7412,
18,
19,
225,
1068,
6810,
18,
19,
225,
23665,
1368,
4232,
39,
3462,
3155,
6835,
16,
15387,
7412,
1265,
18,
225,
389,
3299,
5267,
434,
1147,
358,
7412,
18,
225,
389,
69,
5267,
358,
7412,
1147,
628,
18,
225,
389,
70,
5267,
358,
7412,
1147,
358,
18,
225,
389,
71,
16811,
434,
1147,
358,
7412,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
225,
288,
203,
565,
2583,
12,
203,
1377,
4232,
39,
3462,
24899,
3299,
2934,
13866,
1265,
24899,
69,
16,
389,
70,
16,
389,
71,
3631,
203,
1377,
4235,
17598,
67,
11965,
203,
565,
11272,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.